<template>
  <div>
    <div v-if="processedFanFormData.length > 0">
      <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <el-button
              v-if="props.policyBizId"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form ref="fanFormRef" :model="form" :rules="rules">
        <el-row v-for="father in processedFanFormData" style="margin-bottom: 10px">
          <div class="formBox formFna">
            <!-- <div class="fatherLable">{{ father.fatherTitle }}</div>
            <div class="subTitle" v-if="father.subTitle">{{ father.subTitle }}</div> -->

            <el-row v-if="father.child == 'no'" :gutter="20">
              <template v-for="child in father.data" :key="child.key">
                <el-col :sm="child.sm" :lg="child.lg" class="formItem" v-if="child.show">
                  <div>
                    <el-form-item
                      :label="child.label"
                      :prop="father.key + '.' + child.key"
                      :key="child.key"
                      :label-width="child.labelWidth"
                      :label-position="child.labelPosition"
                    >
                      <el-input
                        v-if="child.domType === 'Input'"
                        :type="child.inputType"
                        v-model="form[father.key][child.key]"
                        :placeholder="child.placeholder"
                        maxlength="30"
                        :disabled="child.disabled"
                        :style="{ width: child.inputWidth ? child.inputWidth : '100%' }"
                      />
                      <el-input
                        v-if="child.inputType === 'Input'"
                        :type="child.inputType"
                        v-model="form[father.key][child.key]"
                        :placeholder="child.placeholder"
                        maxlength="30"
                        :disabled="child.disabled"
                        :style="{ width: child.inputWidth ? child.inputWidth : '100%' }"
                        class="formInput"
                      />
                      <el-select
                        v-if="child.domType === 'Select'"
                        v-model="form[father.key][child.key]"
                        :placeholder="child.placeholder"
                        @change="handleSelectChange(father, child)"
                        :disabled="child.disabled"
                      >
                        <el-option
                          v-for="item in child.options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-date-picker
                        style="width: 100%"
                        v-if="child.domType === 'DatePicker'"
                        v-model="form[father.key][child.key]"
                        type="date"
                        :placeholder="child.placeholder"
                        :disabled="child.disabled"
                      />
                      <el-checkbox-group
                        v-if="child.domType === 'Checkbox'"
                        v-model="form[father.key][child.key]"
                        :disabled="child.disabled"
                      >
                        <el-checkbox
                          v-for="item in child.options"
                          :key="item.value"
                          :label="item.value"
                        >
                          {{ item.label }}
                        </el-checkbox>
                      </el-checkbox-group>
                      <el-select
                        v-model="form[father.key][child.key]"
                        v-if="child.domType === 'SearchSelect'"
                        filterable
                        remote
                        reserve-keyword
                        placeholder="请输入关键词搜索"
                        :remote-method="query => searchSelectList(query, child.key)"
                        :loading="searchLoadingStates[child.key]"
                        :disabled="child.disabled"
                        @change="handleSearchSelectChange(father, child)"
                      >
                        <el-option
                          v-for="item in searchOptions[child.key] || []"
                          :key="item.id"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </div>
                </el-col>
              </template>
            </el-row>
          </div>
        </el-row>

        <el-row>
          <el-col>
            <div class="tabButton">
              <el-button
                type="success"
                icon="Check"
                @click="submitForm('save')"
                size="large"
                :disabled="editStatus"
                >提交</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-else class="domEmpty" v-loading="loading"></div>
  </div>
</template>
<script setup name="policyInfo">
import useDictStore from '@/store/modules/dict'
import policyInfo from '@/formJson/policyInfo'
import { getDicts } from '@/api/system/dict/data'
import { watch, nextTick } from 'vue'
import { addfanForm, getfanFormDetail, editFanForm, getCustomerList } from '@/api/sign/fna'
import {
  listTenantUser,
  getInsuranceProductList,
  getAllCompanys,
  getClientUser
} from '@/api/common'
import { updatePolicyfollow, getPolicyfollow } from '@/api/sign/underwritingMain'
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  customerInfo: { type: Object, default: () => {} }, //客户详情
  // policyInfo: { type: Object, default: () => {} }, //客户详情
  activeName: { type: String, default: '' }, //tab名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  policyBizId: { type: String, default: '' }, //提交状态，新增、修改
  customerBizId: { type: String, default: '' }, //提交状态，新增、修改
  dictTypeLists: { type: Array, default: () => [] }, //多个字典值数据
  policyFollowUpdateDto: { type: Object, default: () => {} } //详情数据
})

const emit = defineEmits(['handleSuccess', 'policyEditSuccess'])
const { proxy } = getCurrentInstance()

const loading = ref(false)
const fanFormRef = ref(null)
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const openList = ref(false) // 客户列表弹窗
const noYesList = ref([]) // 是否列表
const searchOptions = ref({}) // 存储不同key对应的选项
const searchLoadingStates = ref({}) // 存储不同key对应的加载状态
const data = reactive({
  form: {},
  processedFanFormData: [], // 处理后的表单数据
  tempFanFormValue: {}, // 切换tab得时候保存临时填写得值
  tempFanFormData: [], // 处理后的表单数据
  oldFanFormData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const {
  form,
  rules,
  processedFanFormData,
  queryParams,
  oldFanFormData,
  tempFanFormValue,
  tempFanFormData
} = toRefs(data)
const disabledDate = time => {
  return time.getTime() > Date.now()
}
// 搜索方法
const searchSelectList = async (query, fieldKey) => {
  // 设置该字段的加载状态
  searchLoadingStates.value[fieldKey] = true

  try {
    // 根据不同的字段key调用不同的API
    if (fieldKey === 'productName') {
      const params = {
        loginTenantBizId: userStore.projectInfo.tenantBizId,
        productName: query.trim(),
        pageNo: 1,
        pageSize: 10
      }

      const response = await getInsuranceProductList(params)
      if (response.code == 200) {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.productName,
            value: item.productBizId
          }
        })
        searchOptions.value[fieldKey] = response.data.records
      }
    }
    // 可以添加其他字段的处理,可以放其他的字段得请求，目前只有accountName，以后有了其他的在填充
    else if (fieldKey === 'reconciliationCompany' || fieldKey === 'insurer') {
      const params = {
        deptName: query.trim(),
        pageNo: 1,
        pageSize: 10
      }
      getAllCompanys(params).then(response => {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.deptName,
            value: item.deptBizId
          }
        })
        searchOptions.value[fieldKey] = response.data.records
      })
    } else if (fieldKey === 'brokerName') {
      const params = {
        projectBizId: 'project_IbjfmMTYvNEBuh2S',
        tenantBizId: userStore.projectInfo.tenantBizId,
        queryContent: query.trim(),
        pageNo: 1,
        pageSize: 10
      }
      getClientUser(params).then(response => {
        response.data.records = response.data.records.map(item => {
          return {
            ...item,
            label: item.name,
            value: item.clientUserBizId
          }
        })
        searchOptions.value[fieldKey] = response.data.records
      })
    }
  } catch (error) {
    console.error(`${fieldKey} 搜索失败`, error)
    searchOptions.value[fieldKey] = []
  } finally {
    searchLoadingStates.value[fieldKey] = false
  }
}
const handleSearchSelectChange = (father, child) => {
  if (child.key == 'productName') {
    let productItem = dictStore.insureProductList.filter(item => {
      return item.value == form.value[father.key][child.key]
    })
    let options = productItem[0].paymentTerm.split(',').map(item => {
      return {
        label: item,
        value: item
      }
    })

    const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
    for (const section of processedData) {
      if (section.key == father.key) {
        if (section.data) {
          for (const field of section.data) {
            if (field.dictType && field.dictType == 'paymentTerm') {
              field.options = options
            }
          }
        }
      }
    }
    if (options.length > 0) {
      form.value[father.key]['paymentTerm'] = options[0].value
    }
    processedFanFormData.value = processedData
  }
}
// 获取字典数据
const fetchDictData = dictType => {
  let options = []
  try {
    dictStore.dictTypeLists.forEach(item => {
      if (item.dictType == dictType) {
        options = item.dictItemList
      }
    })
    return options
  } catch (error) {
    console.error('获取字典数据失败:', error)
    return []
  }
}
// 处理表单配置，添加字典数据
const processFormData = () => {
  loading.value = true
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(policyInfo))

  for (const section of processedData) {
    if (section.fatherRequired) {
      rules.value[section.key] = {}
    }
    //给表单赋值各模块key,对应表单的father.key便于收集值
    if (section.keyType == 'Array') {
      form.value[section.key] = []
      if (section.key == 'brokerList') {
        form.value[section.key] = section.data
      }
    } else if (section.keyType == 'Object') {
      form.value[section.key] = {}
    }
    if (section.data) {
      for (const formKey in form.value) {
        if (section.key == formKey) {
          for (const field of section.data) {
            // 为下拉搜索框加options
            if (field.domType == 'SearchSelect') {
              if (field.key == 'insurer' || field.key == 'reconciliationCompany') {
                searchOptions.value[field.key] = dictStore.insureCompanyList
              }
            }

            if (field.dictType) {
              // 获取字典数据
              field.options = fetchDictData(field.dictType)
            }
            //
            /*
            1.没有嵌套子级的也就是没有children的数据加rules，根据data中的required字段判断是否必填
            2.有嵌套子级的也就是有children的数据，根据children中的required字段判断是否必填，现在没这个需求，所以先注释
            */
            if (field.required && section.child == 'no') {
              rules.value[section.key][field.key] = [
                { required: true, message: `${field.label}不能为空`, trigger: 'blur' }
              ]
            }
            if (props.policyBizId) {
              field.disabled = true
            } else {
              field.disabled = false
            }
          }
        }
      }
    }
  }
  if (props.policyBizId) {
    form.value.policyFollowUpdateDto = JSON.parse(JSON.stringify(props.policyFollowUpdateDto))
    form.value.policyBizId = props.policyBizId
    editStatus.value = true
  } else {
    // tab切走在切回来时，表单会重置，所以这里需要把表单的值赋回去
    editStatus.value = false
  }
  if (Object.keys(tempFanFormValue.value).length > 0) {
    form.value = JSON.parse(JSON.stringify(tempFanFormValue.value))
  }
  processedFanFormData.value = oldFanFormData.value = processedData
  // if (tempFanFormData.value.length > 0) {
  //   processedFanFormData.value = oldFanFormData.value = JSON.parse(
  //     JSON.stringify(tempFanFormData.value)
  //   )
  // } else {
  //   processedFanFormData.value = oldFanFormData.value = processedData
  // }
  loading.value = false
}
// 根据联动重置表单项的显示与否
const resetShow = (childKey, status) => {
  console.log(childKey, status)

  for (const section of processedFanFormData.value) {
    // 暂时没考虑data里嵌套children的情况
    if (section.data) {
      for (const field of section.data) {
        if (field.key == childKey) {
          // 获取字典数据
          field.show = status
        }
      }
    }
  }
}
const handleSelectChange = (father, child) => {
  switch (child.key) {
    case 'employment':
      // 选择吸烟，展示吸烟数量
      if (form.value[father.key][child.key] == 'OTHER') {
        resetShow('otherEmployment', true)
        form.value[father.key]['otherEmployment'] = ''
      } else {
        resetShow('otherEmployment', false)
      }

      break

    default:
      break
  }
}
// 改变编辑状态
const handleEditStatus = () => {
  editStatus.value = !editStatus.value
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(processedFanFormData.value))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        // 改变data中字段得编辑状态
        if (editStatus.value) {
          field.disabled = true
        } else {
          field.disabled = false
        }
        // 改变data中的children字段得编辑状态
        if (field.children) {
          for (const child of field.children) {
            if (editStatus.value) {
              child.disabled = true
            } else {
              child.disabled = false
            }
          }
        }
      }
    }
  }
  processedFanFormData.value = processedData
}

// 获取校验失败的字段信息
const getInvalidFields = fields => {
  const errors = []
  for (const field in fields) {
    if (fields[field] && fields[field].length > 0) {
      errors.push({
        field: field,
        message: fields[field][0].message
      })
    }
  }
  return errors
}
// 判断是否为数组
const isArray = value => {
  return Array.isArray(value)
}

// 判断是否为对象
const isObject = value => {
  return typeof value === 'object' && value !== null && !Array.isArray(value)
}
// 处理表单填写得数据
const handleFormValues = () => {
  let submitObj = JSON.parse(JSON.stringify(form.value))
  const pattern = /Date$/ // 以Time结尾
  // debugger
  //处理表单数据
  for (const key1 in form.value) {
    // 对象数据格式
    if (isObject(form.value[key1]) && Object.keys(form.value[key1]).length > 0) {
      for (const key2 in form.value[key1]) {
        if (pattern.test(key2) && form.value[key1][key2]) {
          submitObj[key1][key2] = proxy.formatToDate(form.value[key1][key2])
        }
        // 处理搜索下拉框数据需要返回的各种业务ID
        if ((key2 == 'insurer' || key2 === 'reconciliationCompany') && form.value[key1][key2]) {
          dictStore.insureCompanyList.forEach(item => {
            if (item.deptBizId == form.value[key1][key2]) {
              submitObj[key1][key2] = item.deptName
              submitObj[key1][`${key2}BizId`] = item.deptBizId
            }
          })
        } else if (key2 == 'productName' && form.value[key1][key2]) {
          dictStore.insureProductList.forEach(item => {
            if (item.productBizId == form.value[key1][key2]) {
              submitObj[key1][key2] = item.productName
              submitObj[key1]['productBizId'] = item.productBizId
            }
          })
        }
      }
    }
    // 数组数据格式
    if (isArray(form.value[key1]) && form.value[key1].length > 0) {
      submitObj[key1] = form.value[key1].map(item1 => {
        if (item1.brokerName) {
          dictStore.clientUserList.forEach(item => {
            if (item.clientUserBizId == item1.brokerName) {
              item1.brokerName = item.name
              item1['brokerBizId'] = item.clientUserBizId
            }
          })
        }
        // delete item1.id
        return item1
      })
    }
  }

  return submitObj
}
// 表单提交
const submitForm = saveType => {
  let submitObj = handleFormValues()

  proxy.$refs['fanFormRef'].validate((valid, fields) => {
    if (valid) {
      if (props.policyBizId) {
        updatePolicyfollow(submitObj).then(res => {
          if (res.code == 200) {
            handleEditStatus()
            proxy.$message.success('提交成功')
            // 提交成功后，在获取详情信息，防止数据丢失
            // getPolicyDetail()
            emit('policyEditSuccess', 'policyInfo')
          }
        })
      } else {
      }
      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}
// 获取新单跟进详情数据
const getPolicyDetail = () => {
  getPolicyfollow(props.policyBizId).then(res => {
    if (res.code == 200) {
      form.value.policyFollowUpdateDto = res.data.policyFollowUpdateDto
    }
  })
}

watch(
  () => props.activeName,
  newVal => {
    tempFanFormValue.value = JSON.parse(JSON.stringify(form.value))
    tempFanFormData.value = JSON.parse(JSON.stringify(processedFanFormData.value))
    if (newVal === 'policyInfo') {
      setTimeout(() => {
        processFormData()
      }, 500)
    }
  }
)
</script>
<style lang="scss" scoped>
.domEmpty {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 16px;
  color: #a8abb2;
  margin-top: 100px;
}
.topBtn {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.formBox {
  width: 100%;
  .fatherLable {
    font-size: 18px;
    border-left: 4px solid #165dff;
    padding-left: 5px;
    margin-bottom: 5px;
  }
  .subTitle {
    font-size: 15px;
    /* padding-left: 8px; */
    margin-bottom: 10px;
  }
  .childLabel {
    font-size: 14px;
    /* padding-left: 15px; */
    margin-bottom: 15px;
  }
  .fatherDes {
    font-size: 14px;
    color: #a8abb2;
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .inputBox {
    width: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 32px;
    padding: 0px 11px;
    .rightArrow {
      font-size: 14px;
      color: #a8abb2;
    }
  }
  .deleteIcon {
    color: red;
    font-size: 18px;
    padding-top: 10px;
  }
}
.tabButton {
  /* box-shadow: 0 -1px 14px #00000014; */
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 20px;
  .sumbitBtn {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    height: 60px;
    background-color: #165dff;
    color: #fff;
    padding: 0 30px;
    .buttonIcon {
      font-size: 16px;
      color: #fff;
    }
  }
}
.customerBox {
  .customerItem {
    padding: 10px;
    border-radius: 5px;
    margin-bottom: 20px;
    box-shadow: 0 -1px 14px #00000014;
    .top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .left {
        width: 40%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .gender {
          display: flex;
          align-items: center;
        }
      }
    }
    .bottom {
      .infoItem {
        display: flex;
        align-items: center;
        margin: 5px 0;
      }
    }
  }
  .customerItem:last-child {
    margin-bottom: 0px;
  }
}
/* 新增的样式：防止label换行并显示省略号 */
.formFna :deep(.el-checkbox) {
  margin-right: 10px;
}

@media only screen and (min-width: 768px) {
  .formInput {
    margin-top: 30px !important;
  }
}

@media only screen and (min-width: 1200px) {
  .formInput {
    margin-top: 30px !important;
  }
}
</style>
