<template>
  <div class="entity-report-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      :validate-on-rule-change="false"
    >
      <el-form-item label="打印规格：">
        <el-input
          v-model="formData.printCount"
          placeholder="一式几份，如：2"
          controls-position="right"
          class="!w-240px"
        />
      </el-form-item>
      <!-- 出具方式选择 -->
      <el-form-item label="出具方式：" prop="deliveryType" required>
        <el-radio-group v-model="formData.deliveryType" @change="handleDeliveryTypeChange">
          <el-radio
            v-for="(item, key) in PressureIssueReportEntityMethodMap"
            :key="Number(key)"
            :label="Number(key)"
            >{{ item }}</el-radio
          >
        </el-radio-group>
      </el-form-item>

      <!-- 快速邮寄表单 -->
      <template v-if="formData.deliveryType === PressureIssueReportEntityMethod.EXPRESS">
        <el-form-item label="收件人：" prop="recipient">
          <el-input
            :maxlength="10"
            v-model="formData.recipient"
            placeholder="请输入收件人姓名"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item label="收件人电话：" prop="recipientPhone">
          <el-input
            v-model="formData.recipientPhone"
            placeholder="请输入收件人电话"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item label="收件人地址：" prop="recipientAddress">
          <el-input
            v-model="formData.recipientAddress"
            type="textarea"
            :rows="2"
            placeholder="请输入收件人详细地址"
            class="!w-400px"
          />
        </el-form-item>

        <el-form-item label="邮寄单号：" prop="expressNo">
          <el-input v-model="formData.expressNo" placeholder="请输入邮寄单号" class="!w-240px" />
        </el-form-item>

        <el-form-item label="快递公司：" prop="expressCompany">
          <el-input
            v-model="formData.expressCompany"
            placeholder="请输入快递公司"
            class="!w-240px"
          />
        </el-form-item>

        <!-- 备注（只在快速邮寄时显示） -->
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入" class="!w-240px" />
        </el-form-item>
      </template>

      <!-- 业务员送达客户表单 -->
      <template v-if="formData.deliveryType === PressureIssueReportEntityMethod.DELIVERY">
        <el-form-item label="业务员：" prop="salesperson">
          <el-input
            v-model="formData.salespersonName"
            placeholder="请选择业务员"
            class="!w-240px"
            readonly
            @click="openUserSelectDialog"
          >
            <template #append>
              <el-button @click="openUserSelectDialog">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
      </template>

      <!-- 线下领取表单 -->
      <template v-if="formData.deliveryType === PressureIssueReportEntityMethod.PICKUP">
        <el-form-item label="领取人姓名：" prop="pickupPerson">
          <el-input
            v-model="formData.pickupPerson"
            placeholder="请输入领取人姓名"
            class="!w-240px"
          />
        </el-form-item>

        <el-form-item label="领取人电话：" prop="pickupPhone">
          <el-input
            v-model="formData.pickupPhone"
            placeholder="请输入领取人电话"
            class="!w-240px"
          />
        </el-form-item>
      </template>

      <!-- 其他方式表单 -->
      <template v-if="formData.deliveryType === PressureIssueReportEntityMethod.OTHER">
        <el-form-item label="其他方式说明：" prop="otherDescription">
          <el-input
            v-model="formData.otherDescription"
            type="textarea"
            :rows="3"
            placeholder="请输入"
            class="!w-400px"
          />
        </el-form-item>
      </template>
    </el-form>

    <!-- 业务员选择对话框 -->
    <UserSelectForm ref="userSelectFormRef" @confirm="handleUserSelect" :single="true" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import UserSelectForm from '@/components/UserSelectForm/index.vue'
import {
  PressureIssueReportEntityMethod,
  PressureIssueReportEntityMethodMap
} from '@/utils/constants'

const props = defineProps<{
  modelValue: any
  isPartReport: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: any]
  'validate-change': [valid: boolean]
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<any>({
  printCount: '',
  deliveryType: Number(PressureIssueReportEntityMethod.EXPRESS), // 默认为快速邮寄
  recipient: '',
  recipientPhone: '',
  recipientAddress: '',
  expressNo: '',
  expressCompany: '',
  salesperson: '', // 业务员ID
  salespersonName: '', // 业务员姓名（用于显示）
  pickupPerson: '',
  pickupPhone: '',
  otherDescription: '',
  remark: ''
})

// 表单验证规则 - 只在提交时验证，不设置实时验证触发器
const formRules = computed((): FormRules<any> => {
  const rules: FormRules<any> = {
    deliveryType: [{ required: true, message: '请选择出具方式' }]
  }

  // 根据出具方式动态添加验证规则（不设置trigger，只在手动验证时触发）
  if (formData.deliveryType === PressureIssueReportEntityMethod.EXPRESS) {
    rules.recipient = [{ required: true, message: '请输入收件人姓名' }]
    rules.recipientPhone = [
      { required: true, message: '请输入收件人电话' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
    ]
    rules.recipientAddress = [{ required: true, message: '请输入收件人地址' }]
  } else if (formData.deliveryType === PressureIssueReportEntityMethod.DELIVERY) {
    rules.salesperson = [{ required: true, message: '请选择业务员' }]
  } else if (formData.deliveryType === PressureIssueReportEntityMethod.PICKUP) {
    rules.pickupPerson = [{ required: true, message: '请输入领取人姓名' }]
    rules.pickupPhone = [
      { required: true, message: '请输入领取人电话' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
    ]
  } else if (formData.deliveryType === PressureIssueReportEntityMethod.OTHER) {
    rules.otherDescription = [{ required: true, message: '请输入其他方式说明' }]
  }

  return rules
})

// 监听props变化
watch(
  () => props.modelValue,
  (newValue) => {
    Object.assign(formData, newValue)
  },
  { immediate: true, deep: true }
)

// 监听formData变化，向外emit
watch(
  formData,
  (newValue) => {
    emit('update:modelValue', { ...newValue })
  },
  { deep: true }
)

// 出具方式变化处理
const handleDeliveryTypeChange = (value: number) => {
  // 清空其他字段
  const fieldsToReset = [
    'recipient',
    'recipientPhone',
    'recipientAddress',
    'expressNo',
    'expressCompany',
    'salesperson',
    'salespersonName',
    'pickupPerson',
    'pickupPhone',
    'otherDescription'
  ]

  fieldsToReset.forEach((field) => {
    if (field in formData) {
      ;(formData as any)[field] = ''
    }
  })

  // 清除验证错误（如果有的话）
  formRef.value?.clearValidate()
}

const userSelectFormRef = ref<InstanceType<typeof UserSelectForm>>()

// 打开用户选择对话框
const openUserSelectDialog = () => {
  userSelectFormRef.value?.open(formData.salesperson)
}

// 处理用户选择
const handleUserSelect = async (id: string, userList: any[]) => {
  if (userList && userList.length > 0) {
    formData.salesperson = userList[0].id?.toString() || ''
    formData.salespersonName = userList[0].nickname
  }
}

// 验证表单
const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false

  try {
    await formRef.value.validate()
    emit('validate-change', true)
    return true
  } catch (error) {
    emit('validate-change', false)
    return false
  }
}

// 重置表单
const resetFields = () => {
  formRef.value?.resetFields()
}

// 清除验证
const clearValidate = () => {
  formRef.value?.clearValidate()
}

// 暴露方法
defineExpose({
  validate,
  resetFields,
  clearValidate
})
</script>

<style lang="scss" scoped>
.entity-report-form {
  :deep(.el-form-item) {
    margin-bottom: 18px;
  }

  :deep(.el-radio-group) {
    .el-radio {
      margin-right: 24px;
      margin-bottom: 8px;
    }
  }
}
</style>
