<template>
  <div>
    <div v-if="policyTransferData.length > 0" class="content">
      <!-- <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <el-button
              v-if="props.idsObj.appointmentBizId"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus(!editStatus)"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row> -->
      <el-form ref="policyTransferFormRef" :model="form" label-width="0px" class="formCon">
        <div v-for="father in policyTransferData">
          <div class="formBox">
            <el-row :gutter="20">
              <el-col :sm="father.sm" :lg="father.lg" class="formItem" v-if="father.show">
                <div v-if="father.domType === 'Div'" class="divClass">
                  <div v-if="father.key == 'policyTransfer'" class="desBox">
                    <div class="title">{{ father.title }}</div>
                    <div class="informationBox">
                      <div
                        v-for="(item, index) in father.informationList"
                        :key="index"
                        style="margin-bottom: 10px"
                      >
                        {{ item.name }}
                      </div>
                    </div>
                    <el-form-item v-if="father.key == 'policyTransfer'" prop="policyTransfer">
                      <el-radio-group v-model="form[father.key]">
                        <el-radio
                          v-for="dict in father.options"
                          :key="dict.value"
                          :value="dict.value"
                          >{{ dict.label }}</el-radio
                        >
                      </el-radio-group>
                    </el-form-item>
                    <div class="tips" v-if="father.tip">{{ father.tip }}</div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
      <el-row>
        <el-col>
          <div class="tabButton">
            <!-- :disabled="editStatus" -->
            <el-button type="primary" icon="Check" @click="submitForm" size="large">提交</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- <div v-else class="domEmpty" v-loading="loading"></div> -->
  </div>
</template>
<script setup name="PolicyTransferInfo">
import policyTransferDomData from '@/formJson/policyTransferInfo'
import { watch } from 'vue'
import { editPolicytransfer } from '@/api/sign/appointment'
import { updatePolicyProduct } from '@/api/sign/underwritingMain'
import useDictStore from '@/store/modules/dict'

const dictStore = useDictStore() //获取字典数据

const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  formStatus: { type: String, default: '' }, //父组件状态，新增、修改
  idsObj: { type: Object, default: () => ({}) }, //父组件传递过来的id对象
  apiAppointmentInfoDto: { type: Object, default: () => ({}) }, //父组件传递过来的预约信息的详情
  appointmentStatus: { type: Number }, //父组件传递过来的预约的状态
  showSubmitBtn: { type: Boolean, default: false }, //父组件状态，新增、修改
  pageSource: { type: String, default: '' } //页面来源
})
const emit = defineEmits(['handleSuccessEdit', 'policyEditSuccess'])
const { proxy } = getCurrentInstance()
// const { csf_id_type, sys_gender } = proxy.useDict('csf_id_type', 'sys_gender')
const loading = ref(false)
const editStatus = ref(false) //编辑状态
const errorFields = ref([]) // 存储校验失败的字段信息
const data = reactive({
  form: { policyTransfer: '' },
  tempSecondHolderForm: {}, //由于切换tab的时候，表单数据会重置，所以需要
  policyTransferData: [], // 处理后的表单数据
  oldAppointmentData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, policyTransferData, tempSecondHolderForm } = toRefs(data)

// 获取字典数据
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 validateEnglish = (rule, value, callback) => {
  if (value && !/^[A-Za-z]*$/.test(value)) {
    // 清空非英文字符
    form.value.firstNamePinyin = ''
    callback(new Error('只能输入英文字母'))
  } else {
    callback()
  }
}

// 处理表单配置，添加字典数据
/**
 * domdata:表单的dom数据
 * customerInfo:根据客户信息回显表单
 * exportValue:是否从导入联系人列表中导入客户信息到当前表单
 */
const processFormData = async obj => {
  form.value = {}
  loading.value = true
  // console.log('====================================')
  // console.log('传值', props.apiAppointmentInfoDto)
  // console.log('====================================')
  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(obj.domdata))

  for (const section of processedData) {
    if (section.dictType) {
      // 获取字典数据
      section.options = fetchDictData(section.dictType)
    }
  }
  // debugger
  if (props.showSubmitBtn) {
    if (props.apiAppointmentInfoDto.policyTransfer) {
      form.value.policyTransfer = props.apiAppointmentInfoDto.policyTransfer
      console.log('====================================')
      console.log('表单数据', form.value)
      console.log('====================================')
    }
  }
  console.log('转报form', form.value)

  policyTransferData.value = processedData
  loading.value = false
}
// 改变编辑状态
const handleEditStatus = status => {
  editStatus.value = status
  console.log('触发了编辑状态', editStatus.value)

  // 深拷贝原始数据
  const processedData = JSON.parse(JSON.stringify(policyTransferData.value))
  for (const section of processedData) {
    if (section.data) {
      for (const field of section.data) {
        if (editStatus.value) {
          field.disabled = true
        } else {
          field.disabled = false
        }
      }
    }
  }
  policyTransferData.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 handleFormValues = () => {
  let submitObj = {}
  if (props.activeName == 'secondHolder') {
    submitObj = JSON.parse(JSON.stringify(form.value))
  } else {
    submitObj = JSON.parse(JSON.stringify(tempSecondHolderForm.value))
  }

  //处理表单数据
  for (const key1 in submitObj) {
    if (key1 == 'birthTime') {
      submitObj[key1] = proxy.formatToDateTime(submitObj[key1])
    }
  }
  return submitObj
}
// 表单提交
const submitForm = () => {
  proxy.$refs['policyTransferFormRef'].validate((valid, fields) => {
    if (valid) {
      let submitObj = JSON.parse(JSON.stringify(props.apiAppointmentInfoDto))
      submitObj.policyTransfer = form.value.policyTransfer
      if (
        props.idsObj.appointmentBizId &&
        (props.pageSource == 'fnaList' || props.pageSource == 'appointmentList')
      ) {
        submitObj.appointmentBizId = props.idsObj.appointmentBizId
        editPolicytransfer(submitObj).then(res => {
          if (res.code == 200) {
            // handleEditStatus(true)
            proxy.$message.success('预约-转保声明修改成功')
            emit('handleSuccessEdit')
          }
        })
      }
      if (props.idsObj.policyBizId && props.pageSource == 'policyList') {
        // submitObj.policyBizId = props.idsObj.policyBizId
        // console.log('转包声明', submitObj)

        // return
        updatePolicyProduct({
          policyBizId: props.idsObj.policyBizId,
          apiProductPlanMainInfoDto: submitObj
        }).then(res => {
          if (res.code == 200) {
            // handleEditStatus(true)
            proxy.$message.success('新单跟进-转保声明修改成功')
            emit('policyEditSuccess')
          }
        })
      }
      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}

watch(
  () => props.activeName,
  newVal => {
    // 切换tab的时侯把表单值保存在临时变量里，方便切换回来的时候回显
    // tempSecondHolderForm.value = { ...form.value }

    if (newVal === 'policyTransfer') {
      processFormData({
        domdata: policyTransferDomData
      })
    }
  }
)

// 暴露给父组件
defineExpose({
  form,
  handleEditStatus
})
</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;
}
.content {
  display: flex;
  flex-direction: column;
  .formCon {
    flex: 1;
  }
}
.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;
  }
  .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;
    }
  }
  .desBox {
    padding: 10px;
    .title {
      width: 100%;
      font-size: 14px;
      margin-bottom: 15px;
    }
    .informationBox {
      margin-left: 5px;
      font-size: 14px;
      width: 100%;
      border-radius: 4px;
      padding: 2px 4px;
      box-sizing: border-box;
    }
    .tips {
      width: 100%;
      font-size: 13px;
      margin-top: 5px;
    }
  }
}
.tabButton {
  /* box-shadow: 0 -1px 14px #00000014; */
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding-right: 20px; */
  padding-top: 50px;
  .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: flex-end;
      width: 100%;
      .left {
        width: 40%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .gender {
          display: flex;
          align-items: center;
        }
      }
    }
    .bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      .left {
        /* display: flex;
        align-items: center; */
        .infoItem {
          display: flex;
          align-items: center;
          margin: 5px 10px;
        }
      }
    }
  }
  .customerItem:last-child {
    margin-bottom: 0px;
  }
}
</style>
