<template>
  <el-select
    v-model="visit"
    placeholder="请选择"
    @visible-change="selectChange"
    @change="handleChange"
    :disabled="disabled"
  >
    <el-option
      v-for="item in list"
      :key="item.id"
      :label="item.label"
      :value="item.value"
      :disabled="Number(item.SubmitState) > 1"
    />
    <p class="addVisit" @click.stop="add">
      <i class="el-icon-plus" v-loading="loading"></i>
    </p>
  </el-select>
</template>
<script>
import moment from "moment";
export default {
  name: "visitSelect",
  props: {
    list: {
      required: true,
      default: () => {
        return [];
      },
    },
    studyData: {
      required: true,
      default: () => {
        return {};
      },
    },
    disabled: {
      default: false,
    },
    modelData: {
      required: true,
    },
    loading: {
      required: true,
      default: false,
    },
  },
  data() {
    return {
      visit: null,
    };
  },
  watch: {
    modelData: {
      handler() {
        this.visit = this.modelData;
      },
      immediate: true,
    },
  },
  methods: {
    add() {
      this.$emit("add");
    },
    selectChange(flag) {
      this.$emit("selectChange", flag, this.studyData.StudyId);
    },
    async handleChange() {
      try {
        let res = await this.formatVisit();
        if (!res) return;
        this.$emit("update:modelData", this.visit);
        let data = {
          StudyId: this.studyData.StudyId || this.studyData.SCPStudyId,
          VisitId: this.visit,
        };
        this.$emit("putVisit", data);
      } catch (err) {
        console.log(err);
      }
    },
    // 校验选择访视与检查时间是否匹配
    async formatVisit() {
      try {
        let StudyTime = this.studyData.StudyTime;
        let visitIndex = this.list.findIndex((item) => item.Id === this.visit);
        if (visitIndex >= 1) {
          let time = this.list[visitIndex - 1].VisitMaxStudyTime;
          if (time && moment(StudyTime).isBefore(time)) {
            throw "Out of range";
          }
        }
        if (visitIndex < this.list.length - 1 && visitIndex >= 0) {
          let time = this.list[visitIndex + 1].VisitMinStudyTime;
          if (time && moment(StudyTime).isAfter(time)) {
            throw "Out of range";
          }
        }
        let visit = this.list[visitIndex];
        if (
          (visit.VisitMinStudyTime &&
            moment(StudyTime).isBefore(
              moment(visit.VisitMinStudyTime)
                .subtract(15, "day")
                .format("YYYY-MM-DD HH:mm:ss")
            )) ||
          (visit.VisitMaxStudyTime &&
            moment(StudyTime).isAfter(
              moment(visit.VisitMaxStudyTime)
                .add(15, "day")
                .format("YYYY-MM-DD HH:mm:ss")
            ))
        ) {
          let message = this.$t("trials:studyVisit:format:studyTime");
          message = message.replace("minTime", visit.VisitMinStudyTime);
          message = message.replace("maxTime", visit.VisitMaxStudyTime);
          message = message.replace("studyTime", StudyTime);
          this.$confirm(
            message,
            this.$t("trials:uploadDicomList:label:prompt"),
            {
              type: "warning",
              // showCancelButton: false,
            }
          )
            .then(() => {
              this.$emit("update:modelData", this.visit);
              let data = {
                StudyId: this.studyData.StudyId || this.studyData.SCPStudyId,
                VisitId: this.visit,
              };
              this.$emit("putVisit", data);
            })
            .catch((err) => {
              this.visit = this.modelData;
            });
          return false;
        }
        return true;
      } catch (err) {
        console.log(err);
        if (err === "Out of range") {
          this.$confirm(
            this.$t("trials:studyVisit:format:studyTimeNo"),
            this.$t("trials:uploadDicomList:label:prompt"),
            {
              type: "warning",
              showCancelButton: false,
            }
          ).then();
          this.visit = this.modelData;
        }
        return false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.addVisit {
  margin: 0;
  line-height: 34px;
  text-align: center;
  cursor: pointer;
}
</style>