<template>
  <BaseContainer v-loading="loading" style="height:100%;background-color: #fff;">
    <el-tabs v-model="TrialReadingCriterionId" type="border-card">
      <el-tab-pane v-for="item of trialCriterionList" :key="item.TrialReadingCriterionId" :label="item.TrialReadingCriterionName" :name="item.TrialReadingCriterionId">
        <div v-if="TrialReadingCriterionId === item.TrialReadingCriterionId">
          <div slot="search-container" style="position:relative;">
            <el-form :inline="true">
              <!-- 受试者编号 -->
              <el-form-item :label="$t('trials:readTask:table:subjectCode')">
                <el-input
                  v-model="searchData.SubjectCode"
                  style="width:130px;"
                  clearable
                />
              </el-form-item>
              <!-- 任务状态 -->
              <el-form-item style="margin-bottom:10px" :label="$t('trials:readTask: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:readTask:table:readingCategory')">
                <el-select v-model="searchData.ReadingCategory" clearable style="width:120px;">
                  <el-option v-for="i of $d.ReadingCategory" :key="'ReadingCategory' + i.label" :value="i.value" :label="i.label" />
                </el-select>
              </el-form-item>
              <!-- 是否加急 -->
              <el-form-item style="margin-bottom:10px" :label="$t('trials:readTask:form: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>
                <!-- 查询 -->
                <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="position: absolute;right: 0;top: 0;">
              <el-button
                v-hasPermi="['trials:readTask:reread']"
                :disabled="list.length ===0"
                type="primary"
                icon="el-icon-refresh-right"
                @click="handleReread"
              >
                {{ $t('trials:readTask:button:reread') }}
              </el-button>
            </span>
          </div>
          <div slot="main-container">
            <el-table
              v-adaptive="{bottomOffset:75}"
              :data="list"
              stripe
              height="100"
              @sort-change="handleSortChange"
            >
              <el-table-column type="index" width="40" align="left" />
              <!-- 是否加急 -->
              <el-table-column
                prop="IsUrgent"
                min-width="100"
                :label="$t('trials:readTask:table:isUrgent')"
                sortable="custom"
                show-overflow-tooltip
              >
                <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="TaskCode"
                min-width="100"
                :label="$t('trials:readTask:table:taskCode')"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 受试者编号 -->
              <el-table-column
                prop="SubjectCode"
                min-width="100"
                :label="$t('trials:readTask:table:subjectCode')"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 盲态任务标识 -->
              <el-table-column
                prop="TaskBlindName"
                min-width="100"
                :label="$t('trials:readTask:table:blindName')"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 阅片标准 -->
              <el-table-column
                prop="TrialReadingCriterionName"
                :label="$t('trials:readTask:table:criterionName')"
                min-width="140"
                show-overflow-tooltip
                sortable="custom"
              />
              <!-- 任务状态 -->
              <el-table-column
                prop="TaskState"
                :label="$t('trials:readTask:table:taskState')"
                min-width="100"
                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="ReadingCategory"
                min-width="90"
                :label="$t('trials:readTask:table:readingCategory')"
                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="TaskAllocationState"
                min-width="100"
                label="阅片状态"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.ReadingTaskState === 2" type="primary">{{ $fd('ReadingTaskState', scope.row.ReadingTaskState) }}</el-tag>
                  <el-tag v-else type="danger">{{ $fd('ReadingTaskState', scope.row.ReadingTaskState) }}</el-tag>
                </template>
              </el-table-column> -->
              <!-- 分配时间 -->
              <!--              <el-table-column-->
              <!--                prop="AllocateTime"-->
              <!--                min-width="120"-->
              <!--                :label="$t('trials:readTask:table:allocateTime')"-->
              <!--                sortable="custom"-->
              <!--                show-overflow-tooltip-->
              <!--              />-->
              <!-- 签名时间 -->
              <el-table-column
                prop="SignTime"
                min-width="120"
                :label="$t('trials:readTask:table:signTime')"
                sortable="custom"
                show-overflow-tooltip
              />
              <!-- 申请状态 -->
              <el-table-column
                v-if="!hasPermi(['role:air'])"
                prop="ReReadingApplyState"
                :label="$t('trials:readTask:table:reReadingApplyState')"
                min-width="140"
                sortable="custom"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.ReReadingApplyState === 4 || scope.row.ReReadingApplyState === 5" type="danger">{{ $fd('ReReadingApplyState', scope.row.ReReadingApplyState) }}</el-tag>
                  <el-tag v-if="scope.row.ReReadingApplyState === 2" type="primary">{{ $fd('ReReadingApplyState', scope.row.ReReadingApplyState) }}</el-tag>
                  <el-tag v-if="scope.row.ReReadingApplyState === 3" type="warning">{{ $fd('ReReadingApplyState', scope.row.ReReadingApplyState) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('common:action:action')"
                width="250"
                fixed="right"
              >
                <template slot-scope="scope">
                  <!-- 查看 -->
                  <el-button
                    circle
                    :title="$t('trials:readTask:button:view')"
                    icon="el-icon-view"
                    @click="handleReadImage(scope.row)"
                  />
                  <!-- 申请重阅 -->
                  <el-button
                    v-hasPermi="['trials:readTask:apply']"
                    :disabled="(scope.row.TaskState !== 0 && scope.row.TaskState !== 5) || scope.row.ReadingTaskState !== 2 || scope.row.ReReadingApplyState === 2 || scope.row.ReReadingApplyState === 4 || scope.row.ReReadingApplyState === 5"
                    icon="el-icon-collection"
                    circle
                    :title="$t('trials:readTask:button:apply')"
                    @click="openApplyReReading(scope.row)"
                  />
                  <el-button
                    v-hasPermi="['trials:readTask:backwardHistory']"
                    :disabled="!scope.row.ReReadingApplyState"
                    icon="el-icon-toilet-paper"
                    circle
                    :title="$t('trials:readTask:button:backward')"
                    @click="reReadingHistory(scope.row, 1)"
                  />
                </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="ApplyforReasonVisible"
      :title="$t('trials:readTask:dagTitle:apply')"
      :visible.sync="ApplyforReasonVisible"
      width="1460px"
      append-to-body
      :close-on-click-modal="false"
      custom-class="base-dialog-wrapper"
    >
      <el-form
        ref="reasonForm"
        :rules="rules"
        :model="ApplyforReasonForm"
        class="demo-ruleForm"
        size="small"
        label-width="380px"
      >
        <!-- 申请原因 -->
        <el-divider content-position="left">{{ $t('trials:readTask:title:applyReason') }}</el-divider>
        <!-- 申请原因 -->
        <el-form-item
          :label="$t('trials:readTask:title:applyReason')"
          prop="Type"
          :rules="[
            { required: true, message: $t('common:ruleMessage:select')},
          ]"
        >
          <el-radio-group v-model="ApplyforReasonForm.Type">
            <!-- 阅片记录错误 -->
            <el-radio :label="1">{{ $t('trials:readTask:option:errorRecords') }}</el-radio>
            <!-- 其他 -->
            <el-radio :label="2">{{ $t('trials:readTask:option:other') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item v-if="ApplyforReasonForm.Type === 2" :label="$t('trials:readTask:title:remark')" prop="RequestReReadingReason">
          <el-input
            v-model="ApplyforReasonForm.RequestReReadingReason"
            type="textarea"
            style="width: 400px"
            :autosize="{ minRows: 2, maxRows: 4}"
            :placeholder="$t('common:ruleMessage:specify')"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <!-- 是否复制阅片表单 -->
        <el-form-item
          :label="$t('trials:readTask:title:copyForm')"
          prop="IsCopyOrigenalForms"
          :rules="[
            { required: true, message: $t('common:ruleMessage:select')},
          ]"
        >
          <el-radio-group v-model="ApplyforReasonForm.IsCopyOrigenalForms">
            <el-radio v-for="item of $d.YesOrNo" :key="`IsCopyOrigenalForms${item.raw.Id}`" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 影响的任务列表 -->
      <el-divider content-position="left">{{ $t('trials:readTask:title:influenceList') }}</el-divider>
      <div style="padding:10px;border: 1px solid #e0e0e0;max-height:650px;overflow-y: auto;">
        <el-table
          v-loading="loading"
          :data="InfluenceTaskList"
          stripe
          height="100"
          style="min-height: 400px;"
        >
          <!-- 任务编号 -->
          <el-table-column
            prop="TaskCode"
            :label="$t('trials:readTask:table:taskCode')"
            min-width="100"
            show-overflow-tooltip
          />
          <!-- 中心编号 -->
          <el-table-column
            prop="TrialSiteCode"
            :label="$t('trials:readTask:table:siteCode')"
            min-width="100"
            show-overflow-tooltip
          />
          <!-- 受试者编号 -->
          <el-table-column
            prop="SubjectCode"
            :label="$t('trials:readTask:table:subjectCode')"
            min-width="120"
            show-overflow-tooltip
          />
          <!-- <el-table-column
            prop="VisitTaskNum"
            label="访视/阅片期名称"
            min-width="140"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{scope.row.TaskName}}
            </template>
          </el-table-column> -->
          <!-- 盲态任务标识 -->
          <el-table-column
            prop="TaskBlindName"
            :label="$t('trials:readTask:table:blindName')"
            min-width="120"
            show-overflow-tooltip
          />
          <!-- 阅片标准 -->
          <el-table-column
            prop="TrialReadingCriterionName"
            :label="$t('trials:readTask:table:criterionName')"
            min-width="100"
            show-overflow-tooltip
          />
          <!-- 任务状态 -->
          <el-table-column
            prop="TaskState"
            :label="$t('trials:readTask:table:taskState')"
            min-width="100"
            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="ReadingCategory"
            min-width="100"
            :label="$t('trials:readTask:table:readingCategory')"
            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="ReadingTaskState"
            :label="$t('trials:readTask:table:readingTaskState')"
            min-width="100"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.ReadingTaskState === 2" type="primary">{{ $fd('ReadingTaskState', scope.row.ReadingTaskState) }}</el-tag>
              <el-tag v-else type="danger">{{ $fd('ReadingTaskState', scope.row.ReadingTaskState) }}</el-tag>
            </template>
          </el-table-column>
          <!-- 生效后影响 -->
          <el-table-column
            prop="OptType"
            :label="$t('trials:readTask:table:optType')"
            min-width="100"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.OptType === 0" type="primary">{{ $fd('ReReadingOrBackOptType', scope.row.OptType) }}</el-tag>
              <el-tag v-if="scope.row.OptType === 1" type="danger">{{ $fd('ReReadingOrBackOptType', scope.row.OptType) }}</el-tag>
              <el-tag v-if="scope.row.OptType === 2" type="warning">{{ $fd('ReReadingOrBackOptType', scope.row.OptType) }}</el-tag>
            </template>
          </el-table-column>
          <!-- 阅片人 -->
          <el-table-column
            prop="UserName"
            :label="$t('trials:readTask:table:reader')"
            min-width="160"
            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>
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- 取消 -->
        <el-button :disabled="btnLoading" size="small" type="primary" @click="ApplyforReasonVisible = false;ApplyforReasonForm = { Type: null, RequestReReadingReason: null }">
          {{ $t('common:button:cancel') }}
        </el-button>
        <!-- 保存 -->
        <el-button :loading="btnLoading" size="small" type="primary" @click="applyReReading">
          {{ $t('common:button:save') }}
        </el-button>
      </div>
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getIRHaveReadTaskList, aIRReReading } from '@/api/trials'
import { applyReReading, getReReadingOrBackInfluenceTaskList, getTrialCriterionList } from '@/api/trials/reading'

import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import { getToken } from '@/utils/auth'
const searchDataDefault = () => {
  return {
    SubjectCode: '',
    SortField: '',
    PageIndex: 1,
    PageSize: 20,
    TaskState: null,
    ReadingCategory: null,
    IsUrgent: null
  }
}
export default {
  name: 'ReadTask',
  components: { BaseContainer, Pagination },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      btnLoading: false,
      trialId: '',
      ApplyforReasonVisible: false,
      ApplyforReasonForm: {
        Type: null,
        RequestReReadingReason: null,
        IsCopyOrigenalForms: null,
        IsCopyFollowForms: null
      },
      InfluenceTaskList: [],
      rules: {
        Type: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }],
        IsCopyOrigenalForms: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }],
        RequestReReadingReason: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }]
      },
      trialCriterionList: [],
      TrialReadingCriterionId: '0',
      openWindow: null
    }
  },
  watch: {
    TrialReadingCriterionId(v) {
      if (v) {
        this.getList()
      }
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getTrialCriterionList()
  },
  beforeDestroy() {
    if (this.openWindow) {
      this.openWindow.close()
    }
  },
  methods: {
    getTrialCriterionList() {
      getTrialCriterionList(this.trialId).then(res => {
        this.trialCriterionList = res.Result
        this.TrialReadingCriterionId = this.trialCriterionList[0].TrialReadingCriterionId
      }).catch(() => {})
    },
    // 重阅历史
    reReadingHistory(row) {
      this.$router.push({ path: `/trials/trials-panel/reading/rereadTask?trialId=${this.$route.query.trialId}&trialCode=${this.$route.query.trialCode}&researchProgramNo=${this.$route.query.researchProgramNo}&SiteId=${row.SiteId}&SubjectCode=${row.SubjectCode}&TaskName=${row.TaskName}` })
    },
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      this.searchData.TrialReadingCriterionId = this.TrialReadingCriterionId
      getIRHaveReadTaskList(this.searchData).then(res => {
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    handleReadImage(row) {
      if (this.openWindow) {
        this.openWindow.close()
      }
      // var token = getToken()
      // var routeData = ''
      // routeData = this.$router.resolve({
      //   path: `/readingPage?subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&trialId=${this.trialId}&visitTaskId=${row.Id}&TokenKey=${token}`
      // })
      window.localStorage.setItem('TrialReadingCriterionId', this.TrialReadingCriterionId)
      var token = getToken()
      var path = ''
      if (row.ReadingTool === 0) {
        path = `/readingDicoms?TrialReadingCriterionId=${row.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&visitTaskId=${row.Id}&isReadingTaskViewInOrder=${row.IsReadingTaskViewInOrder}&criterionType=${row.CriterionType}&readingTool=${row.ReadingTool}&TokenKey=${token}`
      } else {
        path = `/noneDicomReading?TrialReadingCriterionId=${row.TrialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${row.SubjectCode}&subjectId=${row.SubjectId}&visitTaskId=${row.Id}&isReadingTaskViewInOrder=${row.IsReadingTaskViewInOrder}&criterionType=${row.CriterionType}&readingTool=${row.ReadingTool}&TokenKey=${token}`
      }
      var routeData = this.$router.resolve({ path })
      this.openWindow = window.open(routeData.href, '_blank')
    },
    openApplyReReading(row) {
      this.rowData = { ...row }
      this.loading = true
      getReReadingOrBackInfluenceTaskList(row.Id, true).then(res => {
        this.InfluenceTaskList = res.Result
        this.ApplyforReasonVisible = true
        this.ApplyforReasonForm = {
          Type: null,
          Remake: null
        }
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    // 申请重阅
    applyReReading() {
      this.$refs.reasonForm.validate((valid) => {
        if (!valid) return
        this.loading = true
        this.btnLoading = true
        var params = {
          TaskIdList: [
            this.rowData.Id
          ],
          TrialId: this.$route.query.trialId,
          IsCopyOrigenalForms: this.ApplyforReasonForm.IsCopyOrigenalForms,
          IsCopyFollowForms: this.ApplyforReasonForm.IsCopyFollowForms,
          RequestReReadingType: 1,
          RequestReReadingReason: this.ApplyforReasonForm.Type === 2 ? this.ApplyforReasonForm.RequestReReadingReason : this.$t('trials:readTask:option:errorRecords') // '阅片记录错误'
        }
        applyReReading(params).then(res => {
          this.loading = false
          this.btnLoading = false
          this.$message.success(this.$t('trials:readTask:message:msg1')) // '申请重阅成功'
          this.getList()
          this.ApplyforReasonVisible = false
        }).catch(() => {
          this.loading = false
          this.btnLoading = false
        })
      })
    },
    // 批量重阅
    handleReread() {
      this.$confirm(this.$t('trials:readTask:message:msg2'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          var params = {
            trialId: this.trialId,
            trialReadingCriterionId: this.TrialReadingCriterionId
          }
          aIRReReading(params).then(res => {
            this.$message({
              message: this.$t('trials:readTask:message:msg3'),
              type: 'success'
            })
            this.getList()
          }).catch(() => { this.loading = false })
          console.log(params)
        })
        .catch(() => { this.loading = false })
    },
    // 排序
    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()
    }
  }
}
</script>
