<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- Site -->
<!--        <el-form-item :label="$t('trials:subject:table:site')">-->
<!--          <el-select v-model="searchData.SiteId" clearable filterable style="width:130px;">-->
<!--            <el-option-->
<!--              v-for="(item,index) of siteOptions"-->
<!--              :key="index"-->
<!--              :label="item.TrialSiteCode"-->
<!--              :value="item.SiteId"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <!-- Subject ID -->
        <el-form-item :label="$t('trials:subject:table:subjectId')">
          <el-input :maxLength="$inputMax" v-model="searchData.Code" style="width:130px;" />
        </el-form-item>
        <!-- Status -->
        <el-form-item :label="$t('trials:subject:table:gender')">
          <el-select v-model="searchData.Sex" clearable style="width:130px;">
            <el-option v-for="item of $d.Sex" :key="item.value" :value="item.label" :label="item.label" />
          </el-select>
        </el-form-item>
        <!-- Status -->
        <el-form-item :label="$t('trials:subject:table:status')">
          <el-select v-model="searchData.Status" clearable style="width:130px;">
            <el-option v-for="item of $d.Subject_Visit_Status" :key="item.value" :value="item.value" :label="item.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-button type="primary" icon="el-icon-download" @click="handleExport">-->
<!--            {{ $t('common:button:export') }}-->
<!--          </el-button>-->
        </el-form-item>
      </el-form>
      <el-button
        v-if="visitPlanConfirmed"
        v-hasPermi="['trials:trials-panel:subject:new']"
        type="primary"
        icon="el-icon-plus"
        style="margin-left:auto;"
        @click="handleAdd"
      >
        {{ $t('common:button:new') }}
      </el-button>
    </template>

    <template slot="main-container">
      <!-- 受试者列表 -->
      <el-table
        ref="subjectList"
        v-loading="loading"
        v-adaptive="{bottomOffset:60}"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
      >
        <el-table-column type="index" width="40" />
        <!-- Site -->
<!--        <el-table-column-->
<!--          prop="TrialSiteCode"-->
<!--          :label="$t('trials:subject:table:site')"-->
<!--          sortable="custom"-->
<!--          show-overflow-tooltip-->
<!--          width="120"-->
<!--        />-->
        <!-- Code -->
        <el-table-column
          prop="Code"
          :label="$t('trials:subject:table:subjectId')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 第二编号 -->
        <el-table-column
          v-if="otherInfo.IsSubjectSecondCodeView"
          prop="MedicalNo"
          :label="$t('trials:subject:table:medicalNo')"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="Age"
          :label="$t('trials:subject:table:age')"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="Sex"
          :label="$t('trials:subject:table:gender')"
          show-overflow-tooltip
          sortable="custom"
        >
        </el-table-column>
        <!-- 访视基准日期 -->
<!--        <el-table-column-->
<!--          prop="FirstGiveMedicineTime"-->
<!--          :label="$t('trials:subject:table:firstGiveMedicineTime')"-->
<!--          sortable="custom"-->
<!--          show-overflow-tooltip-->
<!--          width="150"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            {{ scope.row.FirstGiveMedicineTime?moment(scope.row.FirstGiveMedicineTime).format('YYYY-MM-DD'):'' }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <!-- Status -->
        <el-table-column
          prop="Status"
          :label="$t('trials:subject:table:status')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.Status === 1" type="primary">{{ $fd('Subject_Visit_Status', scope.row.Status) }}</el-tag>
            <el-tag v-if="scope.row.Status === 2" type="danger">{{ $fd('Subject_Visit_Status', scope.row.Status) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 总访视量 -->
        <el-table-column
          prop="TotalVisitCount"
          :label="$t('trials:subject:table:totalVisitCount')"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.TotalVisitCount > 0 && (hasCrcRoute || hasQCRoute)"
              type="text"
              @click="handleTotalVisitCount(scope.row.Code)"
            >
              {{ scope.row.TotalVisitCount }}
            </el-button>
            <span v-else> {{ scope.row.TotalVisitCount }}</span>
          </template>
        </el-table-column>
<!--        &lt;!&ndash; 计划访视量 &ndash;&gt;-->
<!--        <el-table-column-->
<!--          prop="InPlanVisitCount"-->
<!--          :label="$t('trials:subject:table:inPlanVisitCount')"-->
<!--          show-overflow-tooltip-->
<!--          sortable="custom"-->
<!--          min-width="120"-->
<!--        />-->
<!--        &lt;!&ndash; 计划外访视量 &ndash;&gt;-->
<!--        <el-table-column-->
<!--          prop="OutPlanVisitCount"-->
<!--          :label="$t('trials:subject:table:outPlanVisitCount')"-->
<!--          show-overflow-tooltip-->
<!--          sortable="custom"-->
<!--          min-width="130"-->
<!--        />-->
<!--        &lt;!&ndash; 当前提交访视量 &ndash;&gt;-->
<!--        <el-table-column-->
<!--          prop="TotalVisitSubmmitCount"-->
<!--          :label="$t('trials:subject:table:totalVisitSubmmitCount')"-->
<!--          show-overflow-tooltip-->
<!--          min-width="130"-->
<!--        />-->
<!--        &lt;!&ndash; 是否漏传 &ndash;&gt;-->
<!--        <el-table-column-->
<!--          prop="IsMissingImages"-->
<!--          :label="$t('trials:subject:table:isMissingImages')"-->
<!--          show-overflow-tooltip-->
<!--          sortable="custom"-->
<!--          min-width="120"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <el-tag v-if="scope.row.IsMissingImages" type="danger">{{ $fd('YesOrNo', scope.row.IsMissingImages) }}</el-tag>-->
<!--            <el-tag v-else type="primary">{{ $fd('YesOrNo', scope.row.IsMissingImages) }}</el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        &lt;!&ndash; 漏提交访视量 &ndash;&gt;-->
<!--        <el-table-column-->
<!--          prop="MissingSubmmitCount"-->
<!--          :label="$t('trials:subject:table:missingSubmmitCount')"-->
<!--          show-overflow-tooltip-->
<!--          min-width="120"-->
<!--        />-->
<!--        &lt;!&ndash; 失访访视量 &ndash;&gt;-->
<!--        <el-table-column-->
<!--          prop="LostVisitCount"-->
<!--          :label="$t('trials:subject:table:lostVisitCount')"-->
<!--          show-overflow-tooltip-->
<!--          min-width="120"-->
<!--        />-->
        <!-- 最新提交访视名称 -->
        <el-table-column
          prop="LatestVisitName"
          :label="$t('trials:subject:table:latestVisitName')"
          show-overflow-tooltip
          sortable="custom"
        />

        <el-table-column
          v-if="hasPermi(['trials:trials-panel:subject:edit', 'trials:trials-panel:subject:status', 'trials:trials-panel:subject:delete'])"
          :label="$t('common:action:action')"
          width="250"
          fixed="right"
        >
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              v-hasPermi="['trials:trials-panel:subject:edit']"
              circle
              :title="$t('trials:subject:action:edit')"
              icon="el-icon-edit-outline"
              @click="handleEdit(scope.row)"
            />
            <!-- 修改状态 -->
            <el-button
              v-hasPermi="['trials:trials-panel:subject:status']"
              circle
              :title="$t('trials:subject:action:status')"
              icon="el-icon-edit"
              @click="handleEditStatus(scope.row)"
            />
            <!-- 删除 -->
            <el-button
              v-hasPermi="['trials:trials-panel:subject:delete']"
              circle
              :title="$t('trials:subject:action:delete')"
              icon="el-icon-delete"
              :disabled="scope.row.StudyCount>0"
              @click="handleDelete(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="editDialog.visible"
      :visible.sync="editDialog.visible"
      :close-on-click-modal="false"
      :title="editDialog.title"
      width="700px"
      custom-class="base-dialog-wrapper"
    >
      <SubjectsForm :data="rowData" :other-info="otherInfo" @close="closeEditDialog" @getList="getList" />
    </el-dialog>

    <!-- 修改受试者状态 -->
    <el-dialog
      v-if="statusVisible"
      :visible.sync="statusVisible"
      :close-on-click-modal="false"
      :title="$t('trials:subject:dialogTitle:editStatus')"
      width="700px"
      custom-class="base-dialog-wrapper"
    >
      <SubjectStatusForm :data="rowData" @closeDialog="closeStatusDialog" @getList="getList" />
    </el-dialog>
    <!-- 修改受试者状态 -->
    <el-dialog
      v-if="MessageVisible"
      :visible.sync="MessageVisible"
      :close-on-click-modal="false"
      :title="$t('trials:subject:title:sendReport').replace('xxx',rowData.Code)"
      width="720px"
      custom-class="base-dialog-wrapper"
    >
      <MessageTable :data="rowData" @closeDialog="closeStatusDialog" @getList="getList" />
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getTrialSiteSelect, getSubjectList, deleteSubject } from '@/api/trials'
import { getSubjectList_Export } from '@/api/export'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import SubjectsForm from './components/SubjectsForm'
import SubjectStatusForm from './components/SubjectStatusForm'
import MessageTable from './components/MessageTable'
import moment from 'moment'
const searchDataDefault = () => {
  return {
    Code: '',
    Status: '',
    SiteId: '',
    ShortName: '',
    Sex: '',
    PageIndex: 1,
    PageSize: 20
  }
}
export default {
  name: 'SubjectList',
  components: { BaseContainer, Pagination, SubjectsForm, SubjectStatusForm, MessageTable },
  data() {
    return {
      moment,
      MessageVisible: false,
      model_cfg: { visible: false, showClose: true, width: '700px', title: '' },
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      siteOptions: [],
      visitPlanConfirmed: false,
      rowData: {},
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      otherInfo: {},
      editDialog: { title: '', visible: false },
      statusVisible: false,
      trialId: '',
      hasCrcRoute: false,
      hasQCRoute: false
    }
  },
  watch: {
    list() {
      this.$nextTick(() => {
        this.$refs.subjectList.doLayout()
      })
    }
  },
  mounted() {
    const trialsRouter = this.$store.getters.routes.find(r => { return r.name === 'Trials' })
    const trialsPanelRouter = trialsRouter.children.find(r => { return r.name === 'TrialsPanel' }).children
    this.hasCrcRoute = this.hasRoute('crc-upload', trialsPanelRouter)
    this.hasQCRoute = this.hasRoute('qc-check', trialsPanelRouter)
    this.trialId = this.$route.query.trialId
    this.getSite()
    this.getList()
  },
  methods: {
    handleMessage(row) {
      this.rowData = { ...row }
      this.MessageVisible = true
    },
    handleExport() {
      getSubjectList_Export(this.searchData).then(res => {
      }).catch(() => { this.loading = false })
    },
    // 获取受试者列表
    getList() {
      this.loading = true
      this.searchData.TrialId = this.$route.query.trialId
      getSubjectList(this.searchData).then(res => {
        this.loading = false
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
        this.otherInfo = res.OtherInfo
        this.visitPlanConfirmed = res.OtherInfo.VisitPlanConfirmed
      }).catch(() => { this.loading = false })
    },
    // 新增
    handleAdd() {
      this.rowData = {}
      this.editDialog.title = this.$t('common:button:new')
      this.editDialog.visible = true
    },
    // 编辑
    handleEdit(row) {
      this.rowData = row
      this.editDialog.title = this.$t('trials:subject:dialogTitle:edit')
      this.editDialog.visible = true
    },
    // 关闭弹窗
    closeEditDialog() {
      this.editDialog.visible = false
    },
    // 删除
    handleDelete(row) {
      this.$confirm(this.$t('trials:subject:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          deleteSubject(this.trialId, row.Id)
            .then(res => {
              this.loading = false
              if (res.IsSuccess) {
                // this.list.splice(this.list.findIndex(item => item.Id === row.Id), 1)
                this.getList()
                this.$message.success(this.$t('common:message:deletedSuccessfully'))
              }
            }).catch(() => { this.loading = false })
        })
    },
    // 审计
    handleAudit(row) {
      const routeData = this.$router.resolve({
        path: '/audit',
        query: { Id: row.TrialId, Code: this.$route.query.trialCode, SubName: row.Name, SubId: row.Id, Type: 2 }
      })
      window.open(routeData.href, '_blank')
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      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
      })
    },
    // 打开编辑状态框
    handleEditStatus(row) {
      this.rowData = { ...row }
      this.statusVisible = true
    },
    // 关闭状态编辑框
    closeStatusDialog() {
      this.statusVisible = false
    },
    handleTotalVisitCount(subjectCode) {
      if (this.hasCrcRoute) {
        this.$router.push({ path: `/trials/trials-panel/visit/crc-upload?trialId=${this.$route.query.trialId}&trialCode=${this.$route.query.trialCode}&researchProgramNo=${this.$route.query.researchProgramNo}&subjectCode=${subjectCode}` })
      } else if (this.hasQCRoute) {
        this.$router.push({ path: `/trials/trials-panel/visit/qc-check?trialId=${this.$route.query.trialId}&trialCode=${this.$route.query.trialCode}&researchProgramNo=${this.$route.query.researchProgramNo}&subjectCode=${subjectCode}` })
      }
    },
    hasRoute(name, routeList) {
      for (let i = 0; i < routeList.length; i++) {
        if (routeList[i].name === name) {
          return true
        }
        if (routeList[i].children) {
          const flag = this.hasRoute(name, routeList[i].children)
          if (flag) {
            return flag
          }
        }
      }
      return false
    }
  }
}
</script>
