<template>
  <div style="padding-top: 10px">
    <div v-if="questionnairesDom.length > 0" ref="questionRef">
      <CommonForm
        :anchorList="anchorList"
        :affixOffset="affixOffset"
        :anchorOffset="10"
        :scrollContainerSelector="anchorContainer"
        :scrollOffset="10"
        :domIndex="tabIndex"
        :activeName="activeName"
        v-if="questionRef"
      >
        <template #form-right>
          <el-form ref="heathFormRef" :model="form" :rules="rules">
            <div
              v-for="(level1, l1) in questionnairesDom"
              :key="level1.firstCategory"
              :id="level1.firstCategory"
            >
              <el-row style="margin-bottom: 10px">
                <div class="formBox">
                  <CardOne :title="level1.firstCategoryName">
                    <template #content>
                      <el-row :gutter="20" v-if="level1.showMoudle">
                        <template
                          v-for="(level2, l2) in level1.secondCategoryDtoList"
                          :key="level2.secondCategory"
                        >
                          <el-col :sm="level2.sm" :lg="level2.lg" class="formItem">
                            <div class="level2Title">
                              {{ level2.secondCategoryName }}
                            </div>
                            <div>
                              <div
                                class="level2Content"
                                v-for="(level3, l3) in level2.questionsDtoList"
                              >
                                <div
                                  class="level2Left"
                                  v-if="level2.secondCategory !== 'MEDICAL_CONDITION'"
                                >
                                  {{ l3 + 1 }}/{{ level2.questionsDtoList.length }}
                                </div>
                                <div class="level2Right">
                                  <div
                                    class="level3Title"
                                    v-if="level2.secondCategory !== 'MEDICAL_CONDITION'"
                                  >
                                    {{ level3.text }}
                                  </div>

                                  <div
                                    class="level3Content"
                                    v-if="level2.secondCategory !== 'MEDICAL_CONDITION'"
                                  >
                                    <el-radio-group
                                      v-model="
                                        form[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][
                                          l3
                                        ]['answerSessionsDto']['optionBizId']
                                      "
                                      @change="handleRadioChange(l1, l2, l3, level3)"
                                      :disabled="editStatus"
                                    >
                                      <el-radio
                                        v-for="dict in level3.optionsDtoList"
                                        :key="dict.optionBizId"
                                        :value="dict.optionBizId"
                                        >{{ dict.text }}</el-radio
                                      >
                                    </el-radio-group>
                                    <!--选择是才展示附加条件 -->
                                    <div
                                      v-if="
                                        form[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][
                                          l3
                                        ]['answerSessionsDto']['optionBizId'] == 'option_1002'
                                      "
                                      style="width: 100%"
                                    >
                                      <!-- 附加问题 -->
                                      <div v-for="(level4, l4) in level3.addQuestionsDtoList">
                                        <el-form-item
                                          label-position="top"
                                          :key="level4.addQuestionsBizId"
                                          :label="level4.text"
                                          :rules="
                                            level4.isRequired
                                              ? [
                                                  {
                                                    required: true,
                                                    message: `${level4.text}不能为空`,
                                                    trigger: 'blur'
                                                  }
                                                ]
                                              : []
                                          "
                                        >
                                          <div class="level4Content">
                                            <el-input
                                              v-if="level4.type === 'TEXT'"
                                              :type="level4.type"
                                              v-model="
                                                form[l1]['secondCategoryDtoList'][l2][
                                                  'questionsDtoList'
                                                ][l3]['addQuestionsDtoList'][l4]['content']
                                              "
                                              placeholder="请输入"
                                              maxlength="30"
                                              style="width: 50%"
                                              :disabled="editStatus"
                                            />
                                            <el-date-picker
                                              style="width: 50%"
                                              v-if="level4.type === 'DATE'"
                                              :disabled="editStatus"
                                              v-model="
                                                form[l1]['secondCategoryDtoList'][l2][
                                                  'questionsDtoList'
                                                ][l3]['addQuestionsDtoList'][l4]['content']
                                              "
                                              type="date"
                                              placeholder="请输入"
                                              :disabled-date="disabledDate"
                                              @change="handleDateChange(l1, l2, l3, l4)"
                                            />
                                          </div>
                                        </el-form-item>
                                      </div>
                                    </div>
                                  </div>
                                  <div v-if="level2.secondCategory == 'MEDICAL_CONDITION'">
                                    <el-button
                                      style="margin-bottom: 10px"
                                      class="addBtn"
                                      type="primary"
                                      :icon="Plus"
                                      size="small"
                                      @click="addMedical(l1, l2, l3)"
                                      :disabled="editStatus"
                                      >继续添加</el-button
                                    >
                                    <div
                                      v-for="(question, q4) in level3.answerSessionsDto
                                        .questionTextJsonDtoList"
                                      style="margin-bottom: 10px"
                                    >
                                      <div class="questionContent">
                                        <div class="questionTitle">
                                          {{ `${question.title}${q4 + 1}` }}
                                        </div>
                                        <el-input
                                          type="text"
                                          :disabled="editStatus"
                                          v-model="
                                            form[l1]['secondCategoryDtoList'][l2][
                                              'questionsDtoList'
                                            ][l3]['answerSessionsDto']['questionTextJsonDtoList'][
                                              q4
                                            ]['content']
                                          "
                                          placeholder="请输入"
                                          maxlength="300"
                                          style="width: 70%"
                                        />
                                        <el-icon
                                          class="deleteIcon"
                                          @click="deleteMedical(l1, l2, l3, q4)"
                                          ><Remove
                                        /></el-icon>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </el-col>
                        </template>
                      </el-row>
                    </template>
                  </CardOne>
                </div>
              </el-row>
            </div>
            <!-- <el-row>
              <el-col>
                <div class="tabButton">
                  <el-button
                    type="primary"
                    icon="Check"
                    @click="submitForm"
                    :disabled="editStatus"
                    size="large"
                    >提交</el-button
                  >
                </div>
              </el-col>
            </el-row> -->
          </el-form>
        </template>
      </CommonForm>
    </div>
    <div v-else class="domEmpty" v-loading="loading"></div>
  </div>
</template>
<script setup name="secondHolderInfo">
import { Plus } from '@element-plus/icons-vue'
import CommonForm from '@/views/components/commonForm'
import CardOne from '@/components/formCard/cardOne'
import { watch } from 'vue'
import { getQuestionnaires, saveQuestionnaires } from '@/api/sign/appointment'
import useDictStore from '@/store/modules/dict'

const dictStore = useDictStore() //获取字典数据
const props = defineProps({
  activeName: { type: String, default: '' }, //tab名称
  editStatus: {
    type: Boolean,
    default: false
  }, //父组件状态，新增、修改
  formStatus: { type: String, default: '' }, //父组件状态，新增、修改
  idsObj: { type: Object, default: () => ({}) }, //父组件传递过来的id对象
  appointmentStatus: { type: Number }, //父组件传递过来的预约的状态
  customerInfo: { type: Object, default: () => ({}) },
  //客户详情回显表单用
  showSubmitBtn: { type: Boolean, default: false }, //父组件状态，新增、修改
  foldInsurantInfo: { type: Boolean }, //是否隐藏受保人信息
  pageSource: { type: String, default: '' }, //页面来源
  anchorContainer: { type: String, default: '' }, //锚点滚动容器
  tabIndex: { type: [String, Number], default: '' }, //tab索引
  affixOffset: { type: Number, default: 250 } //锚点吸顶距离
})
const emit = defineEmits(['handleSuccessEdit'])
const { proxy } = getCurrentInstance()
const loading = ref(false)
const errorFields = ref([]) // 存储校验失败的字段信息
const questionRef = ref(null)
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作
const showInsurant = ref(false) //是否显示受保人信息
const questionnairesDom = ref([])
const data = reactive({
  form: [],
  tempSecondHolderForm: [], //由于切换tab的时候，表单数据会重置，所以需要
  // questionnairesDom: [], // 处理后的表单数据
  oldAppointmentData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, queryParams, oldAppointmentData, tempSecondHolderForm } = toRefs(data)
const changeOpenStatus = level1 => {
  console.log('level1', level1)
  let newDom = JSON.parse(JSON.stringify(questionnairesDom.value))
  newDom.forEach((item, index) => {
    if (item.firstCategory == level1.firstCategory) {
      item.showMoudle = !item.showMoudle
    }
  })
  questionnairesDom.value = newDom
}
const addMedical = (l1, l2, l3) => {
  form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['answerSessionsDto'][
    'questionTextJsonDtoList'
  ].push({
    title: '病况',
    content: ''
  })
}
const deleteMedical = (l1, l2, l3, index) => {
  if (props.editStatus) {
    proxy.$modal.confirm(`请先点击编辑在删除病况`, { showCancel: '0', title: '填写提示' })
    return
  }
  form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['answerSessionsDto'][
    'questionTextJsonDtoList'
  ].splice(index, 1)
  questionnairesDom.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3][
    'answerSessionsDto'
  ]['questionTextJsonDtoList'].splice(index, 1)
}
const handleRadioChange = (l1, l2, l3, level3) => {
  console.log('====================================')
  console.log('表单form', form.value)
  console.log('====================================')
  let answer = JSON.parse(
    JSON.stringify(
      form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['answerSessionsDto']
    )
  )
  if (answer.optionBizId == 'option_1001') {
    if (answer.optionJsonDtoList.length > 0) {
      answer.optionJsonDtoList.map((item, index) => {
        if (item.optionBizId == 'option_1002') {
          answer.optionJsonDtoList.splice(index, 1)
        }
      })
    }
  } else if (answer.optionBizId == 'option_1002') {
    if (answer.optionJsonDtoList.length > 0) {
      answer.optionJsonDtoList.map((item, index) => {
        if (item.optionBizId == 'option_1001') {
          answer.optionJsonDtoList.splice(index, 1)
        }
      })
    }
  }

  let optionItem = level3.optionsDtoList.filter(item => item.optionBizId === answer.optionBizId)

  let newObj = {
    optionBizId: optionItem[0].optionBizId,
    content: optionItem[0].value
  }
  // 检查数组中是否已存在相同ID的地址
  const existingIndex = answer.optionJsonDtoList.findIndex(
    item => item.optionBizId === optionItem[0].optionBizId
  )

  if (existingIndex !== -1) {
    // 更新已存在的数据
    answer.optionJsonDtoList[existingIndex] = { ...newObj }
  } else {
    // 添加新的数据
    answer.optionJsonDtoList.push({ ...newObj })
  }

  form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['answerSessionsDto'] = answer
}

const handleDateChange = (l1, l2, l3, l4) => {
  let time =
    form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['addQuestionsDtoList'][l4][
      'content'
    ]
  time = proxy.formatToDate(time)
  form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['addQuestionsDtoList'][l4][
    'content'
  ] = time
}
const disabledDate = time => {
  return time.getTime() > Date.now()
}

// 获取字典数据
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 handleEditStatus = status => {
  editStatus.value = status
}

// 获取校验失败的字段信息
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 = []
  return new Promise(async resolve => {
    if (questionnairesDom.value.length > 0) {
      proxy.$refs['heathFormRef'].validate((valid, fields) => {
        if (valid) {
          errorFields.value = [] // 清空错误信息
          submitObj = JSON.parse(JSON.stringify(form.value))

          let answerSessionsDtoList = []
          if (submitObj.length > 0) {
            // 处理表单数据
            submitObj.forEach(level1 => {
              level1.secondCategoryDtoList.forEach(level2 => {
                // 修正：应该是 questionsDtoList 而不是 questionDtoList
                if (level2.questionsDtoList && level2.questionsDtoList.length > 0) {
                  level2.questionsDtoList.forEach(level3 => {
                    // 检查是否有答案数据和附加问题
                    //
                    if (level3.answerSessionsDto) {
                      // 问题选择了是
                      if (
                        level3.answerSessionsDto.optionJsonDtoList &&
                        level3.answerSessionsDto.optionBizId &&
                        level3.answerSessionsDto.optionBizId == 'option_1002'
                      ) {
                        level3.answerSessionsDto.optionJsonDtoList.forEach(level4 => {
                          level4.addQuestionsJsonDtoList = JSON.parse(
                            JSON.stringify(level3.addQuestionsDtoList)
                          )
                        })
                      }
                      answerSessionsDtoList.push({
                        questionBizId: level3.questionBizId,
                        ...level3.answerSessionsDto
                      })
                    }
                  })
                }
              })
            })
          }

          let objectBizId = ''
          if (
            props.idsObj.appointmentBizId &&
            (props.pageSource == 'fnaList' || props.pageSource == 'appointmentList')
          ) {
            objectBizId = props.idsObj.appointmentBizId
          } else if (props.idsObj.policyBizId && props.pageSource == 'policyList') {
            objectBizId = props.idsObj.policyBizId
          }
          resolve(
            errorFields.value.length == 0
              ? {
                  questionnaireBizId: 'questionnaires_1001',
                  objectBizId: objectBizId,
                  answerSessionsDtoList
                }
              : null
          )
        } else {
          // 获取校验失败的字段信息
          errorFields.value = getInvalidFields(fields)
          if (errorFields.value.length > 0) {
            proxy.$message.error(errorFields.value[0].message)
          }
          resolve(undefined)
        }
      })
    } else {
      resolve(undefined)
    }
  })
}

const getQuestionnairesInfo = () => {
  loading.value = true
  let id = ''
  if (
    props.idsObj.appointmentBizId &&
    (props.pageSource == 'fnaList' || props.pageSource == 'appointmentList')
  ) {
    id = props.idsObj.appointmentBizId
  } else if (props.idsObj.policyBizId && props.pageSource == 'policyList') {
    id = props.idsObj.policyBizId
  }
  getQuestionnaires(id).then(res => {
    if (res.code == 200) {
      let result = []
      if (props.foldInsurantInfo) {
        result = [res.data.firstAndSecondCategoryDtoList[0]]
      } else {
        result = res.data.firstAndSecondCategoryDtoList
      }
      let first_category = fetchDictData('wj_question_first_category')
      let second_category = fetchDictData('wj_question_second_category')
      form.value = {}
      result.forEach((level1, l1) => {
        first_category.forEach((first, i) => {
          if (level1.firstCategory == first.value && !props.foldInsurantInfo) {
            level1.firstCategoryName = first.label
          } else if (props.foldInsurantInfo && level1.firstCategory == 'POLICYHOLDER') {
            level1.firstCategoryName = '投保人 / 受保人'
          }
        })
        if (level1.firstCategory == 'POLICYHOLDER') {
          // level1.showIcon = true
          level1.showMoudle = true
        } else if (level1.firstCategory == 'INSURED_PERSON') {
          level1.showIcon = true
          level1.showMoudle = true
        }
        level1.secondCategoryDtoList.forEach((level2, l2) => {
          level2.sm = 24
          level2.lg = 24
          second_category.forEach((second, i) => {
            if (level2.secondCategory == second.value) {
              level2.secondCategoryName = second.label
            }
          })
          level2.questionsDtoList.forEach((level3, l3) => {
            level3.labelWidth = '100%'
            level3.labelPosition = 'top'
            level3.key = level3.id
            if (level3.optionsDtoList && level3.optionsDtoList.length > 0) {
              level3.optionsDtoList.forEach((level4, l4) => {})
            }
            if (!level3.answerSessionsDto) {
              level3.answerSessionsDto = {}
              if (
                level2.secondCategory !== 'MEDICAL_CONDITION' &&
                !level3.answerSessionsDto.optionJsonDtoList
              ) {
                level3.answerSessionsDto.optionJsonDtoList = []
              }
              if (
                level2.secondCategory == 'MEDICAL_CONDITION' &&
                !level3.answerSessionsDto.questionTextJsonDtoList
              ) {
                level3.answerSessionsDto.questionTextJsonDtoList = []
              }
            } else {
              if (
                level2.secondCategory !== 'MEDICAL_CONDITION' &&
                !level3.answerSessionsDto.optionJsonDtoList
              ) {
                level3.answerSessionsDto.optionJsonDtoList = []
              } else {
                // 给单选框赋值，方便回显
                if (
                  level3.answerSessionsDto.optionJsonDtoList &&
                  level3.answerSessionsDto.optionJsonDtoList.length > 0
                ) {
                  level3.answerSessionsDto.optionBizId =
                    level3.answerSessionsDto.optionJsonDtoList[0].optionBizId
                  if (level3.answerSessionsDto.optionJsonDtoList[0].addQuestionsJsonDtoList) {
                    level3.addQuestionsDtoList.forEach((level5, l5) => {
                      level3.answerSessionsDto.optionJsonDtoList[0].addQuestionsJsonDtoList.forEach(
                        (level6, l6) => {
                          if (level5.addQuestionsBizId == level6.addQuestionsBizId) {
                            if (level5.type == 'DATE') {
                              level5.content = proxy.formatToDate(level6.content)
                            } else {
                              level5.content = level6.content
                            }
                          }
                        }
                      )
                    })
                  }
                }
              }
              if (
                level2.secondCategory == 'MEDICAL_CONDITION' &&
                !level3.answerSessionsDto.questionTextJsonDtoList
              ) {
                level3.answerSessionsDto.questionTextJsonDtoList = []
              }
            }
          })
        })
      })

      questionnairesDom.value = form.value = result
      loading.value = false

      console.log('questionnairesDom.value', questionnairesDom.value)
    }
  })
}
const anchorList = computed(() => {
  let data = []
  for (const section of questionnairesDom.value) {
    if (section.showMoudle) {
      data.push({ title: section.firstCategory, name: section.firstCategoryName })
    }
  }
  return data
})
const hasLoaded = ref(false) // 新增：是否已加载过数据
watch(
  () => props.activeName,
  newVal => {
    questionRef.value = null
    if (newVal === 'questionnaires') {
      if (!hasLoaded.value) {
        getQuestionnairesInfo()
        hasLoaded.value = true
      }
    }
  }
)

// 受保人模块，与投保人关系改变这里要重新获取问卷信息
watch(
  () => props.foldInsurantInfo,
  newVal => {
    questionnairesDom.value = []
    getQuestionnairesInfo()
    console.log('newVal', newVal)
  }
)

console.log('foldInsurantInfo', props.foldInsurantInfo)
// 暴露给父组件
defineExpose({
  handleFormValues,
  handleEditStatus,
  questionLength: computed(() => {
    return questionnairesDom.value.length
  })
})
</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;
    display: flex;
    align-items: center;
    .openCon {
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .fatherDes {
    font-size: 14px;
    color: #a8abb2;
    margin-top: 5px;
    margin-bottom: 20px;
  }
  .level2Title {
    font-size: 16px;
    margin: 10px 0;
  }
  .level2Content {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    font-size: 14px;
    margin-bottom: 10px;
    .level2Left {
      margin-right: 15px;
      margin-top: 3px;
      color: #0052d9;
    }
    .level2Right {
      width: calc(100% - 30px);
      .level3Title {
        font-size: 13px;
      }
      .level3Content {
        display: flex;
        flex-direction: column;
        .level4Content {
          width: 100%;
        }
      }
      .questionContent {
        display: flex;
        align-items: center;
        .questionTitle {
          margin-right: 10px;
          font-size: 13px;
        }
        .addBtn {
          margin-top: 10px;
        }
        .deleteIcon {
          font-size: 20px;
          color: red;
          margin-left: 5px;
        }
      }
    }
  }
  .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 {
    display: flex;
    justify-content: flex-start;
    .title {
      width: 120px;
      font-size: 14px;
      text-align: right;
    }
    .informationBox {
      margin-left: 5px;
      font-size: 14px;
      border: 1px solid #dcdfe6;
      width: 100%;
      border-radius: 4px;
      padding: 2px 4px;
      box-sizing: border-box;
    }
  }
}
.tabButton {
  /* box-shadow: 0 -1px 14px #00000014; */
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* padding-right: 20px; */
  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: 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>
