<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 中心编号 -->
        <el-form-item :label="$t('trials:qcQuality:table:siteId')">
          <el-select v-model="searchData.SiteId" clearable filterable style="width:120px;">
            <el-option
              v-for="item of siteOptions"
              :key="item.Id"
              :label="item.TrialSiteCode"
              :value="item.SiteId"
            />
          </el-select>
        </el-form-item>
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:qcQuality:table:subjectId')">
          <el-input v-model="searchData.SubjectCode" style="width:100px;" />
        </el-form-item>
        <!-- 访视名称 -->
        <el-form-item class="my_multiple" :label="$t('trials:qcQuality:table:visitName')">
          <el-select
            v-model="searchData.VisitPlanArray"
            style="width:140px"
            clearable
            multiple
          >
            <el-option
              v-for="(item, index) of visitPlanOptions"
              :key="index"
              :label="item.VisitName"
              :value="item.VisitNum"
            >
              <span style="float: left">{{ item.VisitName }}</span>
            </el-option>
            <el-option
              key="Other"
              label="Out of Plan"
              value="1.11"
            />
          </el-select>
        </el-form-item>
        <!-- 发起人 -->
        <el-form-item :label="$t('trials:qcQuality:table:organizer')">
          <el-select v-model="searchData.CreateUserId" clearable filterable style="width:150px;">
            <el-option
              v-for="(item,index) of creatorOptions"
              :key="index"
              :label="item.Creator"
              :value="item.CreateUserId"
            >
              <span style="float: left">{{ item.Creator }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px;margin-left:5px;">
                {{ item.CreatorRealName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 是否重传 -->
        <el-form-item :label="$t('trials:qcQuality:table:ReuploadEnum')">
          <el-select v-model="searchData.ReuploadEnum" clearable style="width:120px">
            <el-option v-for="item of $d.ReuploadEnum" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <!-- 是否超限 -->
        <el-form-item :label="$t('trials:qcQuality:table:isOverTime')">
          <el-select v-model="searchData.IsOverTime" clearable style="width:120px">
            <el-option v-for="item of $d.YesOrNo" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <!-- 是否关闭 -->
        <el-form-item :label="$t('trials:qcQuality:table:isClosed')">
          <el-select v-model="searchData.IsClosed" clearable style="width:120px">
            <el-option v-for="item of $d.YesOrNo" :value="item.value" :label="item.label" />
          </el-select>
        </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-button type="primary" icon="el-icon-download" @click="handleExport">
          {{ $t('common:button:export') }}
        </el-button>
      </el-form>
    </template>

    <!-- qc质疑列表 -->
    <template slot="main-container">
      <el-table
        ref="qcQsTable"
        v-loading="loading"
        v-adaptive="{bottomOffset:60}"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
      >
        <!-- 质疑编号 -->
        <el-table-column
          prop="ChallengeCode"
          :label="$t('trials:qcQuality:table:challengeCode')"
          show-overflow-tooltip
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              :style="{color:scope.row.IsClosed?'':'red'}"
              @click="handleReply(scope.row,scope.$index)"
            >
              {{ scope.row.ChallengeCode }}
            </el-button>
          </template>

        </el-table-column>
        <!-- 中心编号 -->
        <el-table-column
          prop="TrialSiteCode"
          :label="$t('trials:qcQuality:table:siteId')"
          show-overflow-tooltip
          min-width="100"
          sortable="custom"
        />
        <!-- 受试者编号 -->
        <el-table-column
          prop="SubjectCode"
          :label="$t('trials:qcQuality:table:subjectId')"
          show-overflow-tooltip
          min-width="120"
          sortable="custom"
        />
        <!-- 访视名称 -->
        <el-table-column
          prop="VisitName"
          :label="$t('trials:qcQuality:table:visitName')"
          show-overflow-tooltip
          width="130"
          sortable="custom"
        />
        <el-table-column
          prop="QCProcessEnum"
          :label="$t('trials:qcQuality:table:qCProcessEnum')"
          show-overflow-tooltip
          width="160"
          sortable="custom"
        >
          <template slot-scope="scope">
            <div v-if="otherInfo.QCProcessEnum === 1">
              <!-- {{ scope.row.CurrentQCEnum === 1?'审核':'--' }} -->
              <el-tag v-if="scope.row.CurrentQCEnum === 1" type="primary">{{ $fd('CurrentQCType', 0) }}</el-tag>
              <span v-else>--</span>
            </div>
            <div v-else-if="otherInfo.QCProcessEnum === 2">
              <el-tag v-if="scope.row.CurrentQCEnum === 1" type="primary">{{ $fd('CurrentQCType', scope.row.CurrentQCEnum) }}</el-tag>
              <el-tag v-else-if="scope.row.CurrentQCEnum === 2" type="warning">{{ $fd('CurrentQCType', scope.row.CurrentQCEnum) }}</el-tag>
              <span v-else>--</span>
            </div>
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column
          prop="CreateTime"
          :label="$t('trials:qcQuality:table:createTime')"
          show-overflow-tooltip
          min-width="150"
          sortable="custom"
        />
        <!-- 发起人 -->
        <el-table-column
          prop="CreateUserName"
          :label="$t('trials:qcQuality:table:organizer')"
          show-overflow-tooltip
          min-width="120"
          sortable="custom"
        />
        <el-table-column
          prop="CurrentActionUserName"
          :label="$t('trials:qcCheck:table:crrentUser')"
          show-overflow-tooltip
          width="160"
          sortable="custom"
        />
        <!-- 最新回复人 -->
        <el-table-column
          prop="LatestReplyUserName"
          :label="$t('trials:qcQuality:table:latestReplyer')"
          show-overflow-tooltip
          min-width="120"
          sortable="custom"
        />
        <!-- 最新回复时间 -->
        <el-table-column
          prop="LatestMsgTime"
          :label="$t('trials:qcQuality:table:latestReplyTime')"
          show-overflow-tooltip
          width="210"
          sortable="custom"
        />
        <!-- 重传状态 -->
        <el-table-column
          prop="ReuploadEnum"
          :label="$t('trials:qcQuality:table:reUploadStatus')"
          show-overflow-tooltip
          width="170"
          sortable="custom"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.ReuploadEnum === 0">--</span>
            <el-tag v-else-if="scope.row.ReuploadEnum === 1" type="danger">{{ $fd('ReuploadEnum', scope.row.ReuploadEnum) }}</el-tag>
            <el-tag v-else-if="scope.row.ReuploadEnum === 2" type="warning">{{ $fd('ReuploadEnum', scope.row.ReuploadEnum) }}</el-tag>
            <el-tag v-else-if="scope.row.ReuploadEnum === 3" type="primary">{{ $fd('ReuploadEnum', scope.row.ReuploadEnum) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 重传完成时间 -->
        <el-table-column
          prop="ReUploadedTime"
          :label="$t('trials:qcQuality:table:reUploadTime')"
          show-overflow-tooltip
          width="210"
          sortable="custom"
        />
        <!-- 处理截止时限 -->
        <el-table-column
          prop="DeadlineTime"
          :label="$t('trials:qcQuality:table:deadline')"
          show-overflow-tooltip
          width="210"
          sortable="custom"
        />
        <!-- 质疑时长 -->
        <el-table-column
          prop="ChallengeDuration"
          :label="$t('trials:qcQuality:table:qsDuration')"
          show-overflow-tooltip
          min-width="130"
        />
        <!-- 是否超限 -->
        <el-table-column
          prop="IsOverTime"
          :label="$t('trials:qcQuality:table:isOverTime')"
          show-overflow-tooltip
          min-width="100"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsOverTime" type="danger">{{ $fd('YesOrNo', scope.row.IsOverTime) }}</el-tag>
            <el-tag v-else>{{ $fd('YesOrNo', scope.row.IsOverTime) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 是否关闭 -->
        <el-table-column
          prop="IsClosed"
          :label="$t('trials:qcQuality:table:isClosed')"
          show-overflow-tooltip
          min-width="100"
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsClosed" type="danger">{{ $fd('YesOrNo', scope.row.IsClosed) }}</el-tag>
            <el-tag v-else>{{ $fd('YesOrNo', scope.row.IsClosed) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 关闭时间 -->
        <el-table-column
          prop="ClosedTime"
          :label="$t('trials:qcQuality:table:closingTime')"
          show-overflow-tooltip
          width="210"
          sortable="custom"
        />
        <el-table-column
          v-if="hasPermi(['trials:trials-panel:visit:qc-question:send', 'trials:trials-panel:visit:qc-question:close'])"
          :label="$t('common:action:action')"
          width="200"
          fixed="right"
        >
          <template slot-scope="scope">
            <!-- 回复 -->
            <el-button
              v-hasPermi="['trials:trials-panel:visit:qc-question:send']"
              circle
              :title="$t('trials:qcQuality:action:reply')"
              icon="el-icon-chat-dot-square"
              :disabled="scope.row.IsClosed"
              @click="handleReply(scope.row)"
            />
            <!-- 关闭 -->
            <el-button
              v-hasPermi="['trials:trials-panel:visit:qc-question:close']"
              icon="el-icon-error"
              circle
              :title="$t('trials:qcQuality:action:close')"
              :disabled="scope.row.IsClosed || currentUserId !== scope.row.CurrentActionUserId"
              @click="handleCloseQC(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
    </template>

    <!--  回复质疑 -->
    <el-dialog
      v-if="chatVisible"
      :visible.sync="chatVisible"
      :close-on-click-modal="false"
      width="800px"
      :title="$t('trials:qcQuality:dialogTitle:reply') + `(${currentQCRow.SubjectCode} ${currentQCRow.VisitName})`"
      @getList="getList"
    >
      <chat-form :data="currentQCRow" user-type="qc" :sign-text="otherInfo.ImageQCSignText" @close="chatVisible = false" @getDialogList="getDialogList" />
    </el-dialog>
    <!-- 关闭质疑 -->
    <el-dialog
      v-if="closeQuestionVisible"
      :visible.sync="closeQuestionVisible"
      :close-on-click-modal="false"
      append-to-body
      custom-class="base-dialog-wrapper"
      width="600px"
      :title="$t('trials:qcQuality:dialogTitle:closeQuestion')"
    >
      <div style="padding:10px;border: 1px solid #e0e0e0;max-height:650px;overflow-y: auto;">
        <el-form
          ref="closeQuestionForm"
          :model="closeQuestionForm"
          size="small"
          label-width="120px"
        >
          <!-- 关闭原因 -->
          <el-form-item
            :label="$t('trials:qcQuality:label:closeReason')"
            prop="Type"
            :rules="[
              { required: true, message: $t('common:ruleMessage:select')},
            ]"
          >
            <el-radio-group v-model="closeQuestionForm.Type">
              <el-radio :label="1">{{ $t('trials:qcQuality:radio:reason1') }}</el-radio>
              <el-radio :label="2">{{ $t('trials:qcQuality:radio:reason2') }}</el-radio>
              <!--              <el-radio :label="3">{{ $t('trials:qcQuality:radio:reason3') }}</el-radio>-->
            </el-radio-group>
          </el-form-item>
          <!-- 其他原因说明 -->
          <el-form-item
            v-if="closeQuestionForm.Type === 2"
            :label="$t('trials:consistencyCheck:label:closereason')"
            prop="Remake"
            :rules="[
              { required: true, message: $t('common:ruleMessage:specify')},
            ]"
          >
            <el-input
              v-model="closeQuestionForm.Remake"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              :placeholder="$t('common:ruleMessage:specify')"
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="closeBtnLoading" size="small" type="primary" @click="closeQuestionVisible = false">
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button :loading="closeBtnLoading" size="small" type="primary" @click="handleCloseQuestion">
          {{ $t('common:button:save') }}
        </el-button>
      </div>
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getQCChallengeList, getTrialSiteSelect, getTrialVisitStageSelect, getQCChallengeCreatorList, closeQCChallenge, getQCChallengeDialogList } from '@/api/trials'
import { getQCChallengeList_Export } from '@/api/export'
import BaseContainer from '@/components/BaseContainer'
import ChatForm from '@/views/trials/trials-panel/visit/qc-check/components/chatForm'
import Pagination from '@/components/Pagination'
import { changeURLStatic } from '@/utils/history.js'
const searchDataDefault = () => {
  return {
    SiteId: '',
    SubjectCode: '',
    NeedReUpload: null,
    IsOverTime: null,
    CreateUserId: '',
    VisitPlanArray: [],
    IsClosed: null,
    PageIndex: 1,
    PageSize: 20,
    ReuploadEnum: null
  }
}
export default {
  name: 'QcQuestion',
  components: { BaseContainer, Pagination, ChatForm },
  data() {
    return {
      searchData: searchDataDefault(),
      total: 0,
      list: [],
      loading: false,
      chatVisible: false,
      currentQCRow: {},
      /* eslint-disable */
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      siteOptions: [],
      visitPlanOptions: [],
      creatorOptions: [],
      otherInfo: {},
      closeQuestionVisible: false,
      closeQuestionForm: { Id: '', SubjectVisitId: '', Type: null, Reason: '', Remake: '' },
      closeBtnLoading: false,
      trialId: this.$route.query.trialId,
      /* eslint-disable */
      currentUserId: zzSessionStorage.getItem('userId')
    }
  },
  mounted() {
    if (this.$route.query.challengeState && this.$route.query.challengeState * 1 === 1) {
      // ChallengeState:1 关闭；
      this.searchData.IsClosed = true
    }
    if (this.$route.query.challengeState && this.$route.query.challengeState * 1 === 2) {
      // ChallengeState:2 未关闭；
      this.searchData.IsClosed = false
    }
    if (this.$route.query.subjectCode) {
      this.searchData.SubjectCode = this.$route.query.subjectCode
    }
    changeURLStatic('subjectCode', '')
    changeURLStatic('challengeState', '')
    this.getList()
    this.getSite()
    this.getVisitPlanOptions()
    this.getCreatorOptions()
  },
  methods: {
    // 获取QC质疑列表
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      getQCChallengeList(this.searchData).then(res => {
        this.loading = false
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
        this.otherInfo = res.OtherInfo
      }).catch(() => { this.loading = false })
    },
    handleExport() {
      getQCChallengeList_Export(this.searchData).then(res => {
      }).catch(() => {})
    },
    // 回复质疑
    handleReply(row) {
      this.loading = true
      getQCChallengeDialogList(row.Id).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          if (res.Result.length > 0) { Object.assign(row, res.Result[0]) }
          this.currentQCRow = { ...row }
          this.chatVisible = true
        }
      }).catch(() => { this.loading = false })
    },
    getDialogList() {
      this.loading = true
      getQCChallengeDialogList(this.currentQCRow.Id).then(res => {
        this.loading = false
        if (res.IsSuccess && res.Result.length > 0) {
          var i = this.list.findIndex(item => item.Id === this.currentQCRow.Id)
          if (i > -1) {
            this.currentQCRow = Object.assign(this.list[i], res.Result[0])
          }
        }
      }).catch(() => { this.loading = false })
    },
    // 打开关闭质疑框并初始化
    handleCloseQC(row) {
      this.closeQuestionForm = Object.assign(this.closeQuestionForm, row)
      // this.closeQuestionForm.Id = row.Id
      // this.closeQuestionForm.SubjectVisitId = row.SubjectVisitId
      this.closeQuestionForm.Type = null
      this.closeQuestionForm.Reason = ''
      this.closeQuestionForm.Remake = ''
      this.closeQuestionVisible = true
    },
    // 关闭质疑
    handleCloseQuestion() {
      this.$refs['closeQuestionForm'].validate((valid) => {
        if (!valid) return
        this.closeBtnLoading = true
        if (this.closeQuestionForm.Type === 1) {
          // 问题已解决
          this.closeQuestionForm.Reason = this.$t('trials:qcQuality:message:problemSolved')
        } else if (this.closeQuestionForm.Type === 2) {
          // 问题无法解决强制关闭质疑，已提醒中心下次注意
          this.closeQuestionForm.Reason = `${this.$t('trials:qcQuality:message:problemNotSolved')}<br/><br/>${this.$t('trials:consistencyCheck:label:closereason')}:${this.closeQuestionForm.Remake}`
        }
        var params = {
          TrialId: this.trialId,
          QcChallengeId: this.closeQuestionForm.Id,
          SubjectVisitId: this.closeQuestionForm.SubjectVisitId,
          CloseEnum: this.closeQuestionForm.Type,
          CloseReason: this.closeQuestionForm.Reason
        }
        closeQCChallenge(params)
          .then(res => {
            this.closeBtnLoading = false
            if (res.IsSuccess) {
              this.getList()
              // 关闭成功!
              this.$message.success(this.$t('trials:qcQuality:message:closedSuccessfully'))
              this.closeQuestionVisible = false
            }
          }).catch(() => {
            this.closeBtnLoading = false
          })
      })
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
      this.$nextTick(() => {
        this.$refs.qcQsTable.clearSort()
      })
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 获取site下拉框数据
    getSite() {
      getTrialSiteSelect(this.trialId).then(res => {
        this.siteOptions = res.Result
      })
    },
    // 获取访视下拉框数据
    getVisitPlanOptions() {
      getTrialVisitStageSelect(this.trialId)
        .then((res) => {
          this.visitPlanOptions = res.Result
        })
    },
    // 获取发起人下拉框数据
    getCreatorOptions() {
      getQCChallengeCreatorList(this.trialId)
        .then((res) => {
          this.creatorOptions = res.Result
        })
    }
  }
}
</script>
