<template>
  <box-content v-loading="loading" style="height: 100%;background: #fff;">
    <!-- 搜索框 -->
    <div class="search">
      <el-form :inline="true" class="base-search-form">
        <!-- 审核问题 -->
        <el-form-item :label="$t('trials:qcCfg:table:questionName')" style="margin-top: 10px">
          <el-input v-model="searchData.QuestionName" clearable style="width:120px;" />
        </el-form-item>
        <!-- 语言类型 -->
        <el-form-item
          :label="$t('common:title:languageType')"
          style="margin-top: 10px"
        >
          <el-select
            v-model="searchData.LanguageType"
            clearable
            style="width:120px;"
          >
            <el-option
              v-for="item of $d.LanguageType"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        <!-- 类型 -->
        <el-form-item :label="$t('trials:qcCfg:table:type')" style="margin-top: 10px">
          <el-select v-model="searchData.Type" clearable style="width:120px;">
            <el-option v-for="item of $d.QcType" :key="item.label" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:qcCfg:table:isEnable')" style="margin-top: 10px">
          <el-select v-model="searchData.IsEnable" clearable style="width:120px;">
            <el-option v-for="item of $d.YesOrNo" :key="item.label" :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 style="width:120px;">
            <el-option v-for="item of $d.YesOrNo" :key="`IsRequired${item.label}`" :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
            v-if="isHaveQCQuestion"
            type="primary"
            icon="el-icon-view"
            @click="preview.visible = true"
          >
            {{ $t('trials:qcCfg:button:preview') }}
          </el-button>
          <el-button
            v-if="!isConfirm && hasPermi(['trials:trials-panel:setting:qc-question:default-question'])"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            {{ $t('trials:qcCfg:button:default') }}
          </el-button>
          <el-button
            v-if="!isConfirm && hasPermi(['trials:trials-panel:setting:qc-question:custom-question'])"
            type="primary"
            icon="el-icon-plus"
            @click="handleCustomQS"
          >
            {{ $t('trials:qcCfg:button:custom') }}
          </el-button>
          <el-button
            v-if="(!isConfirm && isHaveQCQuestion)"
            v-hasPermi="['trials:trials-panel:setting:qc-question:confirm']"
            type="danger"
            icon="el-icon-circle-check"
            @click="handleConfirm"
          >
            {{ $t('trials:qcCfg:button:confirm') }}
          </el-button>
        </el-form-item>
      </el-form>
<!--      <span style="margin-left:auto">-->
<!--      </span>-->
    </div>

    <el-table
      v-adaptive="{bottomOffset:45}"
      :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')"
        min-width="300"
        show-overflow-tooltip
      />
      <!-- 审核问题 -->
      <el-table-column
        prop="LanguageType"
        :label="$t('common:title:languageType')"
        show-overflow-tooltip
        width="100"
      >
        <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
        width="120"
      >
        <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
        width="180"
      />

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

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

    <!-- 新增默认问题 -->
    <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-modal-body">
        <DefaultQS @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 :data="currentRow" @getList="getList" @close="qsForm.visible = false" />
    </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>

    <!-- 预览 -->
    <el-dialog
      v-if="preview.visible"
      v-dialogDrag
      :visible.sync="preview.visible"
      :close-on-click-modal="false"
      :title="preview.title"
      width="500px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <div class="base-dialog-body">
        <QcQuestionPreview :trial-id="trialId" />
      </div>
    </el-dialog>
  </box-content>
</template>
<script>
import { getTrialQCQuestionConfigureList, deleteTrialQCQuestionConfigure, verifyTrialConfigSignatureConfirm } from '@/api/trials'
import { trialConfigSignatureConfirm } from '@/api/trials/setting'
import BoxContent from '@/components/BoxContent'
import DefaultQS from './components/DefaultQS'
import QsForm from './components/QsForm'
import QcQuestionPreview from '@/views/dictionary/template/components/QcQuestionPreview'
import SignForm from '@/views/trials/components/newSignForm'
import const_ from '@/const/sign-code'
const searchDataDefault = () => {
  return {
    QuestionName: '',
    LanguageType: null,
    Type: '',
    IsEnable: null
  }
}
export default {
  name: 'QcQuestions',
  components: { BoxContent, DefaultQS, QsForm, QcQuestionPreview, SignForm },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      addVisible: false,
      currentRow: {},
      qsForm: { visible: false, title: '' },
      signText: '',
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      isConfirm: true,
      isHaveQCQuestion: false,
      trialId: '',
      preview: { visible: false, title: this.$t('common:button:preview') }// '预览'
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getList()
  },
  methods: {
    // 获取qc模板信息
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      getTrialQCQuestionConfigureList(this.searchData).then(res => {
        this.loading = false
        this.list = res.Result
        this.isConfirm = !!(res.OtherInfo.QCQuestionConfirmedUserId !== null && res.OtherInfo.QCQuestionConfirmedUserId !== '')
        this.isHaveQCQuestion = res.OtherInfo.IsHaveQCQuestion
      }).catch(() => { this.loading = false })
    },
    // 打开系统模板配置项
    handleAdd() {
      this.addVisible = true
    },
    // 编辑qc问题配置信息
    handleEdit(row) {
      this.currentRow = { ...row }
      this.qsForm.title = this.$t('trials:qcCfg:dialogTitle:edit')
      this.qsForm.visible = true
    },
    // 打开自定义qc问题配置框
    handleCustomQS() {
      this.currentRow = {}
      this.qsForm.title = this.$t('trials:qcCfg:dialogTitle:custom')
      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
            deleteTrialQCQuestionConfigure(this.trialId, row.Id)
              .then(res => {
                this.loading = false
                if (res.IsSuccess) {
                  this.getList()
                  this.$message.success(this.$t('common:message:deletedSuccessfully'))
                }
              }).catch(() => { this.loading = false })
          })
      }
    },
    // 打开自定义qc问题配置框
    openCustomDialog() {
      this.customQuestionVisible = true
      this.form.Id = ''
      this.form.QuestionName = ''
      this.form.IsRequired = true
      this.form.IsEnable = true
      this.form.Type = 'select'
      this.form.TypeValue = ''
      this.form.ShowOrder = 0
      this.form.ParentId = ''
      this.form.ParentTriggerValue = ''
      this.getParentOpntions()
    },
    // 查询
    handleSearch() {
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    // 确认前签名
    handleConfirm() {
      if (!this.list || this.list.length === 0) {
        this.$alert(this.$t('trials:qcCfg:message:msg2'))// '请先配置QC审核问题再进行确认！'
        return
      }
      this.loading = true
      verifyTrialConfigSignatureConfirm({ trialId: this.trialId }).then(res => {
        this.loading = false
        const { QCConfirmation } = const_.processSignature
        this.signCode = QCConfirmation
        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,
          signCode: signInfo.SignCode
        },
        signInfo: signInfo
      }
      trialConfigSignatureConfirm(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>
