<template>
  <box-content v-loading="loading" style="height: 100%;background: #fff;padding: 10px;box-sizing: border-box">
    <!-- 搜索框 -->
    <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:qcCfg:table:questionName')"
            >
              <el-input :maxLength="$inputMax"
                v-model="searchData.QuestionName"
                clearable
                style="width:120px;"
              />
            </el-form-item>
            <!-- 类型 -->
            <el-form-item
              :label="$t('trials:medicalFeedbackCfg:title:taskType')"
            >
              <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.IsEnable"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              :label="$t('trials:qcCfg:table:isRequired')"
            >
              <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>
              <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-form-item>
          </el-form>
          <span style="margin-left:auto">
            <!-- 预览 -->
            <el-button
              :disabled="otherInfo.QuestionCount===0"
              type="primary"
              icon="el-icon-view"
              @click="preview.visible = true"
            >
              {{ $t('common:button:preview') }}
            </el-button>
            <el-button
              v-if="!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="otherInfo.QuestionCount===0"
              type="danger"
              icon="el-icon-circle-check"
              @click="handleConfirm"
            >
              {{ $t('trials:qcCfg:button:confirm') }}
            </el-button>
          </span>
        </div>
        <el-table
          v-if="isShow"
          v-adaptive="{bottomOffset:75}"
          :data="list"
          stripe
          height="100"
        >
          <!-- <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:qcCfg:table:questionName')"
            show-overflow-tooltip
          />
          <!-- 类型 -->
          <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>
          <!-- 启用状态 -->
          <el-table-column
            prop="IsEnable"
            :label="$t('trials:qcCfg:table:isEnable')"
          >
            <template slot-scope="scope">
              {{ $fd('IsEnable', 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="1200px"
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
      :title="$t('trials:qcCfg:button:default')"
    >
      <div class="base-dialog-body">
        <DefaultQS :trial-reading-criterion-id="trialReadingCriterionId" :current-criterion-type="CurrentCriterionType" @getList="getList" @close="addVisible = false" />
      </div>
    </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 { getReadingMedicineTrialQuestionList, deleteReadingMedicineTrialQuestion, confirmReadingMedicineQuestion, verifyReadingMedicineQuestion } from '@/api/trials'
import { getTrialCriterionList } from '@/api/trials/reading'
import BoxContent from '@/components/BoxContent'
import DefaultQS from './components/DefaultQS'
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: '',
    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

    }
  },
  watch: {
    trialReadingCriterionId(v) {
      this.getList()
      this.CurrentCriterionType = this.trialCriterionList.find(v => {
        return v.TrialReadingCriterionId === this.trialReadingCriterionId
      }).CriterionType
      console.log(this.CurrentCriterionType)
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getTrialCriterionList()
  },
  methods: {
    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
    },
    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.$message.error(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.QuestionCount === 0) {
        // '请先配置医学审核问题再进行确认！'
        this.$message.error(this.$t('trials:medicalFeedbackCfg:message:msg1'))
        return
      }
      this.loading = true
      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 })
    },
    // 关闭签名框并设置确认状态
    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>
