<template>
  <div v-loading="loading">
    <el-tabs v-model="activeVisitTab" class="visit-tabs" type="border-card">
      <el-tab-pane v-for="visit in visitPlanOptions" :key="visit.Id"
        :label="visit.VisitName" :name="visit.Id">
        <div v-show="!isSign" class="visit-tabs-actions">
          <!-- 批量保存 -->
          <el-button
            v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']"
            :disabled="btnLoading || questionListMap[visit.Id] && questionListMap[visit.Id].length === 0"
            :loading="btnLoading"
            size="small"
            type="primary"
            @click="handleBatchSave(visit.Id, visit.VisitNum)"
          >
            {{ $t('common:button:batchSave') }}
          </el-button>
          <!-- 复制 -->
          <el-button
            v-show="visitPlanOptions.length > 1"
            v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']"
            :disabled="btnLoading || questionListMap[visit.Id] && questionListMap[visit.Id].length === 0"
            :loading="btnLoading"
            size="small"
            type="primary"
            @click="handleCopy(visit.VisitNum)"
          >
            {{ $t('common:button:copy') }}
          </el-button>
          <!-- 应用到随访 -->
          <el-button
            v-show="visitPlanOptions.length > 1 && visit.VisitNum === 0"
            v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']"
            :disabled="btnLoading || questionListMap[visit.Id] && questionListMap[visit.Id].length === 0"
            :loading="btnLoading"
            size="small"
            type="primary"
            @click="applyToFollowup"
          >
            {{ $t('trials:adRules:button:applyToFollowup') }}
          </el-button>
        </div>
        <el-collapse v-if="questionListMap[visit.Id]" v-model="visitActiveNamesMap[visit.Id]" style="border-top:none;">
          <el-collapse-item v-for="(item, index) of questionListMap[visit.Id]"
            :key="item.ReadingQuestionTrialId"
            style="position: relative;padding:0 10px;" :name="item.ReadingQuestionTrialId">
            <div slot="title">
              {{ item.PageName }}Q{{ index + 1 }}：{{ item.QuestionName }}
            </div>
            <div style="position: relative">
              <el-button v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']"
                style="position: absolute; right: 0; top: 0; z-index: 10" size="mini" type="primary"
                :disabled="isSign"
                @click="visitApply(item.ReadingQuestionTrialId, index, visit.Id, visit.VisitNum)">{{ $t('common:button:save')
                }}</el-button>
              <el-button v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']"
                style="position: absolute; right: 60px; top: 0; z-index: 10" size="mini" type="primary"
                :disabled="isSign"
                @click="visitReset(item.ReadingQuestionTrialId, index, visit.Id, visit.VisitNum)">{{ $t('common:button:reset')
                }}</el-button>
              <el-form-item :label-width="'280px'" :label="$t('trials:adRules:title:judgeTypeEnum')" style="width: 95%">
                <el-radio-group
                  v-model="questionListMap[visit.Id][index].JudgeType"
                  @input="(val) => visitJudgeTypeChange(val, index, visit.Id)"
                >
                  <template v-for="judgeTypeItem of $d.JudgeTypeEnum">
                    <el-radio 
                      style="margin-bottom: 5px" 
                      :key="judgeTypeItem.id" 
                      :disabled="isSign || !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])" 
                      :label="judgeTypeItem.value" 
                      v-if="
                        (['number', 'calculation'].includes(questionListMap[visit.Id][index].Type)
                          ? [1, 4, 5, 6]
                          : [1, 2, 3, 6]
                        ).includes(judgeTypeItem.value)
                      "
                    >
                      {{ judgeTypeItem.label }}
                    </el-radio>
                  </template>
                </el-radio-group>
              </el-form-item>
            </div>
            <div v-if="questionListMap[visit.Id][index].JudgeType === 3" style="text-align: right; margin: 10px 0">
              <el-button v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']" size="mini" type="primary"
                :disabled="isSign"
                @click="visitAddGroup(index, null, visit.Id)">{{ $t('trials:adRules:button:addRule')
                }}</el-button>
            </div>
            <el-table v-if="questionListMap[visit.Id][index].JudgeType === 3" v-loading="loading"
              :data="questionListMap[visit.Id][index].AnswerGroupList" border stripe>
              <el-table-column prop="AnswerGroupA" :label="$t('trials:adRules:title:order')" width="160">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="AnswerGroupA" :label="$t('trials:adRules:title:answerGroupA')" min-width="100">
                <template slot-scope="scope">
                  {{
                    questionListMap[visit.Id][index].QuestionGenre === 3
                      ? scope.row.AnswerGroupA.map((v) =>
                        $fd(questionListMap[visit.Id][index].DictionaryCode, parseInt(v))
                      ).toString()
                      : scope.row.AnswerGroupA.toString()
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="AnswerGroupB" :label="$t('trials:adRules:title:answerGroupB')" min-width="100">
                <template slot-scope="scope">
                  {{
                    questionListMap[visit.Id][index].QuestionGenre === 3
                      ? scope.row.AnswerGroupB.map((v) =>
                        $fd(questionListMap[visit.Id][index].DictionaryCode, parseInt(v))
                      ).toString()
                      : scope.row.AnswerGroupB.toString()
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="AnswerGroupB" :label="$t('common:action:action')" min-width="80">
                <template slot-scope="scope">
                  <el-button icon="el-icon-edit" circle :title="$t('common:button:edit')" size="mini"
                    :disabled="isSign"
                    @click="visitAddGroup(index, scope.$index, visit.Id)" />
                  <el-button icon="el-icon-delete" circle :title="$t('common:button:delete')" size="mini"
                    :disabled="isSign"
                    @click="visitTagClose(index, scope.$index, visit.Id)" />
                </template>
              </el-table-column>
            </el-table>
            <div v-if="questionListMap[visit.Id][index].JudgeType === 2">
              <div style="
                  background: #f6f6f6;
                  border-radius: 20px;
                  padding: 15px 20px;
                  margin-top: 10px;
                ">
                <el-checkbox-group v-if="questionListMap[visit.Id][index].QuestionGenre === 3"
                  v-model="questionListMap[visit.Id][index].grouping"
                >
                  <template v-for="dictItem of $d[questionListMap[visit.Id][index].DictionaryCode]">
                    <el-checkbox v-if="dictItem.value !== -1" :key="dictItem.id" :disabled="isSign"
                      :label="dictItem.value">{{ dictItem.label }}</el-checkbox>
                  </template>
                </el-checkbox-group>
                <el-checkbox-group v-else v-model="questionListMap[visit.Id][index].grouping">
                  <el-checkbox v-for="answerItem of item.TypeValue.split('|')" :key="answerItem"
                    :disabled="isSign" :label="answerItem">{{ answerItem }}</el-checkbox>
                </el-checkbox-group>
                <div style="margin-top: 20px">
                  {{ $t('trials:adRules:title:selectAnswerGroup') }}
                  <el-tag v-if="
                    questionListMap[visit.Id][index].grouping.length > 0 &&
                    questionListMap[visit.Id][index].QuestionGenre !== 3
                  ">{{
                    questionListMap[visit.Id][index].grouping.toString().replaceAll(',', '|')
                    }}</el-tag>
                  <el-tag v-if="
                    questionListMap[visit.Id][index].grouping.length > 0 &&
                    questionListMap[visit.Id][index].QuestionGenre === 3
                  ">{{
                    questionListMap[visit.Id][index].grouping
                        .map(
                          (v) =>
                            $d[questionListMap[visit.Id][index].DictionaryCode].find(
                              (v1) => v1.value === v
                            ).label
                        )
                        .toString()
                        .replaceAll(',', '|')
                    }}</el-tag>
                  <el-button size="mini" type="primary" :disabled="isSign"
                    @click="visitAddGroup2(index, visit.Id)">
                    {{ $t('trials:adRules:title:addGroup') }}</el-button>
                </div>
              </div>
              <div v-if="questionListMap[visit.Id][index].QuestionGenre !== 3" style="margin-top: 20px">
                {{ $t('trials:adRules:title:group') }}
                <el-tag v-for="(itemA, indexA) of questionListMap[visit.Id][index].AnswerGroup2List"
                  :key="visit.Id+indexA" closable
                  style="margin-right: 10px" @close="() => visitTagClose2(index, indexA, visit.Id)">{{ itemA }}</el-tag>
              </div>
              <div v-if="questionListMap[visit.Id][index].QuestionGenre === 3" style="margin-top: 20px">
                {{ $t('trials:adRules:title:group') }}
                <el-tag v-for="(itemA, indexA) of questionListMap[visit.Id][index].AnswerGroup2List"
                  :key="visit.Id+indexA" closable
                  style="margin-right: 10px" @close="() => visitTagClose2(index, indexA, visit.Id)">
                  {{
                    itemA
                      .split('|')
                      .map((v) =>
                        $fd(questionListMap[visit.Id][index].DictionaryCode, parseInt(v))
                      )
                      .join('|')
                  }}
                </el-tag>
              </div>
            </div>
            <div v-if="
              questionListMap[visit.Id][index].JudgeType === 4 ||
              questionListMap[visit.Id][index].JudgeType === 5
            ">
              <el-form :inline="true" :model="questionListMap[visit.Id][index]" class="demo-form-inline"
                :ref="`JudgeDifferenceValue${questionListMap[visit.Id][index].JudgeType}_${visit.Id}_${index}`"
                :rules="JudgeDifferenceValueQRules">
                <el-form-item :label="$t(
                  `trials:trials-panel:setting:reading-unit:JudgeDifferenceType`
                )
                  " prop="JudgeDifferenceType">
                  <el-select
                    v-model="questionListMap[visit.Id][index].JudgeDifferenceType"
                    :disabled="isSign">
                    <el-option v-for="judgeDiffItem of $d.JudgeDifferenceType" :key="judgeDiffItem.id"
                      :label="judgeDiffItem.label" :value="judgeDiffItem.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t(
                  `trials:trials-panel:setting:reading-unit:JudgeDifferenceValue${questionListMap[visit.Id][index].JudgeType}`
                )
                  " prop="JudgeDifferenceValue">
                  <div style="display: flex">
                    <el-input v-model="questionListMap[visit.Id][index].JudgeDifferenceValue" clearable
                      :disabled="isSign"></el-input>
                    <span style="margin-left: 10px"
                      v-if="questionListMap[visit.Id][index].JudgeType !== 5 && questionListMap[visit.Id][index].Unit !== 0">
                      {{ `${questionListMap[visit.Id][index].Unit === 4 ? questionListMap[visit.Id][index].CustomUnit : $fd('ValueUnit', questionListMap[visit.Id][index].Unit)}` }}
                    </span>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-tab-pane>
    </el-tabs>
    <el-dialog v-if="questionVisible" :title="$t('trials:adRules:title:selectAnswer')" :visible.sync="questionVisible"
      width="800px" :close-on-click-modal="false" custom-class="base-dialog-wrapper" append-to-body>
      <div class="base-dialog-body">
        <el-form-item label-width="110px" :label="$t('trials:adRules:title:answerGroupA')">
          <el-checkbox-group v-model="questionList[selectIndex].groupingA">
            <template v-for="item of questionList[selectIndex].TypeValue.split('|') || []">
              <el-checkbox 
                v-if="questionList[selectIndex].QuestionGenre !== 3" 
                :key="item" 
                :label="item" 
                :disabled="questionList[selectIndex]?.groupingB?.includes(item) ?? false"
              >
              {{ item }}
            </el-checkbox>
            </template>
            <template v-for="item of $d[questionList[selectIndex].DictionaryCode]">
              <el-checkbox 
                v-if="questionList[selectIndex].QuestionGenre === 3 &&  item.value !== -1" 
                :key="item.id" 
                :label="item.value" 
                :disabled="questionList[selectIndex]?.groupingB?.includes(item.value) ?? false"
                >{{ item.label }}</el-checkbox>
            </template>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label-width="110px" :label="$t('trials:adRules:title:answerGroupB')">
          <el-checkbox-group v-model="questionList[selectIndex].groupingB">
            <template v-for="item of questionList[selectIndex].TypeValue.split('|') || []">
              <el-checkbox 
                v-if="questionList[selectIndex].QuestionGenre !== 3" 
                :key="item" 
                :label="item" 
                :disabled="questionList[selectIndex]?.groupingA?.includes(item) ?? false"
                >
                {{ item }}
              </el-checkbox>
            </template>
            <template v-for="item of $d[questionList[selectIndex].DictionaryCode]">
              <el-checkbox 
                v-if="questionList[selectIndex].QuestionGenre === 3 && item.value !== -1" 
                :key="item.id" 
                :label="item.value" 
                :disabled="questionList[selectIndex]?.groupingA?.includes(item.value) ?? false"
                >
                {{ item.label }}
              </el-checkbox>
            </template>
          </el-checkbox-group>
        </el-form-item>
      </div>
      <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
        <el-button v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']" :disabled="btnLoading" size="small"
          type="primary" @click="
            questionVisible = false
            $set(questionList[selectIndex], 'groupingA', [])
            $set(questionList[selectIndex], 'groupingB', [])
            ">
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']" :disabled="btnLoading" size="small"
          type="primary" @click="save">
          {{ $t('common:button:save') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="copyVisible"
      :title="$t('common:button:copy')"
      :visible.sync="copyVisible"
      width="500px"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      append-to-body
    >
      <div class="base-dialog-body">
        <el-form label-width="100px">
          <el-form-item :label="$t('trials:trials-panel:setting:reading-unit:targetVisitNum')">
            <el-select v-model="copySourceVisitNum" style="width: 100%" filterable>
              <el-option
                v-for="visit in copySourceVisitOptions"
                :key="visit.Id"
                :label="visit.VisitName"
                :value="visit.VisitNum"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
        <el-button
          v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']"
          :disabled="btnLoading"
          size="small"
          @click="closeCopyDialog"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          v-hasPermi="['trials:trials-panel:setting:reading-unit:edit']"
          :disabled="btnLoading"
          :loading="btnLoading"
          size="small"
          type="primary"
          @click="confirmCopy"
        >
          {{ $t('common:button:confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
/* eslint-disable */
import {
  getTrialQuestionVisitJudgeRule,
  setTrialQuestionVisitJudgeRule,
  copyTrialQuestionVisitJudgeRule,
  applyBaseLineTrialQuestionVisitJudgeRule
} from '@/api/trials/reading'
import { getTrialVisitStageSelect } from '@/api/trials'

export default {
  props: {
    trialReadingCriterionId: {
      type: String,
      default: '',
    },
    isSign: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      btnLoading: false,
      loading: false,
      activeVisitTab: '',
      visitActiveNamesMap: {},
      questionListMap: {},
      visitPlanOptions: [],
      questionVisible: false,
      copyVisible: false,
      copyTargetVisitNum: null,
      copySourceVisitNum: null,
      selectIndex: 0,
      indexA: null,
      selectVisitKey: '',
      type: null,
      OtherInfo: {
        IsSign: true,
      },
      JudgeDifferenceValueQRules: {
        JudgeDifferenceType: [
          {
            required: true,
            message: this.$t(
              'trials:trials-list:setitng:JudgeDifferenceTypeRequired'
            ),
            trigger: 'blur',
          },
        ],
        JudgeDifferenceValue: [
          {
            required: true,
            message: this.$t(
              'trials:trials-list:setitng:JudgeDifferenceValueRequired'
            ),
            trigger: 'blur',
          },
          {
            pattern: /^[0-9]+(.[0-9]{2})?$/,
            message: this.$t('trials:trials-list:setitng:JudgeDifferenceValue'),
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(
                  new Error(
                    this.$t(
                      'trials:trials-list:setitng:JudgeDifferenceValueMin'
                    )
                  )
                )
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {
    questionList() {
      return this.questionListMap[this.selectVisitKey]
    },
    copySourceVisitOptions() {
      return this.visitPlanOptions.filter((visit) => visit.VisitNum !== this.copyTargetVisitNum)
    }
  },
  watch: {
    async activeVisitTab(v) {
      if (!v) return
      if (this.questionListMap[v]) {
        return
      }
      await this.getList(v)
    },
  },
  async mounted() {
    await this.initData()
  },
  methods: {
    async initData() {
      this.questionListMap = {}
      this.visitActiveNamesMap = {}
      this.activeVisitTab = ''
      await this.getVisitPlanOptions()
    },
    resetVisitJudgeTypeRelatedFields(question = {}) {
      this.$set(question, 'AnswerGroup2List', [])
      this.$set(question, 'AnswerGroupList', [])
      this.$set(question, 'grouping', [])
      this.$set(question, 'groupingA', [])
      this.$set(question, 'groupingB', [])
      this.$set(question, 'JudgeDifferenceValue', null)
      this.$set(question, 'JudgeDifferenceType', 0)
    },
    normalizeQuestionList(questionList = []) {
      return questionList.map((item) => ({
        ...item,
        grouping: [],
        groupingA: [],
        groupingB: [],
        AnswerGroupList: Array.isArray(item.AnswerCombination)
          ? item.AnswerCombination.map((group) => ({
            ...group,
            AnswerGroupA: Array.isArray(group.AnswerGroupA)
              ? [...group.AnswerGroupA]
              : group.AnswerGroupA,
            AnswerGroupB: Array.isArray(group.AnswerGroupB)
              ? [...group.AnswerGroupB]
              : group.AnswerGroupB
          }))
          : [],
        AnswerGroup2List: Array.isArray(item.AnswerGroup)
          ? [...item.AnswerGroup]
          : []
      }))
    },
    closeCopyDialog() {
      this.copyVisible = false
      this.copyTargetVisitNum = null
      this.copySourceVisitNum = null
    },
    async getVisitPlanOptions() {
      try {
        const trialId = this.$route.query.trialId
        const res = await getTrialVisitStageSelect(trialId)
        if (res.IsSuccess) {
          this.visitPlanOptions = res.Result || []
          if (!this.activeVisitTab && this.visitPlanOptions.length > 0) {
            this.activeVisitTab = this.visitPlanOptions[0].Id
          }
          const outOfPlan = {
            "Id": "00000000-0000-0000-0000-000000000000",
            "VisitNum": -1,
            "VisitName": "Out of Plan",
            "IsBaseLine": false
          }
          const isExists = this.visitPlanOptions.some(x => x.Id === outOfPlan.Id);
          if (!isExists) {
            this.visitPlanOptions.push(outOfPlan);
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    getVisitById(visitKey) {
      return this.visitPlanOptions.find((visit) => visit.Id === visitKey)
    },
    async getList(visitKey = this.activeVisitTab) {
      const visit = this.getVisitById(visitKey)
      if (!visit) return
      try {
        this.loading = true
        let params = {
          trialId: this.$route.query.trialId,
          trialReadingCriterionId: this.trialReadingCriterionId,
          visitNum: visit.VisitNum
        }
        const res = await getTrialQuestionVisitJudgeRule(params)
        const questionList = this.normalizeQuestionList(res.Result)
        this.$set(this.questionListMap, visitKey, questionList)
        this.$set(
          this.visitActiveNamesMap,
          visitKey,
          questionList.map((item) => item.ReadingQuestionTrialId)
        )
      } catch (e) {
        console.log(e)
      } finally {
        this.loading = false
      }
    },
    changeArbitrationRule(value) {
      if (value !== 1) {
        Object.values(this.questionListMap).forEach((questionList) => {
          questionList.forEach((item) => {
            item.JudgeDifferenceValue = 0
            item.JudgeDifferenceType = 0
          })
        })
      }
    },
    visitJudgeTypeChange(value, index, visitKey) {
      this.resetVisitJudgeTypeRelatedFields(this.questionListMap[visitKey][index])
      this.$nextTick(() => {
        if (value === 4 || value === 5) {
          const refName = `JudgeDifferenceValue${value}_${visitKey}_${index}`
          if (this.$refs[refName] && this.$refs[refName][0]) {
            this.$refs[refName][0].resetFields()
          }
        }
      })
    },
    // async saveAllSync(showMessage = false) {
    //   try {
    //     this.btnLoading = true
    //     this.loading = true
    //     for (let i = 0; i < this.visitPlanOptions.length; i++) {
    //       const visit = this.visitPlanOptions[i]
    //       if (!this.questionListMap[visit.Id]) {
    //         await this.getList(visit.Id)
    //       }
    //       const questionList = this.questionListMap[visit.Id] || []
    //       if (questionList.length === 0) {
    //         continue
    //       }
    //       for (let index = 0; index < questionList.length; index++) {
    //         if (questionList[index].JudgeType === 0) {
    //           this.activeVisitTab = visit.Id
    //           this.$alert(this.$t('trials:adRules:message:msg8'))
    //           return false
    //         }
    //         if (
    //           questionList[index].JudgeType === 2 &&
    //           questionList[index].AnswerGroup2List.length === 0
    //         ) {
    //           this.activeVisitTab = visit.Id
    //           this.$alert(this.$t('trials:adRules:message:msg8'))
    //           return false
    //         }
    //         if (
    //           questionList[index].JudgeType === 3 &&
    //           questionList[index].AnswerGroupList.length === 0
    //         ) {
    //           this.activeVisitTab = visit.Id
    //           this.$alert(this.$t('trials:adRules:message:msg8'))
    //           return false
    //         }
    //         if (
    //           questionList[index].JudgeType === 4 ||
    //           questionList[index].JudgeType === 5
    //         ) {
    //           this.activeVisitTab = visit.Id
    //           await this.$nextTick()
    //           const refName = `JudgeDifferenceValue${questionList[index].JudgeType}_${visit.Id}_${index}`
    //           try {
    //             const validate = await this.$refs[refName][0].validate()
    //             if (!validate) return false
    //           } catch (err) {
    //             return false
    //           }
    //         }
    //       }
    //       let params = {
    //         TrialReadingCriterionId: this.trialReadingCriterionId,
    //         VisitNum: visit.VisitNum,
    //         QuestionList: questionList.map((item) => {
    //           return {
    //             ReadingQuestionTrialId: item.ReadingQuestionTrialId,
    //             AnswerGroup: item.AnswerGroup2List,
    //             AnswerCombination: item.AnswerGroupList,
    //             JudgeType: item.JudgeType,
    //             JudgeDifferenceValue: item.JudgeDifferenceValue,
    //             JudgeDifferenceType: item.JudgeDifferenceType
    //           }
    //         })
    //       }
    //       let res = await setTrialQuestionVisitJudgeRule(params)
    //       if (!res.IsSuccess) {
    //         return false
    //       }
    //     }
    //     if (showMessage) {
    //       this.$message.success(this.$t('common:message:savedSuccessfully'))
    //     }
    //     return true
    //   } catch (e) {
    //     console.log(e)
    //     return false
    //   } finally {
    //     this.btnLoading = false
    //     this.loading = false
    //   }
    // },
    async handleBatchSave(visitKey, visitNum) {
      if (!visitKey) return
      const questionList = this.questionListMap[visitKey] || []
      if (questionList.length === 0) return
      try {
        this.btnLoading = true
        this.loading = true
        for (let index = 0; index < questionList.length; index++) {
          if (questionList[index].JudgeType === 0) {
            this.$alert(this.$t('trials:adRules:message:msg8'))
            return
          }
          if (
            questionList[index].JudgeType === 2 &&
            questionList[index].AnswerGroup2List.length === 0
          ) {
            this.$alert(this.$t('trials:adRules:message:msg8'))
            return
          }
          if (
            questionList[index].JudgeType === 3 &&
            questionList[index].AnswerGroupList.length === 0
          ) {
            this.$alert(this.$t('trials:adRules:message:msg8'))
            return
          }
          if (
            questionList[index].JudgeType === 4 ||
            questionList[index].JudgeType === 5
          ) {
            await this.$nextTick()
            const refName = `JudgeDifferenceValue${questionList[index].JudgeType}_${visitKey}_${index}`
            try {
              const validate = await this.$refs[refName][0].validate()
              if (!validate) return
            } catch (err) {
              return
            }
          }
        }
        let params = {
          TrialReadingCriterionId: this.trialReadingCriterionId,
          VisitNum: visitNum,
          QuestionList: questionList.map((item) => {
            return {
              ReadingQuestionTrialId: item.ReadingQuestionTrialId,
              AnswerGroup: item.AnswerGroup2List,
              AnswerCombination: item.AnswerGroupList,
              JudgeType: item.JudgeType,
              JudgeDifferenceValue: item.JudgeDifferenceValue,
              JudgeDifferenceType: item.JudgeDifferenceType
            }
          })
        }
        let res = await setTrialQuestionVisitJudgeRule(params)
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        }
      } catch (e) {
        console.log(e)
      } finally {
        this.btnLoading = false
        this.loading = false
      }
    },
    save() {
      const questionList = this.questionList
      let index = this.selectIndex
      let indexA = this.indexA
      if (questionList[index].groupingA.length === 0) {
        this.$alert(this.$t('trials:adRules:message:msg2'))
        return
      }
      if (questionList[index].groupingB.length === 0) {
        this.$alert(this.$t('trials:adRules:message:msg3'))
        return
      }
      if (this.type === 'add') {
        questionList[index].AnswerGroupList.push({
          AnswerGroupA: questionList[index].groupingA,
          AnswerGroupB: questionList[index].groupingB
        })
      } else {
        this.$set(
          questionList[index].AnswerGroupList[indexA],
          'AnswerGroupA',
          questionList[index].groupingA
        )
        this.$set(
          questionList[index].AnswerGroupList[indexA],
          'AnswerGroupB',
          questionList[index].groupingB
        )
      }
      this.$set(questionList[index], 'groupingA', [])
      this.$set(questionList[index], 'groupingB', [])
      this.$message.success(this.$t('trials:adRules:message:msg4'))
      this.questionVisible = false
    },
    handleCopy(visitNum) {
      this.copyTargetVisitNum = visitNum
      this.copyVisible = true
    },
    async confirmCopy() {
      if (!this.copySourceVisitNum) {
        this.$alert(this.$t('trials:setting:reading-unit:msg1'))
        return
      }
      try {
        this.btnLoading = true
        this.loading = true
        const params = {
          trialReadingCriterionId: this.trialReadingCriterionId,
          sourceVisitNum: this.copySourceVisitNum,
          targetVisitNum: this.copyTargetVisitNum
        }
        const res = await copyTrialQuestionVisitJudgeRule(params)
        if (res.IsSuccess) {
          await this.getList(this.activeVisitTab)
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.closeCopyDialog()
        }
      } catch (e) {
        console.log(e)
      } finally {
        this.btnLoading = false
        this.loading = false
      }
    },
    async applyToFollowup() {
      try {
        await this.$confirm(
          this.$t('trials:adRules:message:msg10'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
          }
        )
        this.btnLoading = true
        this.loading = true
        const res = await applyBaseLineTrialQuestionVisitJudgeRule({
          trialReadingCriterionId: this.trialReadingCriterionId
        })
        if (res.IsSuccess) {
          this.questionListMap = {}
          this.visitActiveNamesMap = {}
          if (this.activeVisitTab) {
            await this.getList(this.activeVisitTab)
          }
          this.$message.success(this.$t('trials:adRules:message:msg9'))
        }
      } catch (e) {
        if (e === 'cancel') return
        console.log(e)
      } finally {
        this.btnLoading = false
        this.loading = false
      }
    },
    visitTagClose2(index, indexA, visitKey) {
      this.$confirm(this.$t('trials:adRules:message:msg1')).then(() => {
        this.questionListMap[visitKey][index].AnswerGroup2List.splice(indexA, 1)
      })
    },
    visitTagClose(index, indexA, visitKey) {
      this.$confirm(this.$t('trials:adRules:message:msg1')).then(() => {
        this.questionListMap[visitKey][index].AnswerGroupList.splice(indexA, 1)
      })
    },
    visitAddGroup2(index, visitKey) {
      const questionList = this.questionListMap[visitKey]
      if (questionList[index].grouping.length === 0) {
        this.$alert(this.$t('trials:adRules:message:msg5'))
        return
      }
      let grouping = questionList[index].grouping
        .toString()
        .replaceAll(',', '|')
      questionList[index].AnswerGroup2List.push(`|${grouping}|`)
      this.$set(questionList[index], 'grouping', [])
    },
    visitAddGroup(index, indexA, visitKey) {
      const questionList = this.questionListMap[visitKey]
      this.selectIndex = index
      this.selectVisitKey = visitKey
      this.type = 'add'
      if (indexA !== null) {
        this.indexA = indexA
        this.type = 'edit'
        this.$set(
          questionList[index],
          'groupingA',
          questionList[index].AnswerGroupList[indexA].AnswerGroupA
        )
        this.$set(
          questionList[index],
          'groupingB',
          questionList[index].AnswerGroupList[indexA].AnswerGroupB
        )
      }
      this.questionVisible = true
    },
    async visitReset(ReadingQuestionTrialId, index, visitKey, visitNum) {
      const questionList = this.questionListMap[visitKey]
      this.btnLoading = true
      this.loading = true
      try {
        await this.$confirm(this.$t('trials:adRules:message:msg6'))
        const params = {
          TrialReadingCriterionId: this.trialReadingCriterionId,
          VisitNum: visitNum,
          QuestionList: [
            {
              ReadingQuestionTrialId: ReadingQuestionTrialId,
              AnswerGroup: [],
              AnswerCombination: [],
              JudgeType: 0,
              JudgeDifferenceValue: 0,
              JudgeDifferenceType: 0
            }
          ]
        }
        await setTrialQuestionVisitJudgeRule(params)
        this.$set(questionList[index], 'AnswerGroup2List', [])
        this.$set(questionList[index], 'AnswerGroupList', [])
        this.$set(questionList[index], 'JudgeType', 0)
        this.$set(questionList[index], 'JudgeDifferenceValue', 0)
        this.$set(questionList[index], 'JudgeDifferenceType', 0)

        this.$message.success(this.$t('trials:adRules:message:msg7'))
      } catch(e) {
        console.log(e)
      } finally {
        this.btnLoading = false
        this.loading = false
      }
    },
    async visitApply(ReadingQuestionTrialId, index, visitKey, visitNum) {
      try {
        const questionList = this.questionListMap[visitKey]
        if (questionList[index].JudgeType === 0) {
          this.$alert(this.$t('trials:adRules:message:msg8'))
          return
        }
        if (
          questionList[index].JudgeType === 2 &&
          questionList[index].AnswerGroup2List.length === 0
        ) {
          this.$alert(this.$t('trials:adRules:message:msg8'))
          return
        }
        if (
          questionList[index].JudgeType === 3 &&
          questionList[index].AnswerGroupList.length === 0
        ) {
          this.$alert(this.$t('trials:adRules:message:msg8'))
          return
        }
        if (
          questionList[index].JudgeType === 4 ||
          questionList[index].JudgeType === 5
        ) {
          const refName = `JudgeDifferenceValue${questionList[index].JudgeType}_${visitKey}_${index}`
          const validate = await this.$refs[refName][0].validate()
          if (!validate) return
        }
        this.btnLoading = true
        this.loading = true
        let params = {
          TrialReadingCriterionId: this.trialReadingCriterionId,
          VisitNum: visitNum,
          QuestionList: [
            {
              ReadingQuestionTrialId: ReadingQuestionTrialId,
              AnswerGroup: questionList[index].AnswerGroup2List,
              AnswerCombination: questionList[index].AnswerGroupList,
              JudgeType: questionList[index].JudgeType,
              JudgeDifferenceValue: questionList[index].JudgeDifferenceValue,
              JudgeDifferenceType: questionList[index].JudgeDifferenceType
            }
          ]
        }
        let res = await setTrialQuestionVisitJudgeRule(params)
        if (res.IsSuccess) {
          this.$message.success(this.$t('trials:adRules:message:msg9'))
        }
      } catch(e) {
        console.log(e)
      } finally {
        this.btnLoading = false
        this.loading = false
      }
    }
  },
}
</script>
<style scoped>
.visit-tabs-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  padding: 0 10px;
}

.visit-tabs ::v-deep .el-tabs__content {
  min-height: 520px;
  padding-top: 20px !important;
}
</style>
