<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:subject:table:subjectId')">
          <el-input v-model="searchData.Code" style="width: 130px" clearable />
        </el-form-item>
        <!-- 患者编号 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
          <el-input
            v-model="searchData.PatientIdStr"
            style="width: 130px"
            clearable
          />
        </el-form-item>
        <!-- 姓名 -->
        <el-form-item :label="$t('trials:researchStaff:table:Name')">
          <el-input
            v-model="searchData.ShortName"
            style="width: 130px"
            clearable
          />
        </el-form-item>
        <!-- 性别 -->
        <el-form-item :label="$t('trials:trials-myinfo:form:gender')">
          <el-select
            v-model="searchData.Sex"
            clearable
            filterable
            style="width: 130px"
          >
            <el-option
              v-for="item of $d.Sex"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 状态 -->
        <!-- <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>
      <span style="margin-left: auto">
        <el-button
          v-hasPermi="['trials:trials-panel:subject:new']"
          type="primary"
          icon="el-icon-plus"
          @click="handleOpenDialog({}, 'addSubject')"
        >
          {{ $t("common:button:new") }}
        </el-button>
      </span>
    </template>

    <template slot="main-container">
      <!-- 受试者列表 -->
      <el-table
        ref="subjectList"
        v-loading="loading"
        v-adaptive="{ bottomOffset: 60 }"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
        :default-sort="{ prop: 'CreateTime', order: 'descending' }"
      >
        <el-table-column type="index" width="40" />
        <!-- 受试者编号 -->
        <el-table-column
          prop="Code"
          :label="$t('trials:subject:table:subjectId')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 患者编号 -->
        <el-table-column
          prop="PatientList.PatientIdStr"
          :label="$t('trials:uploadDicomList:table:pId')"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span
              v-for="(item, index) in scope.row.PatientList"
              :key="`${item.PatientId}${index}`"
              @click.stop="
                openPatientStudy(scope.row.PatientList, scope.row.Id)
              "
              style="color: #68a2d5; cursor: pointer"
            >
              {{
                index === scope.row.PatientList.length - 1
                  ? item.PatientIdStr
                  : `${item.PatientIdStr}, `
              }}
            </span>
          </template>
        </el-table-column>
        <!-- 姓名 -->
        <el-table-column
          prop="ShortName"
          :label="$t('trials:researchStaff:table:Name')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 性别 -->
        <el-table-column
          prop="Sex"
          :label="$t('trials:trials-myinfo:form:gender')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <span>{{ $fd("Sex", scope.row.Sex) }}</span>
          </template>
        </el-table-column>
        <!-- 出生日期 -->
        <el-table-column
          prop="BirthDate"
          :label="$t('trials:inspection:table:birthdate')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <span>{{
              scope.row.BirthDate ? scope.row.BirthDate.split(" ")[0] : ""
            }}</span>
          </template>
        </el-table-column>
        <!-- 年龄 -->
        <el-table-column
          prop="Age"
          :label="$t('trials:subject:table:age')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 总访视量 -->
        <el-table-column
          prop="VisitCount"
          :label="$t('trials:subject:table:totalVisitCount')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.VisitCount >= 1"
              type="text"
              @click="gotoVisit(scope.row)"
            >
              <span>{{ scope.row.VisitCount }}</span>
            </el-button>
            <span v-else>{{ scope.row.VisitCount }}</span>
          </template>
        </el-table-column>
        <!-- 最新检查访视 -->
        <el-table-column
          prop="LatestVisitName"
          :label="$t('trials:subject:table:latestStudiesVisitName')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 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="CreateTime"
          :label="$t('trials:trials-list:table:createDate')"
          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="200"
          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.PatientList.length <= 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-dialogDrag
      v-if="editDialog.visible"
      :visible.sync="editDialog.visible"
      :close-on-click-modal="false"
      :title="editDialog.title"
      width="500px"
      custom-class="base-dialog-wrapper"
    >
      <SubjectsForm
        :data="rowData"
        :other-info="otherInfo"
        @close="closeEditDialog"
        @getList="getList"
      />
    </el-dialog>

    <!-- 修改受试者状态 -->
    <el-dialog
      v-dialogDrag
      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>
    <!--添加受试者-->
    <addSubject
      v-if="addSubjectTrialsVisible"
      :visible.sync="addSubjectTrialsVisible"
      @handleOpenDialog="handleOpenDialog"
      @getList="getList"
    />
    <!--患者列表-->
    <patientStudyList
      v-if="PitentVisible"
      :visible.sync="PitentVisible"
      :list.sync="PitentStudyList"
      :SubjectId="PitentStudySubjectId"
      @getList="getList"
    />
  </BaseContainer>
</template>
<script>
import { deleteSubject } from "@/api/trials";
import { getPatientSubejctList } from "@/api/trials/subject";
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 addSubject from "./components/add-subject.vue";
import patientStudyList from "./components/patient-study-list.vue";
// import confirmVisitList from "../../../trials-inspection/components/confirm-visit-list.vue";
const searchDataDefault = () => {
  return {
    PatientIdStr: null,
    Code: "",
    Status: "",
    Sex: "",
    ShortName: "",
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: "CreateTime",
  };
};
export default {
  name: "SubjectList",
  components: {
    BaseContainer,
    Pagination,
    SubjectsForm,
    SubjectStatusForm,
    addSubject,
    patientStudyList,
  },
  data() {
    return {
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      rowData: {},
      otherInfo: {},
      editDialog: { title: "", visible: false },
      statusVisible: false,
      trialId: "",
      // 添加受试者
      addSubjectTrialsVisible: false,
      // 确认访视
      confirmTrialsVisible: false,
      // 患者列表（点击病历号打开）
      PitentVisible: false,
      PitentStudyList: [],
      PitentStudySubjectId: null,
    };
  },
  watch: {
    list() {
      this.$nextTick(() => {
        this.$refs.subjectList && this.$refs.subjectList.doLayout();
      });
    },
  },
  mounted() {
    this.trialId = this.$route.query.trialId;
    this.getList();
  },
  methods: {
    // 跳转至访视页
    gotoVisit(item) {
      let query = this.$route.query;
      this.$router.push({
        path: "/trials/trials-panel/hir-visit",
        query,
      });
      zzSessionStorage.setItem("SubjectCode", item.Code);
    },
    handleExport() {
      getSubjectList_Export(this.searchData)
        .then((res) => {})
        .catch(() => {
          this.loading = false;
        });
    },
    openPatientStudy(list, id) {
      this.PitentStudyList = list;
      this.PitentStudySubjectId = id;
      this.PitentVisible = true;
    },
    // 获取受试者列表
    async getList() {
      let data = {};
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key];
      });
      data.TrialId = this.$route.query.trialId;
      try {
        this.loading = true;
        let res = await getPatientSubejctList(data);
        this.loading = false;
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData;
          this.total = res.Result.TotalCount;
          this.otherInfo = res.OtherInfo;
        }
      } catch (err) {
        this.loading = false;
        console.log(err);
      }
    },
    // 新增
    // 打开弹框
    handleOpenDialog(item, key) {
      this[`${key}TrialsVisible`] = 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;
          });
      });
    },
    // 查询
    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();
    },
    // 打开编辑状态框
    handleEditStatus(row) {
      this.rowData = { ...row };
      this.statusVisible = true;
    },
    // 关闭状态编辑框
    closeStatusDialog() {
      this.statusVisible = false;
    },
  },
};
</script>
