<template>
  <div>
    <div class="search">
      <p class="line" v-if="showTitle">{{ $t("trials:inspection:message:confirmVisit") }}</p>
      <div class="form">
        <el-form :inline="true" class="base-search-form">
          <!-- 检查日期 -->
          <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-form-item>
        </el-form>
        <div class="buttonBox" v-if="status === 'visit'">
          <!--确认v-if="visitStatus === 'confirm'"-->
          <!-- <el-button type="primary" :loading="btnLoading2" @click="confirm">
            {{ $t("trials:seletctedReviews:timeline:confirmation") }}
          </el-button> -->
          <!--确认提交v-if="visitStatus === 'submit'"-->
          <el-button type="primary" :loading="btnLoading2" :disabled="tableSelectData.length <= 0"
            @click="confirmSubmit">
            {{ $t("trials:inspection:button:confirmAndSubmit") }}
          </el-button>
        </div>
      </div>
    </div>
    <!--可加入项目列表-->
    <!--:header-cell-style="{ background: '#f9f9f9' }"-->
    <el-table ref="confirmVisitList" v-loading="loading" v-adaptive="{ bottomOffset: 60 }" :data="list" stripe
      height="100" highlight-current-row @select="handleSelect" @selection-change="handleSelectChange"
      @sort-change="handleSortByColumn" :default-sort="{ prop: 'StudyTime', order: 'ascending' }">
      <el-table-column type="selection" align="center" :selectable="(row) => row.SubjectVisitId && Number(row.SubmitState) <= 1
        " width="45" />
      <el-table-column type="index" width="40" />
      <!--患者编号-->
      <el-table-column align="center" prop="PatientIdStr" :label="$t('trials:uploadDicomList:table:pId')"
        show-overflow-tooltip min-width="140" sortable="custom"></el-table-column>
      <!--患者姓名-->
      <el-table-column align="center" prop="PatientName" :label="$t('trials:uploadDicomList:table:patientName')"
        show-overflow-tooltip min-width="140" sortable="custom"></el-table-column>
      <!--检查描述-->
      <el-table-column align="center" prop="Description" :label="$t('trials:inspection:table:studyDescription')"
        show-overflow-tooltip min-width="140" sortable="custom"></el-table-column>
      <!--检查类型-->
      <el-table-column align="center" prop="Modalities" :label="$t('trials:audit:table:modality')" show-overflow-tooltip
        min-width="140" sortable="custom"></el-table-column>
      <!--序列数-->
      <el-table-column align="center" prop="SeriesCount" :label="$t('trials:audit:table:seriesCount')"
        show-overflow-tooltip min-width="140" sortable="custom"></el-table-column>
      <!--图像数量-->
      <el-table-column align="center" prop="InstanceCount" :label="$t('trials:audit:table:instanceCount')"
        show-overflow-tooltip min-width="140" sortable="custom"></el-table-column>
      <!--检查日期-->
      <el-table-column align="center" prop="StudyTime" :label="$t('trials:audit:table:studyDate')" show-overflow-tooltip
        min-width="140" sortable="custom"></el-table-column>
      <!--访视-->
      <el-table-column align="center" prop="StudyTime" :label="$t('trials:auditRecord:table:visit')"
        show-overflow-tooltip min-width="140">
        <template slot-scope="scope">
          <!--切换访视-->
          <visitSelect :modelData.sync="scope.row.SubjectVisitId" :disabled="Number(scope.row.SubmitState) > 1"
            :loading="addLoading" :studyData="scope.row" :list="visitList" @add="addVisit" @selectChange="selectChange"
            @putVisit="putVisit" />
        </template>
      </el-table-column>
      <!--操作-->
      <el-table-column :label="$t('common:action:action')" min-width="100" class-name="actionBox">
        <template slot-scope="scope">
          <!-- 详情 -->
          <el-button circle icon="el-icon-view" :title="$t('trials:trials-list:action:panel')"
            @click.stop="detail(scope.row)" />
          <!-- 移除 -->
          <el-button circle icon="el-icon-delete" :title="$t('common:button:remove')" @click.stop="remove(scope.row)"
            :disabled="!scope.row.SubjectVisitId || Number(scope.row.SubmitState) > 1
              " />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <!-- <pagination
      class="page"
      :total="total"
      :page.sync="searchData.PageIndex"
      :limit.sync="searchData.PageSize"
      @pagination="getList"
    /> -->
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import visitSelect from "@/components/visitSelect";
import { getToken } from "@/utils/auth";
import {
  getVisitPatientStudyList,
  getSubjectVisitSelectList,
  addOrUpdateSubjectVisit,
  submitVisitStudyBinding,
} from "@/api/inspection.js";
import { updateSubjectVisitStudyBinding } from "@/api/trials/visit.js";

const defaultSearchData = () => {
  return {
    EarliestStudyTime: null,
    LatestStudyTime: null,
    Asc: true,
    SortField: "StudyTime",
    // PageIndex: 1,
    // PageSize: 20,
  };
};
export default {
  name: "confirmVisitList",
  components: { Pagination, visitSelect },
  props: {
    Patient: {
      required: true,
      default: () => {
        return {};
      },
    },
    submitMessage: {
      require: true,
      default: () => {
        return {};
      },
    },
    status: {
      require: true,
      default: "trial",
    },
    showTitle: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 查询
      dateValue: [],
      searchData: defaultSearchData(),
      // 访视列表
      total: 0,
      loading: false,
      list: [],
      visitList: [],
      visitRule: {},
      addLoading: false,
      // 访视相关提交数据
      tableSelectData: [], // 表格选中
      selectFlag: false,
      btnLoading2: false,
      visitStatus: "confirm", // 确认访视操作状态 confirm 确认  submit 提交
    };
  },
  methods: {
    handleDetail(row) {
      this.$router.push({
        path: `/trials/trials-panel?trialId=${this.submitMessage.TrialId}&trialCode=${this.submitMessage.TrialCode}&researchProgramNo=${this.submitMessage.ResearchProgramNo}`,
      });
    },
    // 访视切换提交
    async putVisit(item) {
      let obj = {
        TrialId: this.submitMessage.TrialId,
        SubjectId: this.submitMessage.SubjectId,
        SubjectVisitId: item.VisitId,
        ScpStudyId: item.StudyId,
        IsAdd: true,
      };
      try {
        // this.btnLoading = true;
        let res = await updateSubjectVisitStudyBinding(obj);
        // this.btnLoading = false;
        if (res.IsSuccess) {
          // this.$message.success(this.$t("common:message:savedSuccessfully"));
          // this.$emit("update:visible", false);
          this.getList();
        }
      } catch (err) {
        // this.btnLoading = false;
        console.log(err);
      }
    },
    // 移除检查与访视绑定关系
    async remove(item) {
      try {
        let confirm = await this.$confirm(
          this.$t("trials:sitesList:message:removeSite"),
          {
            type: "warning",
            distinguishCancelAndClose: true,
            confirmButtonText: this.$t("common:button:confirm"),
            cancelButtonText: this.$t("recompose:button:cancel"),
          }
        );
        if (confirm !== "confirm") return;
        let data = {
          isAdd: false,
          TrialId: this.submitMessage.TrialId,
          SubjectId: this.submitMessage.SubjectId,
          SubjectVisitId: item.SubjectVisitId,
          ScpStudyId: item.SCPStudyId,
        };
        let res = await updateSubjectVisitStudyBinding(data);
        if (res.IsSuccess) {
          this.getList();
          this.$message.success(this.$t("common:message:removedSuccessfully"));
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 切换状态
    changeVisitStatus(flag = false) {
      this.visitStatus = "submit";
      if (flag) this.visitStatus = "confirm";
    },
    // 下拉框出现刷新访视
    selectChange(flag, StudyId) {
      if (flag) {
        this.getSubjectVisitSelectList(StudyId);
      }
    },
    // 获取已存在的访视
    async getSubjectVisitSelectList(StudyId = null) {
      let data = {
        TrialId: this.submitMessage.TrialId,
        SubjectId: this.submitMessage.SubjectId,
      };
      if (StudyId) data.ScpStudyId = StudyId;
      try {
        let res = await getSubjectVisitSelectList(data);
        if (res.IsSuccess) {
          this.visitRule = res.OtherInfo;
          this.visitList = res.Result.map((item) => {
            item.SubjectVisitId = item.Id;
            item.id = item.Id;
            item.label = item.VisitName;
            item.value = item.Id;
            return item;
          });
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 新增访视
    async addVisit() {
      let data = {
        TrialId: this.submitMessage.TrialId,
        SubjectId: this.submitMessage.SubjectId,
      };
      data.VisitNum = this.visitList.length;
      data.VisitName =
        this.visitRule.BlindFollowUpPrefix + " " + this.visitList.length;
      try {
        this.addLoading = true;
        let res = await addOrUpdateSubjectVisit(data);
        this.addLoading = false;
        if (res.IsSuccess) {
          this.getSubjectVisitSelectList();
        }
      } catch (err) {
        this.addLoading = false;
        console.log(err);
      }
    },
    // 获取列表
    async getList(flag = false) {
      if (this.status === "trial") {
        return this.$message.warning(
          this.$t("trials:inspection:message:checkAddTrials")
        );
      }
      let data = {};
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key];
      });
      data.patientIdList = this.Patient.PatientId;
      if (!Array.isArray(this.Patient.PatientId)) {
        data.patientIdList = [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;
      }
      data.TrialId = this.submitMessage.TrialId;
      try {
        this.loading = true;
        let res = await getVisitPatientStudyList(data);
        this.loading = false;
        if (res.IsSuccess) {
          this.list = res.Result;
          // this.total = res.Result.TotalCount;
          this.getSubjectVisitSelectList()
          if (flag) {
            this.$nextTick(() => {
              this.handleAllSelect();
            });
          }
        }
      } catch (err) {
        this.loading = false;
        console.log(err);
      }
    },
    handleDetail(row) {
      this.$router.push({
        path: `/trials/trials-panel?trialId=${row.Id}&trialCode=${row.TrialCode}&researchProgramNo=${row.ResearchProgramNo}`,
      });
    },
    // 查询
    handleSearch() {
      // this.searchData.PageIndex = 1;
      this.getList();
    },
    // 重置
    handleReset() {
      this.reset();
      this.getList();
    },
    // 初始化
    reset(flag = false) {
      this.searchData = defaultSearchData();
      this.dateValue = [];
      this.$refs.confirmVisitList.clearSort();
      if (flag) this.list = [];
    },
    // 表格高亮
    setCurrent(val) {
      this.$refs.confirmVisitList.setCurrentRow(val);
    },
    // 表格选择
    handleSelectChange(selection) {
      // console.log(selection, "handleSelectChange");
      this.tableSelectData = selection;
    },
    // 表格选择（勾选触发）
    handleSelect(selection, row) {
      if (this.selectFlag) return;
      this.selectFlag = true;
      // console.log(selection, row, "handleSelect");
      // 判断是新增还是移除
      let flag = selection.some((item) => item.SCPStudyId === row.SCPStudyId);
      let arr = [...selection];
      if (flag) {
        this.list.forEach((item) => {
          if (
            item.SubjectVisitId === row.SubjectVisitId &&
            !arr.some((data) => data.SCPStudyId === item.SCPStudyId)
          ) {
            arr.push(item);
          }
        });
      } else {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          if (item.SubjectVisitId === row.SubjectVisitId) {
            arr.splice(i, 1);
            i--;
          }
        }
      }
      this.$refs.confirmVisitList.clearSelection();
      arr.forEach((item, index) => {
        this.$refs.confirmVisitList.toggleRowSelection(item, true);
        if (index === arr.length - 1) {
          this.selectFlag = false;
        }
      });
    },
    // 表格全选
    handleAllSelect() {
      this.$refs.confirmVisitList.toggleAllSelection();
    },
    // 表格排序
    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();
    },
    // 详情
    detail(row) {
      var token = getToken();
      const routeData = this.$router.resolve({
        path: `/showdicom?studyId=${row.SCPStudyId}&TokenKey=${token}&type=Patient`,
      });
      var newWindow = window.open(routeData.href, "_blank");
      this.$emit("setOpenWindow", newWindow);
      this.$setOpenWindow(newWindow);
    },
    // 确认提交
    async confirmSubmit() {
      let confirm = await this.$confirm(
        this.$t("trials:adjustRecord:message:confirm"),
        {
          type: "warning",
          distinguishCancelAndClose: true,
          confirmButtonText: this.$t("common:button:confirm"),
          cancelButtonText: this.$t("recompose:button:cancel"),
        }
      );
      if (confirm !== "confirm") return;
      let fd = await this.formatData();
      if (!fd) return;
      let data = {
        TrialId: this.submitMessage.TrialId,
        SubjectVisitIdList: [],
        SubjectId: this.submitMessage.SubjectId,
      };
      this.tableSelectData.forEach((item) => {
        data.SubjectVisitIdList.push(item.SubjectVisitId);
      });
      try {
        this.btnLoading2 = true;
        let res = await submitVisitStudyBinding(data);
        this.btnLoading2 = false;
        if (res.IsSuccess) {
          this.$message.success(
            this.$t("trials:crcUpload:message:submittedSuccessfully")
          );
          this.$emit("close");
        }
      } catch (err) {
        this.btnLoading2 = false;
        console.log(err);
      }
    },
    // 确认提交数据校验
    formatData() {
      if (this.tableSelectData.length <= 0) {
        this.$message.warning(
          this.$t("trials:inspection:formatData:notCheckStudy")
        );
        return false;
      }

      let index = this.tableSelectData.indexOf((item) => !item.SubjectVisitId);
      if (~index) {
        this.$message.warning(
          this.$t("trials:inspection:formatData:notCheckVisit").replace(
            "xx",
            index + 1
          )
        );
        return false;
      }
      return true;
    },
  },
  // 校验表格选择访视是否符合要求
  // verifyData() {
  //   let arr = [...this.tableSelectData];
  //   arr.sort((a, b) => {
  //     new Date(a.StudyTime).getTime() - new Date(b.StudyTime).getTime();
  //   });

  // },
};
</script>
<style lang="scss" scoped>
.search {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .form {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.line {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  &::after {
    display: block;
    content: "";
    flex: 1;
    height: 1px;
    border-top: 1px solid #ddd;
  }
}

.detail {
  margin-left: 10px;
}
</style>