<template>
  <div>
    <div v-if="questionnairesDom.length > 0">
      <el-row>
        <el-col :span="24">
          <div class="topBtn">
            <!-- <el-button type="warning" icon="DocumentAdd" @click="exportInfo" v-if="showContacts"
              >导入联系人</el-button
            > -->
            <el-button
              v-if="props.idsObj.appointmentBizId"
              type="primary"
              icon="EditPen"
              @click="handleEditStatus(!editStatus)"
              >编辑</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-form ref="heathFormRef" :model="form" :rules="rules">
        <div v-for="(level1, l1) in questionnairesDom" :key="level1.firstCategory">
          <el-row style="margin-bottom: 10px">
            <div class="formBox">
              <div class="fatherLable">{{ level1.firstCategoryName }}</div>

              <el-row :gutter="20">
                <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'"
                          >
                            <!-- 回显得时候拿不到optionBizId -->
                            <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'">
                            <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>
                            <el-button
                              class="addBtn"
                              type="primary"
                              :icon="Plus"
                              size="small"
                              @click="addMedical(l1, l2, l3)"
                              :disabled="editStatus"
                              >继续添加</el-button
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-col>
                </template>
              </el-row>
            </div>
          </el-row>
        </div>
        <el-row>
          <el-col>
            <div class="tabButton">
              <!-- <el-button
                type="primary"
                icon="RefreshRight"
                @click="resetForm"
                size="large"
                :disabled="editStatus"
                >重置</el-button
              > -->
              <el-button
                type="primary"
                icon="Check"
                @click="submitForm"
                :disabled="editStatus"
                size="large"
                >提交</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-else class="domEmpty" v-loading="loading"></div>
  </div>
</template>
<script setup name="secondHolderInfo">
import { Plus } from '@element-plus/icons-vue'

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名称
  fearthStatus: { type: String, default: '' }, //父组件状态，新增、修改
  formStatus: { type: String, default: '' }, //父组件状态，新增、修改
  idsObj: { type: Object, default: () => ({}) }, //父组件传递过来的id对象
  apiSecondHolderInfoDto: { type: Object, default: () => ({}) }, //父组件传递过来的预约信息的详情
  appointmentStatus: { type: Number }, //父组件传递过来的预约的状态
  customerInfo: { type: Object, default: () => ({}) } //客户详情回显表单用
})
const emit = defineEmits(['handleSuccessEdit'])
const { proxy } = getCurrentInstance()
const loading = ref(false)
const errorFields = ref([]) // 存储校验失败的字段信息
const editStatus = ref(true) // 表单是否可编辑,若是修改初始不可编辑
const oldObjInfo = ref({}) // 修改时存储原始数据，便于撤销操作

const data = reactive({
  form: [],
  tempSecondHolderForm: [], //由于切换tab的时候，表单数据会重置，所以需要
  questionnairesDom: [], // 处理后的表单数据
  oldAppointmentData: [], // 保存旧的表单Dom,便于撤销操作
  rules: {}, //表单验证规则,
  queryParams: {
    pageNo: 1,
    pageSize: 4,
    name: undefined
  }
})
const { form, rules, questionnairesDom, queryParams, oldAppointmentData, tempSecondHolderForm } =
  toRefs(data)
const addMedical = (l1, l2, l3) => {
  form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['answerSessionsDto'][
    'questionTextJsonDtoList'
  ].push({
    title: '病况',
    content: ''
  })
}
const deleteMedical = (l1, l2, l3, index) => {
  if (editStatus.value) {
    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) => {
  let answer = JSON.parse(
    JSON.stringify(
      form.value[l1]['secondCategoryDtoList'][l2]['questionsDtoList'][l3]['answerSessionsDto']
    )
  )

  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 = []
  if (props.activeName == 'questionnaires') {
    submitObj = JSON.parse(JSON.stringify(form.value))
    console.log('1111', submitObj)
  } else {
    // submitObj = JSON.parse(JSON.stringify(tempSecondHolderForm.value))
    // console.log('2222', submitObj)
  }

  let answerSessionsDtoList = []
  // 处理表单数据
  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
            })
          }
        })
      }
    })
  })

  return {
    questionnaireBizId: 'questionnaires_1001',
    objectBizId: props.idsObj.appointmentBizId,
    answerSessionsDtoList
  }
}
// 表单提交
const submitForm = () => {
  proxy.$refs['heathFormRef'].validate((valid, fields) => {
    if (valid) {
      let submitObj = handleFormValues()

      if (props.idsObj.appointmentBizId) {
        saveQuestionnaires(submitObj).then(res => {
          if (res.code == 200) {
            handleEditStatus(true)
            proxy.$message.success('健康信息修改成功')
            emit('handleSuccessEdit')
          }
        })
      }

      errorFields.value = [] // 清空错误信息
    } else {
      // 获取校验失败的字段信息
      errorFields.value = getInvalidFields(fields)
      if (errorFields.value.length > 0) {
        proxy.$message.error(errorFields.value[0].message)
      }
    }
  })
}
const resetForm = () => {
  proxy.$modal
    .confirm('是否确认撤销所作操作？')
    .then(function () {
      if (props.customerBizId) {
        form.value = { ...oldObjInfo.value }
        editStatus.value = true
      } else {
        // resetShow('smokeQuantity', false)
        proxy.$refs['heathFormRef'].resetFields()
      }
      questionnairesDom.value = JSON.parse(JSON.stringify(oldAppointmentData.value))
    })

    .catch(() => {})
}
const getQuestionnairesInfo = () => {
  loading.value = true
  getQuestionnaires(props.idsObj.appointmentBizId).then(res => {
    if (res.code == 200) {
      let 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) => {
        // form.value[level1.firstCategory] = {}
        first_category.forEach((first, i) => {
          if (level1.firstCategory == first.value) {
            level1.firstCategoryName = first.label
          }
        })
        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
    }
  })
}

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

    if (newVal === 'questionnaires') {
      if (props.idsObj.appointmentBizId) {
        editStatus.value = true
      }
      getQuestionnairesInfo()
    }
  }
)

// 暴露给父组件
defineExpose({
  handleFormValues,
  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;
}
.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;
  }
  .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;
    }
    .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>
