<template>
  <BaseContainer>
    <el-tabs v-model="TrialReadingCriterionId" type="border-card">
      <el-tab-pane v-for="item of trialCriterionList" :key="item.TrialReadingCriterionName" :label="item.TrialReadingCriterionName" :name="item.TrialReadingCriterionId">
        <div v-if="item.TrialReadingCriterionId === TrialReadingCriterionId">
          <div slot="search-container">
            <el-form :inline="true">
              <!-- 是否加急 -->
              <el-form-item
                style="margin-bottom:10px"
                :label="$t('trials:medicalFeedback:table:isUrgent')"
              >
                <el-select
                  v-model="searchData.IsUrgent"
                  clearable
                  style="width:120px;"
                >
                  <el-option
                    v-for="i of $d.YesOrNo"
                    :key="'IsUrgent' + i.label"
                    :value="i.value"
                    :label="i.label"
                  />
                </el-select>
              </el-form-item>
              <!-- 中心编号 -->
              <el-form-item :label="$t('trials:medicalFeedback:table:siteCode')">
                <el-select
                  v-model="searchData.SiteId"
                  clearable
                  filterable
                  style="width:120px;"
                >
                  <el-option
                    v-for="(site,index) of siteOptions"
                    :key="index"
                    :label="site.TrialSiteCode"
                    :value="site.SiteId"
                  />
                </el-select>
              </el-form-item>
              <!-- 受试者编号 -->
              <el-form-item :label="$t('trials:medicalFeedback:table:subjectCode')">
                <el-input
                  v-model="searchData.SubjectCode"
                  style="width:100px;"
                />
              </el-form-item>
              <!-- 访视/阅片期名称 -->
              <el-form-item
                style="margin-bottom:10px"
                :label="$t('trials:medicalFeedback:table:taskName')"
              >
                <el-input
                  v-model="searchData.TaskName"
                  style="width:100px;"
                  clearable
                />
              </el-form-item>
              <!-- 盲态任务标识 -->
              <el-form-item
                style="margin-bottom:10px"
                :label="$t('trials:medicalFeedback:table:taskBlindName')"
              >
                <el-input
                  v-model="searchData.TaskName"
                  style="width:100px;"
                  clearable
                />
              </el-form-item>
              <!-- 阅片角色 -->
              <el-form-item
                style="margin-bottom:10px"
                :label="$t('trials:medicalFeedback:table:armEnum')"
              >
                <el-select
                  v-model="searchData.ArmEnum"
                  clearable
                  style="width:120px;"
                >
                  <el-option
                    v-for="arm of $d.ArmEnum"
                    :key="'ArmEnum' + arm.label"
                    :value="arm.value"
                    :label="arm.label"
                  />
                </el-select>
              </el-form-item>
              <!-- 阅片人 -->
              <el-form-item
                style="margin-bottom:10px"
                :label="$t('trials:medicalFeedback:table:reader')"
              >
                <el-select
                  v-model="searchData.DoctorUserId"
                  clearable
                  style="width:120px;"
                >
                  <el-option
                    v-for="doctor of doctorUserList"
                    :key="'DoctorUserId' + doctor.DoctorUserId"
                    :value="doctor.DoctorUserId"
                    :label="`${doctor.UserName}(${doctor.FullName})`"
                  />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-bottom:10px" :label="$t('trials:medicalFeedback:table:taskState')">
                <el-select v-model="searchData.TaskState" clearable style="width:120px;">
                  <el-option v-for="i of $d.TaskState" :key="'TaskState' + i.label" :value="i.value" :label="i.label" />
                </el-select>
              </el-form-item>
              <!-- 任务类型 -->
              <el-form-item
                style="margin-bottom:10px"
                :label="$t('trials:medicalFeedback:table:readingCategory')"
              >
                <el-select
                  v-model="searchData.ReadingCategory"
                  clearable
                  style="width:120px;"
                >
                  <el-option
                    v-for="r of $d.ReadingCategory"
                    :key="'ReadingCategory' + r.label"
                    :value="r.value"
                    :label="r.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-bottom:10px" :label="$t('trials:medicalFeedback:table:auditState')">
                <el-select v-model="searchData.AuditState" clearable style="width:120px;">
                  <el-option v-for="i of $d.MedicalReviewAuditState" :key="'AuditState' + i.label" :value="i.value" :label="i.label" />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-bottom:10px" :label="$t('trials:medicalFeedback:table:DoctorUserIdeaEnum')">
                <el-select v-model="searchData.DoctorUserIdeaEnum" clearable style="width:120px;">
                  <el-option v-for="i of $d.MedicalReviewDoctorUserIdea" :key="'DoctorUserIdeaEnum' + i.label" :value="i.value" :label="i.label" />
                </el-select>
              </el-form-item>
              <el-form-item style="margin-bottom:10px">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="handleSearch"
                >
                  {{ $t('common:button:search') }}
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-refresh-left"
                  @click="handleReset"
                >
                  {{ $t('common:button:reset') }}
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-download" @click="handleReset">
                  {{ $t('common:button:export') }}
                </el-button>
              </el-form-item>
              <!--导出-->
            </el-form>
          </div>
          <div slot="main-container">
            <el-table
              ref="mimMedicalAudit"
              v-adaptive="{bottomOffset:75}"
              v-loading="loading"
              :data="list"
              stripe
              height="100"
              @sort-change="handleSortChange"
            >
              <el-table-column
                type="index"
                width="50"
              />
              <!-- 是否加急 -->
              <el-table-column
                prop="IsUrgent"
                :label="$t('trials:medicalFeedback:table:isUrgent')"
                show-overflow-tooltip
                width="120"
                sortable="custom"
              >
                <template slot-scope="scope">
                  <el-tag
                    v-if="scope.row.IsUrgent"
                    type="danger"
                  >
                    {{ $fd('YesOrNo', scope.row.IsUrgent) }}
                  </el-tag>
                  <el-tag
                    v-else
                    type="primary"
                  >
                    {{ $fd('YesOrNo', scope.row.IsUrgent) }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- 中心编号 -->
              <el-table-column
                prop="TrialSiteCode"
                :label="$t('trials:medicalFeedback:table:siteCode')"
                width="120"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 受试者编号 -->
              <el-table-column
                prop="SubjectCode"
                :label="$t('trials:medicalFeedback:table:subjectCode')"
                width="140"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 访视/阅片期名称 -->
              <el-table-column
                prop="TaskName"
                :label="$t('trials:medicalFeedback:table:taskName')"
                width="160"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 盲态任务标识 -->
              <el-table-column
                prop="TaskBlindName"
                :label="$t('trials:medicalFeedback:table:taskBlindName')"
                width="180"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 任务类型 -->
              <el-table-column
                prop="ReadingCategory"
                :label="$t('trials:medicalFeedback:table:readingCategory')"
                min-width="100"
                sortable="custom"
                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="TaskState"
                :label="$t('trials:medicalFeedback:table:taskState')"
                width="160"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.TaskState === 0" type="primary">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
                  <el-tag v-if="scope.row.TaskState === 1" type="info">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
                  <el-tag v-if="scope.row.TaskState === 3" type="danger">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
                  <el-tag v-if="scope.row.TaskState === 4" type="warning">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
                  <el-tag v-if="scope.row.TaskState === 5" type="danger">{{ $fd('TaskState', scope.row.TaskState) }}</el-tag>
                </template>
              </el-table-column>
              <!-- 阅片角色 -->
              <el-table-column
                prop="Role"
                :label="$t('trials:medicalFeedback:table:armEnum')"
                width="100"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag
                    v-if="scope.row.ArmEnum === 1"
                    type="primary"
                  >
                    {{ $fd('ArmEnum', scope.row.ArmEnum) }}
                  </el-tag>
                  <el-tag
                    v-if="scope.row.ArmEnum === 2"
                    type="success"
                  >
                    {{ $fd('ArmEnum', scope.row.ArmEnum) }}
                  </el-tag>
                  <el-tag
                    v-if="scope.row.ArmEnum === 3"
                    type="info"
                  >
                    {{ $fd('ArmEnum', scope.row.ArmEnum) }}
                  </el-tag>
                  <el-tag
                    v-if="scope.row.ArmEnum === 4"
                    type="danger"
                  >
                    {{ $fd('ArmEnum', scope.row.ArmEnum) }}
                  </el-tag>
                  <el-tag
                    v-if="scope.row.ArmEnum === 5"
                    type="warning"
                  >
                    {{ $fd('ArmEnum', scope.row.ArmEnum) }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- 阅片人 -->
              <el-table-column
                prop="UserName"
                :label="$t('trials:medicalFeedback:table:reader')"
                width="120"
                sortable="custom"
                show-overflow-tooltip
              >
                <template v-if="scope.row.DoctorUser" slot-scope="scope">
                  {{ scope.row.DoctorUser.UserName }}({{ scope.row.DoctorUser.FullName }})
                </template>
              </el-table-column>
              <!-- 阅片签名时间 -->
              <el-table-column
                prop="SignTime"
                :label="$t('trials:medicalFeedback:table:signTime')"
                width="180"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 审核分配时间 -->
              <el-table-column
                prop="AllocateTime"
                :label="$t('trials:medicalFeedback:table:allocateTime')"
                width="180"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 任务状态 -->
              <el-table-column
                prop="IsInvalid"
                width="120"
                :label="$t('trials:medicalFeedback:table:isInvalid')"
                show-overflow-tooltip
                sortable="custom"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.IsInvalid" type="danger">
                    {{ $fd('IsTakeEffect', scope.row.IsInvalid) }}
                  </el-tag>
                  <el-tag v-else type="primary">
                    {{ $fd('IsTakeEffect', scope.row.IsInvalid) }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- 审核状态 -->
              <el-table-column
                prop="AuditState"
                :label="$t('trials:medicalFeedback:table:auditState')"
                width="140"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.AuditState === 0" type="warning">
                    {{ $fd('MedicalReviewAuditState', scope.row.AuditState) }}
                  </el-tag>
                  <el-tag v-if="scope.row.AuditState === 1" type="primary">
                    {{ $fd('MedicalReviewAuditState', scope.row.AuditState) }}
                  </el-tag>
                  <el-tag v-if="scope.row.AuditState === 2" type="danger">
                    {{ $fd('MedicalReviewAuditState', scope.row.AuditState) }}
                  </el-tag>
                </template>
              </el-table-column>
              <!-- 审核建议 -->
              <el-table-column
                prop="AuditAdviceEnum"
                :label="$t('trials:medicalFeedback:table:auditAdvice')"
                width="130"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ $fd('AuditAdvice',scope.row.AuditAdviceEnum) }}
                </template>
              </el-table-column>
              <!-- 阅片人是否认同 -->
              <el-table-column
                prop="DoctorUserIdeaEnum"
                :label="$t('trials:medicalFeedback:table:doctorUserIdea')"
                width="150"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  {{ $fd('MedicalReviewDoctorUserIdea',scope.row.DoctorUserIdeaEnum) }}
                </template>
              </el-table-column>
              <!-- 审核签名时间 -->
              <el-table-column
                prop="AuditSignTime"
                :label="$t('trials:medicalFeedback:table:auditSignTime')"
                width="180"
                sortable="custom"
                show-overflow-tooltip
              />
              <el-table-column
                fixed="right"
                :label="$t('common:action:action')"
                width="200"
              >
                <template slot-scope="scope">
                  <!-- 审核 -->
                  <el-button
                    v-if="scope.row.AuditState < 2"
                    icon="el-icon-edit-outline"
                    circle
                    :title="$t('trials:medicalFeedback:button:audit')"
                    :disabled="scope.row.IsInvalid"
                    @click="handleAudit(scope.row)"
                  />
                  <el-button
                    v-if="scope.row.AuditState === 2"
                    icon="el-icon-view"
                    circle
                    :title="$t('trials:medicalFeedback:table:view')"
                    @click="handleView(scope.row)"
                  />
                  <!-- 反馈 -->
                  <el-button
                    icon="el-icon-chat-dot-round"
                    circle
                    :title="$t('trials:medicalFeedback:title:feedback')"
                    :disabled="!scope.row.IsHaveQuestion || scope.row.IsInvalid"
                    @click="handleReply(scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 审核 -->
    <el-dialog
      v-if="auditVisible"
      :visible.sync="auditVisible"
      :close-on-click-modal="false"
      :fullscreen="true"
      :title="$t('trials:medicalFeedback:title:mfDetail')"
      :before-close="beforeCloseAudit"
    >
      <MedicalAudit
        :visit-task-id="currentRow.VisitTaskId"
        :task-medical-review-id="currentRow.Id"
        :row-data="currentRow"
        @getList="getList"
        @close="closeAudit"
        @nextTask="nextTask"
      />
    </el-dialog>

    <el-dialog
      v-if="chatForm.visible"
      :visible.sync="chatForm.visible"
      :close-on-click-modal="false"
      width="800px"
      :title="chatForm.title"
      append-to-body
    >
      <ChatForm
        ref="chatForm"
        :task-medical-review-id="currentRow.Id"
        :visit-task-id="currentRow.VisitTaskId"
        @handleCloseReply="handleCloseReply"
      />
    </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:medicalFeedback:title:closeQc')"
    >
      <CloseQC
        :task-medical-review-id="currentRow.Id"
        @close="closeQuestionVisible = false"
        @refresh="refresh"
      />
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getTrialSiteSelect, getMIMMedicalReviewTaskList, getNextMedicalReviewTask } from '@/api/trials'
import { getTrialCriterionList } from '@/api/trials/reading'
import { getDoctorUserSelectList } from '@/api/trials/reading'
import { getToken } from '@/utils/auth'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import MedicalAudit from './components/MedicalAudit'
import ChatForm from './components/ChatForm'
import CloseQC from './components/CloseQC'

const searchDataDefault = () => {
  return {
    PageIndex: 1,
    PageSize: 20,
    TrialId: '',
    SiteId: '',
    SubjectId: '',
    SubjectCode: '',
    TaskName: '',
    IsUrgent: null,
    DoctorUserId: '',
    ReadingCategory: null,
    ReadingTaskState: null,
    AuditState: null,
    TaskState: null,
    DoctorUserIdeaEnum: null
  }
}
export default {
  name: 'MIMMedicalAudit',
  components: { BaseContainer, Pagination, MedicalAudit, ChatForm, CloseQC },
  data() {
    return {
      list: [],
      total: 0,
      loading: false,
      siteOptions: [],
      doctorUserList: [],
      trialId: '',
      searchData: searchDataDefault(),
      auditVisible: false,
      chatForm: { visible: false, title: '' }, // 质询记录
      currentRow: {},
      otherInfo: {},
      isConfirmMedicineQuestion: false,
      TrialReadingCriterionId: '0',
      trialCriterionList: [],
      closeQuestionVisible: false,
      readingWindow: null
    }
  },
  watch: {
    TrialReadingCriterionId(v1) {
      this.getList()
    },
    list() {
      this.$nextTick(() => {
        this.$refs.mimMedicalAudit[0].doLayout()
      })
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getTrialCriterionList()
    this.getSite()
    this.getDoctorUserSelectList()
  },
  beforeDestroy() {
    if (this.readingWindow) {
      this.readingWindow.close()
    }
  },
  methods: {
    refresh() {
      this.isClosedDialog = true
      this.$refs['chatForm'].getMessageList()
    },
    handleCloseReply() {
      this.closeQuestionVisible = true
    },
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      this.searchData.TrialReadingCriterionId = this.TrialReadingCriterionId
      getMIMMedicalReviewTaskList(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 })
    },
    getTrialCriterionList() {
      getTrialCriterionList(this.trialId).then(res => {
        this.trialCriterionList = res.Result
        this.TrialReadingCriterionId = this.trialCriterionList[0].TrialReadingCriterionId
      }).catch(() => {})
    },
    handleView(row) {
      this.currentRow = { ...row }
      this.auditVisible = true
      // 访视任务，打开阅片页面
      if (row.ReadingCategory === 1) {
        this.handleViewReadingPage(row)
      }
    },
    handleReply(row) {
      this.currentRow = { ...row }
      this.chatForm.title = `${this.$t('trials:medicalFeedback:title:qaRecord')} (${row.SubjectCode} ${row.TaskBlindName})`
      this.chatForm.visible = true
    },
    handleAudit(row) {
      if (this.otherInfo.IsConfirmMedicineQuestion) {
        this.currentRow = { ...row }
        this.auditVisible = true
        // 访视任务，打开阅片页面
        if (row.ReadingCategory === 1) {
          this.handleViewReadingPage(row)
        }
      } else {
        // '请先确认医学审核问题模板配置！'
        this.$alert(this.$t('trials:medicalFeedback:message:confirmTemplate'), {
          callback: action => {}
        })
      }
    },
    handleViewReadingPage(row) {
      var trialId = this.$route.query.trialId
      var token = getToken()
      var visitTaskId = row.VisitTaskId
      var criterionType = row.CriterionType
      var readingTool = row.ReadingTool
      readingTool = isNaN(parseInt(readingTool)) ? null : parseInt(readingTool)
      var isReadingTaskViewInOrder = row.IsReadingTaskViewInOrder
      var trialReadingCriterionId = row.TrialReadingCriterionId
      var path = ''

      if (readingTool === 0) {
        path = `/readingDicoms?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&visitTaskId=${visitTaskId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}&key=${new Date().getTime()}`
      } else {
        path = `/noneDicomReading?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&visitTaskId=${visitTaskId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}&key=${new Date().getTime()}`
      }
      const routeData = this.$router.resolve({ path })
      if (this.readingWindow) {
        this.readingWindow.close()
      }
      this.readingWindow = window.open(routeData.href, '_blank')
    },
    beforeCloseAudit(done) {
      if (this.readingWindow) {
        this.readingWindow.close()
      }
      done()
    },
    closeAudit() {
      if (this.readingWindow) {
        this.readingWindow.close()
      }
      this.auditVisible = false
    },
    getSite() {
      getTrialSiteSelect(this.trialId).then(res => {
        this.siteOptions = res.Result
      })
    },
    getDoctorUserSelectList() {
      getDoctorUserSelectList(this.$route.query.trialId).then(res => {
        this.doctorUserList = res.Result
      })
    },
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    // 排序
    handleSortChange(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()
    },
    nextTask(medicalReviewId) {
      getNextMedicalReviewTask({ medicalReviewId }).then(res => {
        this.auditVisible = false
        this.currentRow = res.Result
        this.$nextTick(() => {
          this.auditVisible = true
          if (res.Result.ReadingCategory === 1) {
            this.handleViewReadingPage(this.currentRow)
          }
        })
      }).catch(() => { this.auditVisible = false })
    }
  }

}
</script>
