<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true" class="base-search-form">
        <!-- 患者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-list:table:researchName')">
          <el-input v-model="searchData.ExperimentName" style="width: 100px" clearable />
        </el-form-item>
        <!-- 最新接收时间 -->
        <el-form-item :label="$t('trials:inspection:table:latestReceiveTime')">
          <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']"
            clearable>
          </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-form-item>
        <el-form-item>
          <!-- 推送记录 -->
          <el-button type="primary" @click="handleOpenDialog({}, 'push')">
            {{ $t('common:button:push') }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <!-- pacs拉取 -->
          <el-button type="primary" @click="handleOpenDialog({}, 'pull')"
            v-hasPermi="['trials:trialsInspection:pullPACS']">
            {{ $t('common:button:pull') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>

    <!-- 检查列表 -->
    <template slot="main-container">
      <el-table ref="inspectionList" v-loading="loading" v-adaptive="{ bottomOffset: 60 }" :data="list" stripe
        height="100" @sort-change="handleSortByColumn" :default-sort="{ prop: 'LatestPushTime', order: 'descending' }">
        <el-table-column type="index" width="40" />
        <!--患者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>
        <!--Called AE-->
        <el-table-column prop="CalledAEList" :label="$t('trials:inspection:table:CalledAE')" show-overflow-tooltip
          min-width="120">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.CalledAEList" :key="`CalledAEList${index}`">{{
              index === scope.row.CalledAEList.length - 1 ? item : `${item}, `
            }}</span>
          </template>
        </el-table-column>
        <!--Calling AE-->
        <el-table-column prop="CallingAEList" :label="$t('trials:inspection:table:CallingAE')" show-overflow-tooltip
          min-width="120">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.CallingAEList" :key="`CallingAEList${index}`">{{
              index === scope.row.CallingAEList.length - 1
                ? item
                : `${item}, `
            }}</span>
          </template>
        </el-table-column>
        <!-- 研究名称 -->
        <el-table-column prop="TrialList" :label="$t('trials:trials-list:table:researchName')" show-overflow-tooltip
          min-width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="handleOpenDialog(scope.row, 'research')"
              v-for="(item, index) in scope.row.TrialList" :key="`TrialList${index}`">
              <span>{{
                index === scope.row.TrialList.length - 1
                  ? `${item.ExperimentName}（${item.VisitCount}）`
                  : `${item.ExperimentName}（${item.VisitCount}），`
              }}</span>
            </el-button>
            <!-- <span v-else>{{ scope.row.VisitName }}</span> -->
          </template>
        </el-table-column>
        <!--课题组-->
        <el-table-column prop="StudyHospitalGroupList" :label="$t('trials:trials-myinfo:form:StudyHospitalGroupList')"
          show-overflow-tooltip min-width="100">
          <template slot-scope="scope">
            <span>{{
              scope.row.StudyHospitalGroupList && scope.row.StudyHospitalGroupList.length > 0 ?
                scope.row.StudyHospitalGroupList.map(item => item.Name).join(', '):'' }}</span>
          </template>
        </el-table-column>
        <!-- 检查数 -->
        <el-table-column prop="StudyCount" :label="$t('trials:studyList:table:count')" show-overflow-tooltip
          min-width="100" sortable="custom">
          <template slot-scope="scope">
            <el-button v-if="scope.row.StudyCount >= 1" type="text" @click="handleOpenDialog(scope.row, 'study')">
              <span>{{ scope.row.StudyCount }}</span>
            </el-button>
            <span v-else>{{ scope.row.StudyCount }}</span>
          </template>
        </el-table-column>
        <!--最新接收时间-->
        <el-table-column prop="LatestPushTime" :label="$t('trials:inspection:table:latestReceiveTime')"
          show-overflow-tooltip min-width="180" sortable="custom"></el-table-column>
        <!--操作-->
        <el-table-column :label="$t('common:action:action')" min-width="100" fixed="right" v-if="
          hasPermi([
            'trials:trialsInspection:addTrials',
            'trials:trialsInspection:delPatient',
          ])
        ">
          <template slot-scope="scope">
            <el-button circle v-hasPermi="['trials:trialsInspection:addTrials']" icon="el-icon-plus"
              :title="$t('trials:inspection:button:addTrials')" @click.stop="handleOpenDialog(scope.row, 'add')" />
            <!-- <el-button
              circle
              icon="el-icon-delete"
              v-hasPermi="['trials:trialsInspection:delPatient']"
              :title="$t('trials:inspection:button:delete')"
              @click.stop="deletePatientStudyAllData(scope.row)"
            /> -->
          </template>
        </el-table-column>
      </el-table>

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

    <!--研究项目列表-->
    <researchTrialsList v-if="researchTrialsVisible" :visible.sync="researchTrialsVisible" :Patient="selectPatient"
      @getList="getList" @handleOpenDialog="handleOpenDialog" />
    <!--可加入项目列表-->
    <addTrialsList v-if="addTrialsVisible" :visible.sync="addTrialsVisible" :Patient="selectPatient" @getList="getList"
      @handleOpenDialog="handleOpenDialog" />
    <!--查看检查列表-->
    <viewStudyList v-if="studyTrialsVisible" :visible.sync="studyTrialsVisible" :Patient="selectPatient"
      @getList="getList" />
    <!--推送记录列表-->
    <pushRecordList v-if="pushTrialsVisible" :visible.sync="pushTrialsVisible" :calledAeList="calledAeList"
      :callingAeList="callingAeList" />
    <!--pacs拉取列表-->
    <pullImage v-if="pullTrialsVisible" :visible.sync="pullTrialsVisible" :calledAeList="calledAeList"
      :callingAeList="callingAeList" />
  </BaseContainer>
</template>
<script>
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import researchTrialsList from './components/research-trials-list'
import addTrialsList from './components/add-trials-list'
import viewStudyList from './components/view-study-list'
import pushRecordList from './components/push-record-list'
import pullImage from './components/pullImage/index.vue'
import { getPatientList, deletePatientStudyAllData } from '@/api/inspection.js'
import { getDicomCalledAEList, getDicomCallingAEList } from '@/api/dicomAE.js'

const defaultSearchData = () => {
  return {
    PatientIdStr: null,
    PatientName: null,
    CalledAEList: [],
    callingAE: null,
    ExperimentName: null,
    Asc: false,
    BeginPushTime: null,
    EndPushTime: null,
    SortField: 'LatestPushTime',
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'inspection',
  components: {
    BaseContainer,
    Pagination,
    researchTrialsList,
    addTrialsList,
    viewStudyList,
    pushRecordList,
    pullImage,
  },
  data() {
    return {
      // 查询
      searchData: defaultSearchData(),
      calledAeList: [],
      callingAeList: [],
      dateValue: [],
      // 检查列表
      total: 0,
      loading: false,
      list: [],
      // 选中的患者
      selectPatient: {},
      // 研究项目列表
      researchTrialsVisible: false,
      // 可加入项目列表
      addTrialsVisible: false,
      // 查看检查列表
      studyTrialsVisible: false,
      // 推送记录列表
      pushTrialsVisible: false,
      // pacs拉取列表
      pullTrialsVisible: false,
    }
  },
  created() {
    this.getDicomCalledAEList()
    this.getDicomCallingAEList()
    this.getList()
  },
  methods: {
    // 清除数据
    async deletePatientStudyAllData(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 = {
          PatientId: item.PatientId,
        }
        let res = await deletePatientStudyAllData(params)
        if (res.IsSuccess) {
          this.getList()
          this.$message.success(this.$t('common:message:removedSuccessfully'))
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取calledAE列表
    async getDicomCalledAEList() {
      try {
        let res = await getDicomCalledAEList()
        if (res.IsSuccess) {
          this.calledAeList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取callingAE列表
    async getDicomCallingAEList() {
      try {
        let res = await getDicomCallingAEList()
        if (res.IsSuccess) {
          this.callingAeList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取列表数据
    async getList() {
      let data = {}
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key]
      })
      if (this.dateValue && this.dateValue[0] && this.dateValue[1]) {
        data.BeginPushTime = this.$moment(this.dateValue[0]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        data.EndPushTime = this.$moment(this.dateValue[1]).format(
          'YYYY-MM-DD HH:mm:ss'
        )
      } else {
        data.BeginPushTime = null
        data.EndPushTime = null
      }
      try {
        this.loading = true
        let res = await getPatientList(data)
        this.loading = false
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = defaultSearchData()
      this.$refs.inspectionList.clearSort()
      this.dateValue = []
      this.getList()
    },
    // 表格排序
    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()
    },
    // 打开弹框
    handleOpenDialog(item, key) {
      this[`${key}TrialsVisible`] = true
      this.selectPatient = item
    },
  },
  mounted() {
    this.$EventBus.$on("reload", (data) => {
      window.location.reload()
    });
  }
}
</script>
<style lang="scss" scoped></style>