<template>
  <div>
    <SearchBox ref="SearchBoxRef" formName="selectTop" :formData="query" @showPop="showPop" @reset="reset"></SearchBox>
    <ButtonBox @search="handleSearch" @add="insertDialog" @start="start('0')" @remove="shutdwon('1')" @edit="editDialog"></ButtonBox>
  </div>
  <div>
    <TableBox ref="TableBoxRef" :tableData="tableDate" @edit="handleEdit" @remove="handleRemove" :page="pageType" :url="url" :param="query"></TableBox>

    <FormBox ref="FormBoxRef" formName="input" :formData="form" :dialog="dialog" @save="handleSave" 
      @update:dialog="(val) => dialog = val" :title="dialogTitle"></FormBox>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import tools from '@/tools'
import ButtonBox from "@/components/ButtonBox.vue"
import SearchBox from "@/components/SearchBox.vue"
import FormBox from '@/components/FormBox.vue'
import TableBox from '@/components/TableBox.vue'

const { proxy } = getCurrentInstance()

// 查询参数
const query = ref({
  customerNm: ''
})

// 表单数据 - 确保包含所有动态配置的字段
const form = ref({
  id: '',
  customerNm: '',
  customerShortNm: '',
  contactPerson: '',
  contactInfo: '',
  defaultAddress: ''
})

// 控制弹窗显示
const dialog = ref(false)

// 弹窗标题
const dialogTitle = ref('新增客户')

// 表格相关配置
const url = ref('sto/Customer/query')
const tName = ref('sto_customer')
const pageType = ref(true)

// 组件引用
const TableBoxRef = ref(null)
const FormBoxRef = ref(null)

// 监听弹窗状态
watch(dialog, (newVal) => {
  console.log('弹窗状态变化:', newVal)
})

// ========== 弹窗相关方法 ==========

// 新增弹窗
const insertDialog = () => {
  console.log('打开新增弹窗')
  
  // 重置表单数据
  form.value = {
    id: '',
    customerNm: '',
    customerShortNm: '',
    contactPerson: '',
    contactInfo: '',
    defaultAddress: ''
  }
  
  dialogTitle.value = '新增客户'
  dialog.value = true
  
  console.log('dialog.value:', dialog.value)
  console.log('form.value:', form.value)
}

// 编辑弹窗（通过顶部按钮）
const editDialog = () => {
  if (TableBoxRef.value?.multipleSelection?.length > 0) {
    const selectedRow = TableBoxRef.value.multipleSelection[0]
    handleEdit(selectedRow)
  } else {
    ElMessage.warning('请先选择要编辑的行')
  }
}

// 表格行编辑（通过表格内的编辑按钮）
const handleEdit = (row) => {
  console.log('编辑行数据:', row)
  
  // 确保所有字段都有值
  form.value = {
    id: row.id || '',
    customerNm: row.customerNm || '',
    customerShortNm: row.customerShortNm || '',
    contactPerson: row.contactPerson || '',
    contactInfo: row.contactInfo || '',
    defaultAddress: row.defaultAddress || ''
  }
  
  dialogTitle.value = '编辑客户'
  dialog.value = true
  
  console.log('编辑弹窗已打开，form:', form.value)
}

// 保存表单
const handleSave = async (formData) => {
  try {
    const url = 'sto/Customer/save'
    var param = {
      json: JSON.stringify(formData),
    }
    console.log(JSON.stringify(formData))
    
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == 0) {
        ElMessage({
          message: '保存成功',
          type: 'success',
        })
        dialog.value = false
        handleSearch()
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败' + response.data.msg
        })
      }
    });
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
    console.error('保存失败:', error)
  }
}

// ========== 表格相关方法 ==========

// 搜索
const handleSearch = () => {
  //console.log('执行搜索')
  if (TableBoxRef.value?.search) {
    TableBoxRef.value.search()
  }
}

// 删除处理
const handleRemove = (row) => {
  var url = 'sto/Customer/remove'
  var param = {
    id: row.id
  }
  ElMessageBox.confirm(`确定删除客户 "${row.customerNm}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      proxy.$axios.get(url, param).then(response => {
        if (response.data.code == '0') {
          console.log(response.data.data)
          ElMessage({
            type: 'success',
            message: '删除成功！',
          });
          handleSearch()
        } else {
          ElMessage.error('操作失败！' + response.data.msg)
        }
      })
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    }
  })
}

// 行选择变化
const handleSelectionChange = (selectedRows) => {
  console.log('选中行:', selectedRows)
}

// ========== 其他方法 ==========

const reset = () => {
  query.value = { customerNm: '' }
  handleSearch()
}

const start = (type) => {
  console.log('启用操作:', type)
  // TODO: 实现启用逻辑
}

const shutdwon = (type) => {
  console.log('停用操作:', type)
  // TODO: 实现停用逻辑
}
</script>