<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-select
            v-model="form.contractId"
            placeholder="请选择合同"
            clearable
            filterable
            style="width: 100%"
            :loading="contractLoading"
            @visible-change="onContractSelectVisibleChange"
          >
            <el-option
              v-for="item in contractOptions"
              :key="item.id"
              :label="item.contractName || item.contractNo || item.id"
              :value="item.id"
            />
          </el-select>
        </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, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getContracts } from '/@/api/finance/purchasingrequisition'

const props = defineProps<{
  modelValue: Record<string, any>
  projectName?: string
  deptName?: string
  /** 采购申请ID，用于拉取合同列表 */
  purchaseId?: string | number
  /** 每次打开弹窗时变化，用于强制重置内部 form */
  resetKey?: number
}>()

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

const formRef = ref<FormInstance>()
const purchaserList = ref<any[]>([])
const assetAdminList = ref<any[]>([])
const contractOptions = ref<any[]>([])
const contractLoading = ref(false)
const contractLoaded = ref(false)

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 = []
  }
}

const loadContractOptions = async () => {
  if (contractLoaded.value || contractLoading.value) return
  contractLoading.value = true
  try {
    const res = await getContracts(props.purchaseId ? { id: props.purchaseId } : {})
    const list = res?.data
    contractOptions.value = Array.isArray(list) ? list : []
    contractLoaded.value = true
  } catch (_) {
    contractOptions.value = []
  } finally {
    contractLoading.value = false
  }
}

const onContractSelectVisibleChange = (visible: boolean) => {
  if (visible && form.hasContract === '1' && contractOptions.value.length === 0) {
    loadContractOptions()
  }
}

watch(() => props.modelValue, syncFormFromModel, { deep: true, immediate: true })
// resetKey 变化时强制用 modelValue 覆盖内部 form，并重置合同列表以便重新拉取
watch(() => props.resetKey, () => {
  syncFormFromModel(props.modelValue)
  contractLoaded.value = false
  contractOptions.value = []
})
watch(form, () => emit('update:modelValue', { ...form }), { deep: true })

watch(() => form.hasContract, (val) => {
  if (val === '1') {
    contractLoaded.value = false
    loadContractOptions()
  } else {
    contractOptions.value = []
    contractLoaded.value = false
  }
})

onMounted(() => {
  if (form.hasContract === '1') {
    loadContractOptions()
  }
})

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>
