<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="140px">
    <el-row :gutter="24">
      <el-col :span="8" class="mb20">
        <el-form-item label="项目名称">
          <el-input :model-value="projectName || form.projectName" readonly placeholder="-" />
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20">
        <el-form-item label="需求部门">
          <el-input :model-value="deptName || form.deptName" readonly placeholder="-" />
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20">
        <el-form-item label="是否签订合同" prop="hasContract">
          <el-radio-group v-model="form.hasContract">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20" v-if="form.hasContract === '1'">
        <el-form-item label="合同" prop="contractId">
          <el-input v-model="form.contractId" placeholder="请选择合同（待对接合同接口）" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20">
        <el-form-item label="是否分期验收" prop="isInstallment">
          <el-radio-group v-model="form.isInstallment">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20" v-if="form.isInstallment === '1'">
        <el-form-item label="分期次数" prop="totalPhases">
          <el-input-number v-model="form.totalPhases" :min="1" :max="99" placeholder="请输入" style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="选择合同后自动带出" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20">
        <el-form-item label="供应商联系人及电话" prop="supplierContact">
          <el-input v-model="form.supplierContact" placeholder="请输入" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20">
        <el-form-item label="采购人员" prop="purchaserId">
          <org-selector v-model:orgList="purchaserList" type="user" :multiple="false" @update:orgList="onPurchaserChange" />
        </el-form-item>
      </el-col>
      <el-col :span="8" class="mb20">
        <el-form-item label="资产管理员" prop="assetAdminId">
          <org-selector v-model:orgList="assetAdminList" type="user" :multiple="false" @update:orgList="onAssetAdminChange" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const props = defineProps<{
  modelValue: Record<string, any>
  projectName?: string
  deptName?: string
  /** 每次打开弹窗时变化，用于强制重置内部 form */
  resetKey?: number
}>()

const emit = defineEmits(['update:modelValue'])

const formRef = ref<FormInstance>()
const purchaserList = ref<any[]>([])
const assetAdminList = ref<any[]>([])

const form = reactive({
  hasContract: '0',
  contractId: '',
  isInstallment: '0',
  totalPhases: 1,
  supplierName: '',
  supplierContact: '',
  purchaserId: '',
  purchaserName: '',
  assetAdminId: '',
  assetAdminName: '',
  ...props.modelValue,
})

const syncFormFromModel = (val: Record<string, any> | undefined) => {
  Object.assign(form, val || {})
  if (form.purchaserId && form.purchaserName) {
    purchaserList.value = [{ id: form.purchaserId, name: form.purchaserName, type: 'user' }]
  } else {
    purchaserList.value = []
  }
  if (form.assetAdminId && form.assetAdminName) {
    assetAdminList.value = [{ id: form.assetAdminId, name: form.assetAdminName, type: 'user' }]
  } else {
    assetAdminList.value = []
  }
}

watch(() => props.modelValue, syncFormFromModel, { deep: true, immediate: true })
// resetKey 变化时强制用 modelValue 覆盖内部 form
watch(() => props.resetKey, () => syncFormFromModel(props.modelValue))
watch(form, () => emit('update:modelValue', { ...form }), { deep: true })

const onPurchaserChange = (list: any[]) => {
  if (list?.length) {
    const u = list[0]
    form.purchaserId = u.userId || u.id || ''
    form.purchaserName = u.name || u.realName || ''
  } else {
    form.purchaserId = ''
    form.purchaserName = ''
  }
}

const onAssetAdminChange = (list: any[]) => {
  if (list?.length) {
    const u = list[0]
    form.assetAdminId = u.userId || u.id || ''
    form.assetAdminName = u.name || u.realName || ''
  } else {
    form.assetAdminId = ''
    form.assetAdminName = ''
  }
}

const rules: FormRules = {
  isInstallment: [{ required: true, message: '请选择是否分期验收', trigger: 'change' }],
  totalPhases: [{ required: true, message: '请输入分期次数', trigger: 'blur' }],
}

const validate = () => formRef.value?.validate()

defineExpose({ validate, form })
</script>

<style scoped>
.mb20 {
  margin-bottom: 20px;
}
</style>
