<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="formData" class="-mt-10px">
      <el-table-column label="序号" type="index" width="100" />
       <el-table-column label="授权人姓名" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.customerContactId`" :rules="formRules.customerContactId" class="mb-0px!">
            <el-input v-model="row.customerContactId" placeholder="请输入客户联系人ID" />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column label="姓名" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.customerName`" :rules="formRules.customerName" class="mb-0px!">
            <el-input v-model="row.customerName" placeholder="请输入姓名" />
          </el-form-item>
        </template>
      </el-table-column> -->
      <el-table-column label="授权人类型" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.authPersonType`" :rules="formRules.authPersonType" class="mb-0px!">
            <el-select v-model="row.authPersonType" placeholder="请选择授权人类型">
              <el-option
                v-for="dict in getIntDictOptions('auth_person_type')"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="授权人手机号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.phoneNumber`" :rules="formRules.phoneNumber" class="mb-0px!">
            <el-input v-model="row.phoneNumber" placeholder="请输入手机号" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="微信号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.wechat`" :rules="formRules.wechat" class="mb-0px!">
            <el-input v-model="row.wechat" placeholder="请输入微信号" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.idNumber`" :rules="formRules.idNumber" class="mb-0px!">
            <el-input v-model="row.idNumber" placeholder="请输入身份证号" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="电子邮箱" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.email`" :rules="formRules.email" class="mb-0px!">
            <el-input v-model="row.email" placeholder="请输入电子邮箱" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60" v-if="!type">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-row justify="center" class="mt-3" v-if="!type">
    <el-button @click="handleAdd" round>+ 添加</el-button>
  </el-row>
  <!-- 表单弹窗：添加/修改 -->
  <ContactForm ref="contactRef" @success="getList" />
</template>
<script setup lang="ts">
import * as ContractApi from '@/api/crm/contract'
import { getIntDictOptions, getStrDictOptions, DICT_TYPE, getBoolDictOptions } from '@/utils/dict'
import ContactForm from '@/components/contact/index.vue'

const props = defineProps<{
  contractId: undefined, // 合同ID（主表的关联字段）
  type: undefined,
  customerId: undefined
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  contractId: [{ required: true, message: '合同ID不能为空', trigger: 'blur' }],
  customerContactId: [{ required: true, message: '客户联系人ID不能为空', trigger: 'blur' }],
  customerName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '手机号不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.contractId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await ContractApi.getContractAAuthorizedPersonListByContractId(val)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)

/** 新增按钮操作 */
// const handleAdd = () => {
//   const row = {
//     id: undefined,
//     contractId: undefined,
//     customerContactId: undefined,
//     customerName: undefined,
//     authPersonType: undefined,
//     phoneNumber: undefined,
//     wechat: undefined,
//     idNumber: undefined,
//     email: undefined,
//     deletedFlag: undefined
//   }
//   row.contractId = props.contractId
//   formData.value.push(row)
// }
const contactRef = ref() // 表单 Ref
const handleAdd = () => {
  contactRef.value.open(formData.value, props.customerId)
}

const getList = (val: []) => {
  for(let i = val.length - 1; i >= 0; i--) {
    let obj = val[i]
    if(formData.value.some(v => v.id === obj.id)) val.splice(i, 1)
  }
  val.forEach(item => {
    if(!formData.value.some(v => v.id === item.id)) {
      val.forEach(item => {
        formData.value.push({
          "name": item.name,
          "postId": item.post,
          "userRank": item.userRank,
          "phoneNumber": item.mobile,
          "authDesc": item.authDesc,
          "wechat":item. wechat,
          "email":item. email,
          "id": item.id
        })
      })
    }
  })
  

}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

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