<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="top"
      class="customer-form"
      :disabled="isDetailMode"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="客户组" prop="customerGroup">
            <el-input v-model="formData.customerGroup" placeholder="请输入客户组" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="客户SAP编码" prop="customerSapCode">
            <el-select
              v-model="formData.customerSapCode"
              placeholder="请选择客户SAP编码"
              filterable
              remote
              :remote-method="searchCustomerCode"
              :loading="customerCodeLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in customerCodeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="客户备注" prop="customerName">
            <el-input v-model="formData.customerName" placeholder="请输入客户备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer v-if="!isDetailMode">
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          保存
        </el-button>
      </div>
    </template>

    <template #footer v-else>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import { getCustomerCodeList } from '@/api/print/customerGroup'
interface CustomerFormData {
  id?: number
  customerGroup: string
  customerSapCode: string
  customerName: string
}

interface Props {
  visible: boolean
  mode: 'add' | 'edit' | 'detail'
  data?: CustomerFormData
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': [type: 'save', data: CustomerFormData]
}>()

// 表单引用
const formRef = ref()

// 弹窗可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 弹窗标题
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'add':
      return '新增客户组'
    case 'edit':
      return '编辑客户组'
    case 'detail':
      return '客户组详情'
    default:
      return '客户组信息'
  }
})

// 是否为详情模式
const isDetailMode = computed(() => props.mode === 'detail')

// 提交加载状态
const submitLoading = ref(false)

// 客户SAP编码下拉框相关
const customerCodeOptions = ref<{ value: string; label: string }[]>([])
const customerCodeLoading = ref(false)

// 搜索客户编码
const searchCustomerCode = async (keyword: string) => {
  customerCodeLoading.value = true
  try {
    const res = await getCustomerCodeList({ keyword })
    console.log('--------searchCustomerCode---------', searchCustomerCode)
    if (res && res.length > 0) {
      customerCodeOptions.value = res.map((item: any) => ({
        value: item,
        label: item
      }))
    }
  } catch (error) {
    console.error('搜索客户编码失败:', error)
    customerCodeOptions.value = []
  } finally {
    customerCodeLoading.value = false
  }
}

// 表单数据
const formData = reactive<CustomerFormData>({
  id: undefined,
  customerGroup: '',
  customerSapCode: '',
  customerName: ''
})

// 表单验证规则
const formRules = {
  customerGroup: [{ required: true, message: '请输入客户组', trigger: 'blur' }],
  customerSapCode: [{ required: true, message: '请输入客户SAP编码', trigger: 'blur' }],
  customerName: [{ required: false, message: '请输入客户备注', trigger: 'blur' }]
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    customerGroup: '',
    customerSapCode: '',
    customerName: ''
  })
  customerCodeOptions.value = []
  formRef.value?.clearValidate()
}

// 初始化表单数据
const initFormData = () => {
  resetForm()
  
  if (props.data) {
    Object.assign(formData, props.data)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true
    emit('success', 'save', { ...formData })
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  resetForm()
}

// 监听弹窗显示变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initFormData()
  }
})
</script>

<style scoped>
.customer-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 8px 16px;
  font-weight: 500;
}
</style>