<template>
  <box-content v-loading="loading" class="medical-audit-setting">
    <!-- 搜索框 -->
    <el-tabs v-model="trialReadingCriterionId" type="border-card">
      <el-tab-pane v-for="i of trialCriterionList" :key="i.TrialReadingCriterionId" :label="i.TrialReadingCriterionName" :name="i.TrialReadingCriterionId">
        <div class="search">
          <el-form
            :inline="true"
            class="base-search-form"
          >
            <!-- 审核问题 -->
            <el-form-item
              :label="$t('trials:MIMqcCfg:table:questionName')"
              style="margin-top: 10px"
            >
              <el-input
                v-model="searchData.QuestionName"
                clearable
                style="width:120px;"
              />
            </el-form-item>
            <!-- 类型 -->
            <el-form-item
              :label="$t('trials:medicalFeedbackCfg:title:taskType')"
              style="margin-top: 10px"
            >
              <el-select
                v-model="searchData.ReadingCategory"
                clearable
              >
                <el-option
                  v-for="item of $d.ReadingCategory"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
<!--            <el-form-item-->
<!--              :label="$t('trials:qcCfg:table:isEnable')"-->
<!--            >-->
<!--              <el-select-->
<!--                v-model="searchData.IsEnable"-->
<!--                clearable-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="item of $d.YesOrNo"-->
<!--                  :key="item.value"-->
<!--                  :value="item.value"-->
<!--                  :label="item.label"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item
              :label="$t('trials:qcCfg:table:isRequired')"
              style="margin-top: 10px"
            >
              <el-select
                v-model="searchData.IsRequired"
                clearable
              >
                <el-option
                  v-for="item of $d.YesOrNo"
                  :key="`IsRequired${item.value}`"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-top: 10px">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
              >
                {{ $t('common:button:search') }}
              </el-button>
              <el-button
                type="primary"
                icon="el-icon-refresh-left"
                @click="handleReset"
              >
                {{ $t('common:button:reset') }}
              </el-button>
              <!-- 预览 -->
              <el-button
                :disabled="!otherInfo.IsHaveQuestion"
                type="primary"
                icon="el-icon-view"
                @click="preview.visible = true"
              >
                {{ $t('common:button:preview') }}
              </el-button>
              <el-button
                v-if="i.CriterionType!==0&&!otherInfo.IsConfirmMedicineQuestion && hasPermi(['trials:trials-panel:setting:medical-audit:confirm'])"
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
              >
                {{ $t('trials:qcCfg:button:default') }}
              </el-button>
              <el-button
                v-if="!otherInfo.IsConfirmMedicineQuestion && hasPermi(['trials:trials-panel:setting:medical-audit:confirm'])"
                type="primary"
                icon="el-icon-plus"
                @click="handleCustomQS"
              >
                {{ $t('trials:qcCfg:button:custom') }}
              </el-button>
              <el-button
                v-if="!otherInfo.IsConfirmMedicineQuestion && hasPermi(['trials:trials-panel:setting:medical-audit:confirm'])"
                :disabled="list.length === 0"
                type="primary"
                icon="el-icon-delete"
                @click="handleBatchDelete"
              >
                {{ $t('common:button:batchDelete') }}
              </el-button>
              <el-button
                v-if="!otherInfo.IsConfirmMedicineQuestion && hasPermi(['trials:trials-panel:setting:medical-audit:confirm'])"
                :disabled="!otherInfo.IsHaveQuestion"
                type="danger"
                icon="el-icon-circle-check"
                @click="handleConfirm"
              >
                {{ $t('trials:qcCfg:button:confirm') }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          v-if="isShow"
          v-adaptive="{bottomOffset:65}"
          :data="list"
          stripe
          height="100"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <!-- <el-table-column type="index" width="60" /> -->
          <!-- 序号 -->
          <el-table-column
            prop="ShowOrder"
            :label="$t('trials:qcCfg:table:order')"
            width="60"
          />
          <!-- 审核问题 -->
          <el-table-column
            prop="QuestionName"
            :label="$t('trials:MIMqcCfg:table:questionName')"
            show-overflow-tooltip
            min-width="260"
          />
<!--          &lt;!&ndash; 审核问题 &ndash;&gt;-->
<!--          <el-table-column-->
<!--            prop="LanguageType"-->
<!--            :label="$t('common:title:languageType')"-->
<!--            show-overflow-tooltip-->
<!--          >-->
<!--            <template slot-scope="scope">-->
<!--              {{ $fd('LanguageType', scope.row.LanguageType) }}-->
<!--            </template>-->
<!--          </el-table-column>-->
          <!-- 类型 -->
          <el-table-column
            prop="Type"
            :label="$t('trials:qcCfg:table:type')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ $fd('QcType', scope.row.Type) }}
            </template>
          </el-table-column>
          <!-- 选项 -->
          <el-table-column
            prop="TypeValue"
            :label="$t('trials:qcCfg:table:typeValue')"
            show-overflow-tooltip
          />
          <!-- 任务类型 -->
          <el-table-column
            prop="ReadingCategory"
            :label="$t('trials:medicalFeedbackCfg:title:taskType')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.ReadingCategory === 1" type="primary">
                {{ $fd('ReadingCategory', scope.row.ReadingCategory) }}
              </el-tag>
              <el-tag v-if="scope.row.ReadingCategory === 2" type="info">
                {{ $fd('ReadingCategory', scope.row.ReadingCategory) }}
              </el-tag>
              <el-tag v-if="scope.row.ReadingCategory === 4" type="danger">
                {{ $fd('ReadingCategory', scope.row.ReadingCategory) }}
              </el-tag>
              <el-tag v-if="scope.row.ReadingCategory === 5" type="warning">
                {{ $fd('ReadingCategory', scope.row.ReadingCategory) }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 父问题 -->
          <el-table-column
            prop="ParentShowOrder"
            :label="$t('trials:qcCfg:table:parentQs')"
            show-overflow-tooltip
          />
          <!-- 父问题触发值 -->
          <el-table-column
            prop="ParentTriggerValue"
            :label="$t('trials:qcCfg:table:parentTriggerValue')"
            show-overflow-tooltip
          />
          <!-- 是否必填 -->
          <el-table-column
            prop="IsRequired"
            :label="$t('trials:qcCfg:table:isRequired')"
          >
            <template slot-scope="scope">
              {{ $fd('YesOrNo', scope.row.IsRequired) }}
            </template>
          </el-table-column>
<!--          &lt;!&ndash; 启用状态 &ndash;&gt;-->
<!--          <el-table-column-->
<!--            prop="IsEnable"-->
<!--            :label="$t('trials:qcCfg:table:isEnable')"-->
<!--          >-->
<!--            <template slot-scope="scope">-->
<!--              {{ $fd('YesOrNo', scope.row.IsEnable) }}-->
<!--            </template>-->
<!--          </el-table-column>-->

          <el-table-column
            v-if="!otherInfo.IsConfirmMedicineQuestion && hasPermi(['trials:trials-panel:setting:medical-audit:confirm'])"
            :label="$t('common:action:action')"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                circle
                :title="$t('common:button:edit')"
                icon="el-icon-edit-outline"
                @click="handleEdit(scope.row)"
              />
              <el-button
                circle
                :title="$t('common:button:delete')"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              />

            </template>
          </el-table-column>
        </el-table>
        <Pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
      </el-tab-pane>
    </el-tabs>
    <!-- 新增默认问题 -->
    <el-dialog
      v-if="addVisible"
      :visible.sync="addVisible"
      width="500px"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="$t('trials:mimCfg:title:addDefault')"
    >
<!--        <DefaultQS :trial-reading-criterion-id="trialReadingCriterionId" :current-criterion-type="CurrentCriterionType" @getList="getList" @close="addVisible = false" />-->
        <DefaultQS :other-info="otherInfo" :trial-reading-criterion-id="trialReadingCriterionId" @getList="getList" @close="addVisible = false" />
    </el-dialog>

    <!-- 新增/编辑问题 -->
    <el-dialog
      v-if="qsForm.visible"
      :visible.sync="qsForm.visible"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="qsForm.title"
      width="600px"
    >
      <QSForm :trial-reading-criterion-id="trialReadingCriterionId" :data="currentRow" @getList="getList" @close="qsForm.visible = false" />
    </el-dialog>

    <!-- 预览模板 -->
    <el-dialog
      v-if="preview.visible"
      :visible.sync="preview.visible"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="preview.title"
      width="600px"
    >
      <div class="base-dialog-body">
        <QuestionsPreview :trial-reading-criterion-id="trialReadingCriterionId" />
      </div>
    </el-dialog>

    <!--签名框 -->
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      custom-class="base-dialog-wrapper"
    >
      <div slot="title">
        <span
          style="font-size:18px;"
        >
          {{ $t('common:dialogTitle:sign') }}
        </span>
        <span
          style="font-size:12px;margin-left:5px"
        >
          {{ `(${$t('common:label:sign')}${ currentUser })` }}
        </span>
      </div>
      <SignForm
        ref="signForm"
        :sign-code-enum="signCode"
        @closeDialog="closeSignDialog"
      />
    </el-dialog>
  </box-content>
</template>
<script>
import { addDefaultQuestions , batchDeteteCriterionMedicineQuestion, getReadingMedicineTrialQuestionList, deleteReadingMedicineTrialQuestion, confirmReadingMedicineQuestion, verifyReadingMedicineQuestion, verifyIsCanConfirm } from '@/api/trials'
import { getTrialCriterionList } from '@/api/trials/reading'
import BoxContent from '@/components/BoxContent'
import DefaultQS from './components/DefaultQsLang'
import QSForm from './components/QSForm'
import Pagination from '@/components/Pagination'
import QuestionsPreview from './components/QuestionsPreview'
import SignForm from '@/views/trials/components/newSignForm'
import const_ from '@/const/sign-code';
const searchDataDefault = () => {
  return {
    QuestionName: '',
    LanguageType: null,
    ReadingCategory: null,
    Type: '',
    IsEnable: null,
    PageIndex: 1,
    PageSize: 10
  }
}
export default {
  name: 'MedicalAuditQS',
  components: { Pagination, BoxContent, DefaultQS, QSForm, QuestionsPreview, SignForm },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      addVisible: false,
      btnLoading: false,
      signText: '',
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      otherInfo: {
        IsConfirmMedicineQuestion: true
      },
      trialId: '',
      qsForm: { visible: false, title: '' },
      preview: { visible: false, title: this.$t('common:button:preview') },
      currentRow: {},
      trialCriterionList: [],
      trialReadingCriterionId: '0',
      CurrentCriterionType: null,
      isShow: false,
      selectedList: []
    }
  },
  watch: {
    trialReadingCriterionId(v) {
      this.getList()
      this.CurrentCriterionType = this.trialCriterionList.find(v => {
        return v.TrialReadingCriterionId === this.trialReadingCriterionId
      }).CriterionType
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getTrialCriterionList()
  },
  methods: {
    // 添加默认问题
    addDefaultQuestions(){
      let data = {
        TrialId: this.$route.query.trialId,
        TrialReadingCriterionId: this.trialReadingCriterionId,
        LanguageType: 0
      }
      if( this.otherInfo.LanguageType === null ){
        data.LanguageType = this.$i18n.locale === 'zh' ? 0 : 1
      } else {
        data.LanguageType = this.otherInfo.LanguageType
      }
      addDefaultQuestions(data).then(res => {
        this.$message.success(this.$t('common:message:savedSuccessfully'))
        this.getList();
      })
    },
    handleSelectionChange(value) {
      this.selectedList = value
    },
    handleBatchDelete() {
      if (this.selectedList.length < 1) {
        this.$alert(this.$t('trials:medicalAuditCfg:message:message1'))
      }
      this.$confirm(this.$t('trials:staffResearch:message:confirmDel')).then(() => {
        batchDeteteCriterionMedicineQuestion({
          trialReadingCriterionId: this.trialReadingCriterionId,
          ids: this.selectedList.map(v => v.Id)
        }).then(res => {
          this.$message.success(this.$t('common:message:deletedSuccessfully'))
          this.getList()
        })
      })
    },
    getTrialCriterionList() {
      getTrialCriterionList(this.trialId).then(res => {
        this.trialCriterionList = res.Result
        this.trialReadingCriterionId = this.trialCriterionList[0].TrialReadingCriterionId
        this.CurrentCriterionType = this.trialCriterionList.find(v => {
          return v.TrialReadingCriterionId === this.trialReadingCriterionId
        }).CriterionType
      }).catch(() => {})
    },
    // 获取qc模板信息
    getList() {
      this.loading = true
      this.isShow = false
      this.searchData.TrialId = this.trialId
      this.searchData.TrialReadingCriterionId = this.trialReadingCriterionId
      getReadingMedicineTrialQuestionList(this.searchData).then(res => {
        this.loading = false
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
        this.isShow = true
        // this.otherInfo.IsConfirmMedicineQuestion = false
        this.otherInfo = res.OtherInfo
      }).catch(() => { this.loading = false })
    },
    // 打开系统模板配置项
    handleAdd() {
      // this.addVisible = true
      this.addDefaultQuestions();
    },
    handleEdit(row) {
      this.currentRow = { ...row }
      this.qsForm.title = this.$t('common:button:edit')// '编辑'
      this.qsForm.visible = true
    },
    // 删除qc问题配置项
    handleDelete(row) {
      // 判断该问题是否存在子问题，如果有则不允许删除
      const i = this.list.findIndex(item => item.ParentId === row.Id)
      if (i !== -1) {
        this.$alert(this.$t('trials:qcCfg:message:deleteWarning'))
      } else {
        this.$confirm(this.$t('trials:qcCfg:message:delete'), {
          type: 'warning',
          distinguishCancelAndClose: true
        })
          .then(() => {
            this.loading = true
            var param = {
              trialId: this.trialId,
              id: row.Id
            }
            deleteReadingMedicineTrialQuestion(param)
              .then(res => {
                this.loading = false
                if (res.IsSuccess) {
                  this.getList()
                  this.$message.success(this.$t('common:message:deletedSuccessfully'))
                }
              }).catch(() => { this.loading = false })
          })
      }
    },
    // 打开自定义qc问题配置框
    handleCustomQS() {
      this.currentRow = {}
      this.qsForm.title = this.$t('common:button:new')// '新增'
      this.qsForm.visible = true
    },
    // 查询
    handleSearch() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },

    // 确认前签名
    handleConfirm() {
      if (!this.otherInfo.IsHaveQuestion) {
        // '请先配置医学审核问题再进行确认！'
        this.$alert(this.$t('trials:medicalFeedbackCfg:message:msg1'))
        return
      }
      this.loading = true
      verifyIsCanConfirm({
        TrialReadingCriterionId: this.trialReadingCriterionId
      }).then(res => {
        console.log(res)
        verifyReadingMedicineQuestion({ trialId: this.trialId, TrialReadingCriterionId: this.trialReadingCriterionId }).then(res => {
          this.loading = false
          const { MedicalAuditConfirmation } = const_.processSignature
          this.signCode = MedicalAuditConfirmation
          this.signVisible = true
        }).catch(() => { this.loading = false })
      }).catch(() => { this.loading = false })
    },
    // 关闭签名框并设置确认状态
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名确认
    signConfirm(signInfo) {
      this.loading = true
      const params = {
        data: {
          trialId: this.trialId,
          TrialReadingCriterionId: this.trialReadingCriterionId
        },
        signInfo: signInfo,
        TrialReadingCriterionId: this.trialReadingCriterionId
      }
      confirmReadingMedicineQuestion(params).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
          this.getList()
        }
      }).catch(_ => {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.medical-audit-setting {
  height: 100%;
  background: #fff;
  padding: 0px 10px;
  box-sizing: border-box;
  ::v-deep .search {
    padding: 0px !important;
  }
  ::v-deep .el-tabs--border-card>.el-tabs__content {
    padding: 0px 15px;
  }
}
</style>
