<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
      v-loading="formLoading"
    >
      <!-- 客户基本信息 -->
      <el-divider content-position="left">客户信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-select
              v-model="formData.customerName"
              placeholder="请选择客户"
              clearable
              filterable
              @change="handleCustomerChange"
            >
              <el-option
                v-for="customer in customerList"
                :key="customer.id"
                :label="customer.name"
                :value="customer.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contactInfo">
            <el-input v-model="formData.contactInfo" placeholder="请输入联系方式" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户类型" prop="customerType">
            <el-select v-model="formData.customerType" placeholder="请选择客户类型" clearable>
              <el-option
                v-for="item in customerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户用途" prop="customerUsage">
            <el-input v-model="formData.customerUsage" placeholder="请输入客户用途" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 产品信息 -->
      <el-divider content-position="left">产品信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="formData.productName" placeholder="请输入产品名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品评价" prop="productEvaluation">
            <el-input
              v-model="formData.productEvaluation"
              placeholder="请输入产品评价"
              type="textarea"
              :rows="2"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 服务评价 -->
      <el-divider content-position="left">服务评价</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="采购意愿" prop="repurchaseIntention">
            <el-select v-model="formData.repurchaseIntention" placeholder="请选择采购意愿" clearable>
              <el-option
                v-for="item in repurchaseOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="服务评分" prop="serviceRating">
            <el-rate
              v-model="formData.serviceRating"
              :max="5"
              :allow-half="false"
              :show-text="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">
        确定
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { AfterSalesVisitApi, AfterSalesVisit } from '@/api/erp/aftersale/aftersalesvisit'
import { CustomerApi, CustomerVO } from '@/api/erp/sale/customer'

/** 售后回访 表单 */
defineOptions({ name: 'AfterSalesVisitForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerName: undefined,
  contactInfo: undefined,
  customerUsage: undefined,
  productName: undefined,
  productEvaluation: undefined,
  customerType: undefined,
  repurchaseIntention: undefined,
  serviceRating: undefined
})

// 客户类型选项
const customerTypeOptions = [
  { value: 'large_food_factory', label: '大型食品厂' },
  { value: 'small_food_factory', label: '中小型加工厂' },
  { value: 'distributor', label: '经销商' },
  { value: 'catering_chain', label: '餐饮连锁' },
  { value: 'government_unit', label: '机关单位' },
  { value: 'other', label: '其他' }
]

// 重复采购意愿选项
const repurchaseOptions = [
  { value: 'definitely', label: '一定会' },
  { value: 'probably', label: '应该会' },
  { value: 'uncertain', label: '不确定' },
  { value: 'unlikely', label: '可能不会' },
  { value: 'never', label: '肯定不会' }
]

const formRules = reactive({
  customerName: [
    { required: true, message: '客户名称不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '客户名称长度应在2-50字符之间', trigger: 'blur' }
  ],
  contactInfo: [
    { required: true, message: '联系方式不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '产品名称不能为空', trigger: 'blur' },
    { min: 1, max: 100, message: '产品名称长度应在1-100字符之间', trigger: 'blur' }
  ],
  customerType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
  repurchaseIntention: [{ required: true, message: '请选择采购意愿', trigger: 'change' }],
  serviceRating: [
    { required: true, message: '请给出服务评分', trigger: 'change' },
    { type: 'number', min: 0, max: 5, message: '评分应在0-5之间', trigger: 'change' }
  ]
})
const formRef = ref() // 表单 Ref
const customerList = ref<CustomerVO[]>([]) // 客户列表

/** 加载客户列表 */
const loadCustomerList = async () => {
  try {
    const data = await CustomerApi.getCustomerSimpleList()
    customerList.value = data
  } catch (error) {
    console.error('加载客户列表失败:', error)
  }
}

/** 处理客户选择 */
const handleCustomerChange = (customerName: string) => {
  if (!customerName) {
    formData.value.contactInfo = ''
    return
  }
  const selectedCustomer = customerList.value.find(customer => customer.name === customerName)
  if (selectedCustomer) {
    // 自动填充联系方式，优先使用手机号，其次电话
    formData.value.contactInfo = selectedCustomer.mobile || selectedCustomer.telephone || ''
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AfterSalesVisitApi.getAfterSalesVisit(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as AfterSalesVisit
    if (formType.value === 'create') {
      await AfterSalesVisitApi.createAfterSalesVisit(data)
      message.success(t('common.createSuccess'))
    } else {
      await AfterSalesVisitApi.updateAfterSalesVisit(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerName: undefined,
    contactInfo: undefined,
    customerUsage: undefined,
    productName: undefined,
    productEvaluation: undefined,
    customerType: undefined,
    repurchaseIntention: undefined,
    serviceRating: undefined
  }
  formRef.value?.resetFields()
}

/** 初始化 */
onMounted(() => {
  loadCustomerList()
})
</script>
