<template>
  <el-dialog :visible.sync="visible" :close-on-click-modal="false" :fullscreen="true" custom-class="upload-dialog"
    :before-close="beforeCloseStudyDig">
    <span slot="title" v-if="!isAll">{{ $t('trials:inspection:message:viewStudy') }}（{{
      $t('trials:uploadDicomList:table:patientInfo')
    }}：{{ Patient.PatientIdStr }}，{{ Patient.PatientName }}）</span>
    <div class="search">
      <el-form :inline="true" class="base-search-form">
        <template v-if="isAll">
          <!-- 患者ID/患者姓名 -->
          <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
            <el-input v-model="searchData.PatientIdStr" style="width: 100px" clearable />
          </el-form-item>
          <el-form-item :label="$t('trials:uploadDicomList:table:patientName')">
            <el-input v-model="searchData.PatientName" style="width: 100px" clearable />
          </el-form-item>
          <!-- Called AE -->
          <el-form-item class="my_multiple" :label="$t('trials:inspection:search:CalledAE')">
            <el-select v-model="searchData.CalledAEList" clearable multiple style="width: 140px">
              <el-option v-for="(item, index) of calledAeList" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- Calling AE -->
          <el-form-item class="my_multiple" :label="$t('trials:inspection:search:CallingAE')">
            <el-select v-model="searchData.callingAE" clearable style="width: 140px">
              <el-option v-for="(item, index) of callingAeList" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 课题组 -->
          <el-form-item :label="$t('trials:trials-myinfo:form:StudyHospitalGroupList')">
            <el-select v-model="searchData.HospitalGroupIdList" clearable multiple style="width: 140px">
              <el-option v-for="(item) of hospitalGroupList" :key="item.Id" :label="item.Name" :value="item.Id">
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <!-- 检查类型 -->
        <el-form-item :label="$t('trials:audit:table:modality')">
          <el-select v-model="searchData.Modalities" clearable style="width: 140px">
            <el-option v-for="item of $d.modalType" :key="item.id" :label="item.label" :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 检查日期 -->
        <el-form-item :label="$t('trials:uploadedDicoms:table:studyDate')">
          <el-date-picker v-model="dateValue" type="datetimerange" range-separator="-"
            :start-placeholder="$t('trials:uploadClinicalData:table:beginDate')"
            :end-placeholder="$t('trials:uploadClinicalData:table:endDate')" :default-time="['00:00:00', '23:59:59']">
          </el-date-picker>
        </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-button type="primary" v-hasPermi="['trials:trialsInspection:addGroup']" v-if="!isAll"
            :disabled="multipleSelection.length <= 0" @click="openGroup({})">
            {{ $t('trials:inspection:button:checkGroupId') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--检查列表-->
    <el-table ref="viewStudyList" v-loading="loading" v-adaptive="{ bottomOffset: 60 }" :data="list" stripe height="100"
      @sort-change="handleSortByColumn" :default-sort="{ prop: 'StudyTime', order: 'descending' }"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" v-if="hasPermi(['trials:trialsInspection:editGroup']) && !isAll" />
      <el-table-column type="index" width="40" v-else />
      <template v-if="isAll">
        <!--患者ID-->
        <el-table-column prop="PatientIdStr" :label="$t('trials:uploadDicomList:table:pId')" show-overflow-tooltip
          min-width="120" sortable="custom"></el-table-column>
        <!--患者姓名-->
        <el-table-column prop="PatientName" :label="$t('trials:uploadDicomList:table:patientName')"
          show-overflow-tooltip min-width="120" sortable="custom"></el-table-column>
        <!--出生日期-->
        <el-table-column prop="PatientBirthDate" :label="$t('trials:inspection:table:birthdate')" show-overflow-tooltip
          min-width="120" sortable="custom"></el-table-column>
        <!--性别-->
        <el-table-column prop="PatientSex" :label="$t('trials:trials-myinfo:form:gender')" show-overflow-tooltip
          min-width="100" sortable="custom">
          <template slot-scope="scope">
            <span>{{ $fd('Sex', scope.row.PatientSex) }}</span>
          </template>
        </el-table-column>
      </template>
      <!--检查申请号-->
      <el-table-column align="center" prop="AccessionNumber" :label="$t('trials:inspection:table:AccessionNumber')"
        show-overflow-tooltip min-width="120" sortable="custom"></el-table-column>
      <!--检查描述-->
      <el-table-column align="center" prop="Description" :label="$t('trials:inspection:table:studyDescription')"
        show-overflow-tooltip min-width="120" sortable="custom"></el-table-column>
      <!--检查类型-->
      <el-table-column align="center" prop="Modalities" :label="$t('trials:audit:table:modality')" show-overflow-tooltip
        min-width="120" sortable="custom"></el-table-column>
      <!--Called AE-->
      <el-table-column prop="CalledAE" :label="$t('trials:inspection:table:CalledAE')" show-overflow-tooltip
        min-width="120">
      </el-table-column>
      <!--Calling AE-->
      <el-table-column prop="CallingAE" :label="$t('trials:inspection:table:CallingAE')" show-overflow-tooltip
        min-width="120">
      </el-table-column>
      <!--课题组-->
      <el-table-column prop="HospitalGroupList" :label="$t('trials:inspection:table:ViewHospitalGroupList')"
        show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          <span>{{
            scope.row.ViewHospitalGroupList && scope.row.ViewHospitalGroupList.length > 0 ?
              scope.row.ViewHospitalGroupList.map(item => item.Name).join(', ') : ''}}</span>
        </template>
      </el-table-column>
      <!--序列数量-->
      <el-table-column align="center" prop="SeriesCount" :label="$t('trials:audit:table:seriesCount')"
        show-overflow-tooltip min-width="100" sortable="custom"></el-table-column>
      <!--图像数量-->
      <el-table-column align="center" prop="InstanceCount" :label="$t('trials:audit:table:instanceCount')"
        show-overflow-tooltip min-width="100" sortable="custom"></el-table-column>
      <!--检查日期-->
      <el-table-column align="center" prop="StudyTime" :label="$t('trials:audit:table:studyDate')" show-overflow-tooltip
        min-width="180" sortable="custom"></el-table-column>
      <!--操作-->
      <el-table-column :label="$t('common:action:action')" min-width="200" fixed="right">
        <template slot-scope="scope">
          <!-- 影像 -->
          <el-button circle icon="el-icon-view" :title="$t('trials:inspection:button:image')"
            @click.stop="image(scope.row)" />
          <!-- 修改课题组 -->
          <el-button circle icon="el-icon-edit-outline" :title="$t('trials:inspection:button:editGroup')" v-if="!isAll"
            v-hasPermi="['trials:trialsInspection:editGroup']" @click.stop="openGroup(scope.row, 3)" />
          <!--删除-->
          <el-button circle v-hasPermi="['trials:trialsInspection:delStudy']" icon="el-icon-delete" v-if="!isAll"
            :title="$t('trials:inspection:button:delete')" @click.stop="deletePatientStudy(scope.row)" />
          <!-- 诊断报告 -->
          <el-button circle icon="el-icon-document" @click.stop="report(scope.row)"
            :title="$t('trials:inspection:button:diagnosticReport')" disabled />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
      @pagination="getList" />
    <base-model v-if="group_model.visible" :config="group_model">
      <template slot="dialog-body">
        <el-form ref="groupFrom" :model="form" :rules="rules" label-width="100px" size="small">
          <el-form-item :label="$t('trials:externalStaff:table:lastName')" prop="LastName" v-show="false">
            <el-input clearable />
          </el-form-item>
          <!-- 用户类型 -->
          <el-form-item :label="$t('trials:externalStaff:table:hospitalGroupIdList')" prop="HospitalGroupIdList">
            <el-select v-model="form.HospitalGroupIdList" style="width: 100%" multiple clearable>
              <el-option v-for="item of hospitalGroupList" :key="item.Id" :label="item.Name" :value="item.Id">
                <!-- <span>{{ item.UserType }}</span> -->
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-footer">
        <!-- 取消 -->
        <el-button size="small" type="primary" :disabled="btnLoading" @click="handleCancelGroup">
          {{ $t("common:button:cancel") }}
        </el-button>
        <!-- 保存 -->
        <el-button size="small" type="primary" :loading="btnLoading" @click="handleSaveGroup">
          {{ $t("common:button:save") }}
        </el-button>
      </template>
    </base-model>
  </el-dialog>
</template>
<script>
import Pagination from '@/components/Pagination'
import { getPatientStudyList, deletePatientStudy } from '@/api/inspection.js'
import { modifySCPStudyHospitalGroup, getHospitalGroupList } from '@/api/admin.js'
import { getToken } from '@/utils/auth'
import BaseModel from '@/components/BaseModel'
const defaultSearchData = () => {
  return {
    PatientIdStr: null,
    PatientName: null,
    CalledAEList: [],
    callingAE: null,
    ExperimentName: null,
    HospitalGroupIdList: [],
    Modalities: null,
    EarliestStudyTime: null,
    LatestStudyTime: null,
    PatientId: null,
    Asc: false,
    SortField: 'StudyTime',
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'viewStudyList',
  components: { Pagination, BaseModel },
  props: {
    visible: {
      required: true,
      default: false,
    },
    Patient: {
      required: true,
      default: () => {
        return {}
      },
    },
    isAll: {
      required: true,
      default: false,
    },
    calledAeList: {
      type: Array,
      default: () => {
        return []
      },
    },
    callingAeList: {
      type: Array,
      default: () => {
        return []
      },
    },
    hospitalGroupList: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    return {
      // 查询
      searchData: defaultSearchData(),
      dateValue: [],
      // 可加入项目列表
      loading: false,
      list: [],
      total: 0,
      multipleSelection: [],
      group_model: {
        visible: false,
        title: this.$t('trials:inspection:dialogTitle:add'),
        width: '400px',
        appendToBody: true
      },
      form: {
        HospitalGroupIdList: [],
      },
      rules: {
        HospitalGroupIdList: [
          {
            required: true,
            type: "array",
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change']
          }
        ]
      },
      btnLoading: false,
      hospitalGroupList: [],
      groupStatus: 1,
      currentData: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getHospitalGroupList() {
      try {
        let res = await getHospitalGroupList({})
        if (res.IsSuccess) {
          this.hospitalGroupList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    openGroup(row, status = 1) {
      this.form.HospitalGroupIdList = []
      this.group_model.title = this.$t('trials:inspection:dialogTitle:add')
      if (row.ViewHospitalGroupList && row.ViewHospitalGroupList.length > 0) {
        this.form.HospitalGroupIdList = row.ViewHospitalGroupList.map(item => item.Id)
        this.group_model.title = this.$t('trials:inspection:dialogTitle:edit')
      }
      this.currentData = row
      this.groupStatus = status
      this.getHospitalGroupList()
      this.group_model.visible = true
    },
    handleCancelGroup() {
      this.form.HospitalGroupIdList = []
      this.groupStatus = 1
      this.group_model.visible = false
    },
    async handleSaveGroup() {
      try {
        let validate = await this.$refs.groupFrom.validate()
        if (!validate) return false
        let ScPstudyIdList = []
        if (this.groupStatus === 1) {
          if (this.multipleSelection.length <= 0) return false
          ScPstudyIdList = this.multipleSelection.map(item => item.SCPStudyId)
        } else {
          ScPstudyIdList = [this.currentData.SCPStudyId]
        }
        let data = {
          ScPstudyIdList,
          AddOrDelete: this.groupStatus,
          HospitalGroupIdList: this.form.HospitalGroupIdList
        }
        this.btnLoading = true
        let res = await modifySCPStudyHospitalGroup(data)
        this.btnLoading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.handleCancelGroup()
          this.getList()
        }
      } catch (err) {
        console.log(err)
        this.btnLoading = false
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 删除检查
    async deletePatientStudy(item) {
      try {
        let confirm = await this.$confirm(
          this.$t('trials:inspection:message:remove'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
            confirmButtonText: this.$t('common:button:confirm'),
            cancelButtonText: this.$t('common:button:cancel'),
          }
        )
        if (confirm !== 'confirm') return
        let params = {
          PatiendId: item.PatientId,
          ScpStudyId: item.SCPStudyId,
        }
        let res = await deletePatientStudy(params)
        if (res.IsSuccess) {
          this.getList()
          this.$emit('getList')
          this.$message.success(this.$t('common:message:deletedSuccessfully'))
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 关闭弹框
    beforeCloseStudyDig() {
      this.$setOpenWindow()
      this.$emit('update:visible', false)
    },
    // 获取列表
    async getList() {
      let data = {}
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key]
      })
      if (!this.isAll) {
        data.PatientId = this.Patient.PatientId
      }
      if (this.dateValue && this.dateValue[0] && this.dateValue[1]) {
        data.EarliestStudyTime = this.$moment(this.dateValue[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        data.LatestStudyTime = this.$moment(this.dateValue[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        data.EarliestStudyTime = null
        data.LatestStudyTime = null
      }

      try {
        this.loading = true
        let res = await getPatientStudyList(data)
        this.loading = false
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.reset()
      this.getList()
    },
    // 初始化
    reset() {
      this.searchData = defaultSearchData()
      this.dateValue = []
    },
    // 查看影像
    image(item) {
      let token = getToken()
      const routeData = this.$router.resolve({
        path: `/showdicom?studyId=${item.SCPStudyId}&TokenKey=${token}&type=Patient`,
      })
      let newWindow = window.open(routeData.href, '_blank')
      this.$setOpenWindow(newWindow)
    },
    // 查看报告
    report() { },
    // 表格排序
    handleSortByColumn(sort) {
      this.searchData.SortField = sort.prop
      if (sort.order === 'ascending') this.searchData.Asc = true
      if (sort.order === 'descending') this.searchData.Asc = false
      if (!sort.order) this.searchData.SortField = null
      this.getList()
    },
  },
}
</script>
<style lang="scss" scoped></style>