<template>
  <div>
    <div class="search">
      <p class="line">{{ $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="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </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"
            @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
      @selection-change="handleSelectChange"
      @sort-change="handleSortByColumn"
      :default-sort="{ prop: 'StudyTime', order: 'descending' }"
    >
      <el-table-column type="selection" align="center" 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
        :label="$t('common:action:action')"
        width="300"
        class-name="actionBox"
      >
        <template slot-scope="scope">
          <!--切换访视-->
          <visitSelect
            :modelData.sync="scope.row.SubjectVisitId"
            :loading="addLoading"
            :list="visitList"
            @add="addVisit"
            @selectChange="selectChange"
          />
          <!-- 详情 -->
          <el-button
            type="text"
            @click.stop="detail(scope.row)"
            class="detail"
            disabled
            >{{ $t("trials:trials-list:action:panel") }}</el-button
          >
        </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 {
  getVisitPatientStudyList,
  getSubjectVisitSelectList,
  addOrUpdateSubjectVisit,
  addSubjectPatientStudyBinding,
  submitVisitStudyBinding,
} from "@/api/inspection.js";

const defaultSearchData = () => {
  return {
    EarliestStudyTime: null,
    LatestStudyTime: null,
    Asc: false,
    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",
    },
  },
  data() {
    return {
      // 查询
      dateValue: [],
      searchData: defaultSearchData(),
      // 访视列表
      total: 0,
      loading: false,
      list: [],
      visitList: [],
      visitRule: {},
      addLoading: false,
      // 访视相关提交数据
      tableSelectData: [], // 表格选中
      btnLoading2: false,
      visitStatus: "confirm", // 确认访视操作状态 confirm 确认  submit 提交
    };
  },
  methods: {
    // 切换状态
    changeVisitStatus(flag = false) {
      this.visitStatus = "submit";
      if (flag) this.visitStatus = "confirm";
    },
    // 下拉框出现刷新访视
    selectChange(flag) {
      if (flag) {
        this.getSubjectVisitSelectList();
      }
    },
    // 获取已存在的访视
    async getSubjectVisitSelectList() {
      let data = {
        TrialId: this.submitMessage.TrialId,
        SubjectId: this.submitMessage.SubjectId,
      };
      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[0] && this.dateValue[1]) {
        data.earliestStudyTime = this.dateValue[0].toISOString();
        data.latestStudyTime = this.dateValue[1].toISOString();
      } 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.CurrentPageData;
          this.total = res.Result.TotalCount;
          if (flag) {
            this.$nextTick(() => {
              this.handleAllSelect();
            });
          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 查询
    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);
      this.tableSelectData = selection;
    },
    // 表格全选
    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() {},
    // 确认
    async confirm() {
      let fd = await this.formatData();
      if (!fd) return;
      let arr = this.tableSelectData.map((item) => {
        let obj = {
          TrialId: this.submitMessage.TrialId,
          SubjectId: this.submitMessage.SubjectId,
          SubjectVisitId: item.SubjectVisitId,
          ScpStudyId: item.SCPStudyId,
        };
        return obj;
      });
      try {
        this.btnLoading2 = true;
        let res = await addSubjectPatientStudyBinding(arr);
        this.btnLoading2 = false;
        if (res.IsSuccess) {
          this.visitStatus = "submit";
          this.$message.success(this.$t("common:message:savedSuccessfully"));
        }
      } catch (err) {
        this.btnLoading2 = false;
        console.log(err);
      }
    },
    // 确认提交
    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 : [],
      };
      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")
          );
        }
      } 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>