<template>
  <a-modal
    v-model:visible="visible"
    :title="supplierData ? '编辑供应商' : '新增供应商'"
    :width="700"
    :mask-closable="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
      :label-col-style="{ fontWeight: 'bold' }"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="供应商名称"
            field="supplierName"
            :required="true"
          >
            <a-input
              v-model="formData.supplierName"
              placeholder="请输入供应商名称"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="供应商类型"
            field="supplierType"
            :required="true"
          >
            <a-select
              v-model="formData.supplierType"
              placeholder="请选择供应商类型"
              allow-clear
            >
              <a-option value="equipment">设备供应商</a-option>
              <a-option value="material">材料供应商</a-option>
              <a-option value="service">服务供应商</a-option>
              <a-option value="comprehensive">综合供应商</a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="联系人"
            field="contactPerson"
            :required="true"
          >
            <a-input
              v-model="formData.contactPerson"
              placeholder="请输入联系人"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="联系电话"
            field="contactPhone"
            :required="true"
          >
            <a-input
              v-model="formData.contactPhone"
              placeholder="请输入联系电话"
              allow-clear
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="邮箱地址"
            field="email"
          >
            <a-input
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="信用等级"
            field="creditRating"
          >
            <a-rate
              v-model="formData.creditRating"
              :count="5"
              show-score
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item
            label="合作状态"
            field="cooperationStatus"
            :required="true"
          >
            <a-select
              v-model="formData.cooperationStatus"
              placeholder="请选择合作状态"
              allow-clear
            >
              <a-option value="cooperating">合作中</a-option>
              <a-option value="paused">暂停合作</a-option>
              <a-option value="terminated">终止合作</a-option>
              <a-option value="evaluating">待评估</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="合作开始日期"
            field="cooperationStartDate"
          >
            <a-date-picker
              v-model="formData.cooperationStartDate"
              style="width: 100%"
              placeholder="请选择合作开始日期"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item
        label="公司地址"
        field="address"
      >
        <a-textarea
          v-model="formData.address"
          placeholder="请输入公司地址"
          :max-length="200"
          show-word-limit
          :rows="3"
        />
      </a-form-item>

      <a-form-item
        label="经营范围"
        field="businessScope"
      >
        <a-textarea
          v-model="formData.businessScope"
          placeholder="请输入经营范围"
          :max-length="500"
          show-word-limit
          :rows="3"
        />
      </a-form-item>

      <a-form-item
        label="备注"
        field="remark"
      >
        <a-textarea
          v-model="formData.remark"
          placeholder="请输入备注信息"
          :max-length="300"
          show-word-limit
          :rows="3"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue'

interface Props {
  visible: boolean
  supplierData?: any | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  supplierData: null,
})

const emit = defineEmits<Emits>()

// Form ref
const formRef = ref<FormInstance>()
const loading = ref(false)

// Form data
const formData = reactive({
  supplierName: '',
  supplierType: '',
  contactPerson: '',
  contactPhone: '',
  email: '',
  creditRating: 3,
  cooperationStatus: '',
  cooperationStartDate: '',
  address: '',
  businessScope: '',
  remark: '',
})

// Form rules
const rules = {
  supplierName: [
    { required: true, message: '请输入供应商名称' },
  ],
  supplierType: [
    { required: true, message: '请选择供应商类型' },
  ],
  contactPerson: [
    { required: true, message: '请输入联系人' },
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址' },
  ],
  cooperationStatus: [
    { required: true, message: '请选择合作状态' },
  ],
}

// Watch visible prop
const visible = ref(props.visible)
watch(() => props.visible, (newVal) => {
  visible.value = newVal
  if (newVal && props.supplierData) {
    initFormData()
  }
})

watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

// Initialize form data
const initFormData = () => {
  if (props.supplierData) {
    Object.assign(formData, {
      supplierName: props.supplierData.supplierName || '',
      supplierType: props.supplierData.supplierType || '',
      contactPerson: props.supplierData.contactPerson || '',
      contactPhone: props.supplierData.contactPhone || '',
      email: props.supplierData.email || '',
      creditRating: props.supplierData.creditRating || 3,
      cooperationStatus: props.supplierData.cooperationStatus || '',
      cooperationStartDate: props.supplierData.cooperationStartDate || '',
      address: props.supplierData.address || '',
      businessScope: props.supplierData.businessScope || '',
      remark: props.supplierData.remark || '',
    })
  }
}

// Handle OK
const handleOk = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) {
      loading.value = true
      // 这里调用保存API
      await new Promise((resolve) => setTimeout(resolve, 1000))
      Message.success(props.supplierData ? '更新成功' : '创建成功')
      emit('success')
      handleCancel()
    }
  } catch (error) {
    console.error('保存失败:', error)
    Message.error('保存失败')
  } finally {
    loading.value = false
  }
}

// Handle Cancel
const handleCancel = () => {
  visible.value = false
  resetForm()
}

// Reset form
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    supplierName: '',
    supplierType: '',
    contactPerson: '',
    contactPhone: '',
    email: '',
    creditRating: 3,
    cooperationStatus: '',
    cooperationStartDate: '',
    address: '',
    businessScope: '',
    remark: '',
  })
}
</script>

<style scoped>
:deep(.arco-form-item-label) {
  font-weight: 500;
}
</style>
