<template>
  <div class="appointment-add">
    <div class="appointment-add__header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in $route.matched"
          :key="index"
          :to="{ path: item.path }"
          >{{ item.name }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="appointment-add__body">
      <el-form
        class="appointment-content"
        ref="form"
        :model="form"
        label-width="100px"
      >
        <div class="appointment-content__body">
          <el-descriptions title="预约考试"></el-descriptions>
          <el-form-item label="考试地点：">
            <el-select
              v-model="addressId"
              placeholder="请选择"
              @change="addressChange"
            >
              <el-option
                :label="item.siteAddress"
                :value="item.id"
                v-for="(item, index) in listData"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试时间：">
            <el-select
              v-if="activeList && activeList.length"
              v-model="timeIndex"
              placeholder="请选择"
            >
              <el-option
                :label="
                  item.dataTime +
                  ' ' +
                  item.startTime +
                  ' ~ ' +
                  item.endTime +
                  `已报：${item.registration}/ ${item.num} ` +
                  (item.status === 2
                    ? '预约名额已满'
                    : item.status === 1
                    ? '此时段您已经有其他考试预约'
                    : '')
                "
                :disabled="item.status !== 0"
                :value="index"
                v-for="(item, index) in activeList"
                :key="index"
              ></el-option>
            </el-select>
            <span v-if="addressId && !activeList.length">该考试地点暂无考试时间，建议重新选择考试地点</span>
          </el-form-item>

          <el-form-item v-if="reportStatus == 1" label="考试疫情防控承诺书：" label-width="165px">
            <div class="commitment">
              本人参加“住房和城乡建设领域施工现场专业人员岗位”考试，愿意遵守疫情防控各项管理的相关要求，秉承对自己、对他人负责的原则，承担疫情防控社会责任，郑重作出以下承诺：<br/>
              一、充分理解并遵守考试期间考点各项防疫安全的要求。<br/>
              二、在考试前14天内，没有到过国内疫情中风险、高风险地区，未出境，不存在自境外回国情形。<br/>
              三、在考试前14天内，每日自觉监测体温，体温均未出现高于37.3度的情形，无发热和呼吸道门诊就诊史。<br/>
              四、在考试前14天内，未和新冠肺炎病例或疑似病例密切接触或间接接触，没有发烧、干咳、乏力、咳痰、气短、肌肉痛或关节痛、咽喉痛、头痛、寒颤、恶心或呕吐、鼻塞、腹泻、咳血、结膜充血等疑似新冠肺炎症状。<br/>
              五、如出现与前述第二、三、四项任何一项不符的情形之一的，本人将及时在考前向相关管理机构报告，自觉配合采取隔离或其他防疫措施，并根据情况，自愿放弃参加考试。<br/>
              六、考试当日自行做好防护工作，佩戴防护口罩。提前抵达考点，配合查验健康码、测量体温等。<br/>
              七、考试期间，将严格遵守应考人员考场守则及疫情防控相关管理要求，完成考试后立即离场，不扎堆，不聚集。<br/>
              八、本人承诺遵守《应考人员安全承诺书》中所有承诺内容，若因有瞒报、谎报造成新冠肺炎疫情传播的，一经查实，由本人承担相应的法律和经济责任。
            </div>
          </el-form-item>
          <el-form-item v-if="reportStatus == 1" label="签名板：">
            <div class="dis_stys">
              <span style="color: #999999">请在下方签名区进行签名</span>
              <el-button
                type="primary"
                size="mini"
                @click="retDraw"
                mode=""
                >清空</el-button
              >
            </div>
            <div class="handCenter">
              <vue-esign
                ref="esign"
                :width="600"
                :height="300"
                :isCrop="false"
                :lineWidth="5"
                :lineColor="'#333'"
              />
              <!-- <div
                v-else
                style="width: 100%; height: 100%; position: relative"
              >
                <img
                  style="width: 100%; height: 100%"
                  :src="$tools.splitImgHost(infoForm[item.fieldKey])"
                  mode=""
                />
              </div> -->
            </div>
          </el-form-item>
        </div>

        <div class="appointment-content__footer">
          <div class="btns">
            <div class="cancel" @click="cancel">上一步</div>
            <div v-loading="subLoading" class="ok" @click="sureOppoint">
              {{ dataId == 1 ? "下一步" : dataId == 2 ? "确定预约" : "异常" }}
            </div>
          </div>
        </div>
      </el-form>
    </div>

    <el-dialog
      width="400px"
      class="appointment-modal"
      :visible.sync="showDetailModal"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="appointment-modal__content">
        <div class="appointment-modal__close" @click="showDetailModal = false">
          X
        </div>
        <div class="appointment-modal__header">提示</div>
        <div class="appointment-modal__body">
          <div class="content">
            <div class="content__body">
              <div class="icon-text">
                <div class="icon">✔</div>
                <div class="text">考试预约成功</div>
              </div>
              <div class="confirm" @click="viewAppointment">查看预约</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  name: "Myappointment",
  data() {
    return {
      form: {},
      showDetailModal: false,
      addressId: "", //当前选中考试点ID
      timeIndex: "", //当前选中考试点ID
      listData: [], //考试地点数据
      activeList: [], //选中考试地点列表
      applyId: "",
      goodsId: "",
      applyStatus: "",
      dataId: "",
      orderGoodsId: "",
      addressName: "",
      isUploading: false,
      subLoading: false,
      commitment_electr_signature: '',
      siteId: '', // 考场id
      reportStatus: 0, // 是否线上签署疫情防控承诺书， 1是，0否
      baseAddress: '', // 签名转成base64
    };
  },
  mounted() {
    this.applyId = this.$route.query.applyId;
    this.goodsId = this.$route.query.goodsId;
    this.applyStatus = this.$route.query.applyStatus;
    this.dataId = this.$route.query.dataId;
    this.orderGoodsId = this.$route.query.orderGoodsId;
    this.reportStatus = this.$route.query.reportStatus

    this.getApplysubscribeApplySite();
  },
  methods: {
    ...mapMutations(["updateApplyData"]),
    cancel() {
      this.$router.go(-1);
    },
    viewAppointment(){
      this.$router.push({
        path:"/person-center/my-examination"
      })
    },
    addressChange() {
      var arrays = [];
      var self = this;
      const index = this.listData.findIndex(
        (item) => item.id == this.addressId
      );
      this.addressName = this.listData[index].siteAddress;

      this.siteId = this.listData[index].siteId
      console.log('siteId: ', this.siteId, index)
      this.listData[index].examUserApplySiteTime.forEach((item) => {
        item.examApplySiteTimeTwoVo.forEach((items) => {
          arrays.push({
            examTime: item.examTime,
            startTimeC: items.startTime,
            endTimeC: items.endTime,
            dataTime: self.$tools
              .timestampToTime(item.examTime)
              .replace(/-/g, "/"),
            startTime: items.startTime,
            endTime: items.endTime,
            num: items.num,
            registration: items.registration,
            checked: false,
            status:
              items.status === 1
                ? items.status
                : items.registration >= items.num
                ? 2
                : items.status,
          });
        });
      });
      this.timeIndex = "";
      this.activeList = arrays.filter((item, index) => {
        console.log(item);
        const newTime = parseInt(new Date().getTime() / 1000);
        console.log(
          item.dataTime.replace(/-/g, "/") + "" + item.startTime + ":00"
        );
        const liTime = parseInt(
          new Date(
            item.dataTime.replace(/-/g, "/") + "" + item.startTime + ":00"
          ).getTime() / 1000
        );
        console.log(liTime, "liTime");
        console.log(newTime, "newTime");
        if (liTime > newTime) {
          return item;
        }
      });

      console.log(this.activeList);
    },

    //获取考试地点
    getApplysubscribeApplySite() {
      this.$request
        .getApplysubscribeApplySite({ applyId: this.applyId })
        .then((res) => {
          res.data.forEach((item, index) => {
            item.checked = false;
          });
          this.listData = res.data;
        });
    },

    async sureOppoint() {
      if (this.isUploading) {
        // this.$message.warning('不要重复预约')
        return
      }
      this.isUploading = true

      var self = this;
      if (self.addressId) {
        if (this.timeIndex !== "") {
          if (this.reportStatus == 1) {
            await this.subCanvas()
            if (!this.commitment_electr_signature) {
              this.$message.warning('请签名')
              this.isUploading = false
              return
            } else {
              this.submits()
            }
          } else {
            this.submits()
          }
          
        } else {
          this.$message({
            type: "warning",
            message: "请选择考试时间",
          });
          this.isUploading = false
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择考试地点",
        });
        this.isUploading = false
      }
    },
    submits() {
      this.subLoading = true
      var copyData = JSON.parse(JSON.stringify(this.activeList));
      const index = copyData.findIndex(
        (item, index) => this.timeIndex == index
      );
      var data = {
        applyId: this.applyId,
        goodsId: this.goodsId,
        studentType: this.applyStatus,
        applySiteAddress: this.addressName,
        applySiteExamTime: copyData[index].examTime,
        applySiteStartTime: copyData[index].startTimeC,
        applySiteEndTime: copyData[index].endTimeC,
        orderGoodsId: this.orderGoodsId,
        siteId: this.siteId, // 考场id
      };
      if (this.reportStatus == 1) {
        data.signImageStr = this.commitment_electr_signature
      }
      console.log('---data', data)
      // return
      if (this.dataId == 1) {
        this.updateApplyData(data);
        this.$router.push({
          path: "/person-center/my-classhour/appointment-add-kp",
          query: {
            applyId: this.applyId,
            applyStatus: this.applyStatus,
            goodsId: this.goodsId,
            orderGoodsId: this.orderGoodsId,
          },
        });
        this.subLoading = false
      }
      if (this.dataId == 2) {
        this.$request.addApply(data).then((res) => {
          console.log('sfhsdfu成功', res)
          if (res.code == 200) {
            this.showDetailModal = true;
          } else {
            this.$message.warning(res.msg || '预约失败，请重新预约')
          }
          this.subLoading = false
        }).catch((err) => {
          this.subLoading = false
        })
      }

      this.isUploading = false
    },
    retDraw() {
      this.commitment_electr_signature = ''
      this.$nextTick(() => {
        this.$refs.esign.reset()
      })
    },
    subCanvas() {
      return new Promise((resolve, reject) => {
        if (this.commitment_electr_signature) {
          resolve();
          return;
        }
        console.log('this.$refs', this.$refs)
        this.$refs.esign
          .generate() // 使用生成器调用把签字的图片转换成为base64图片格式
          .then(async (res) => {
            console.log('base64:', res)
            this.commitment_electr_signature = res
            resolve();
          })
          .catch((err) => {
            console.log(err, "err");
            // 画布没有签字时会执行这里提示一下
            this.isUploading = false
            // this.$message({
            //   type: "warning",
            //   message: "请签名后再生成签字图片",
            // });
            resolve();
          });
      });
    },
    convertBase64UrlToBlob(urlData) {
      console.log('dsfsdg', urlData)
      var localData = urlData; //dataUrl为base64位
      let base = atob(localData.substring(localData.indexOf(",") + 1)); // base是将base64编码解码，去掉data:image/png;base64部分
      console.log('base', base)
      let length = base.length;
      let url = new Uint8Array(length);
      while (length--) {
        url[length] = base.charCodeAt(length);
      }
      let file = new File([url], "a.jpg", {
        type: "image/jpg",
      });
      console.log('file',file)
      //最后将file，通过ajax请求做为参数传给服务器就可以了
      return file;
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.appointment-add {
  overflow: hidden;
  &__header {
    border-bottom: 1px solid #eee;
    margin-top: 24px;
    padding-bottom: 20px;
  }
  &__body {
    .appointment-content {
      &__header {
        margin-top: 20px;
        width: 1110px;
        padding: 10px 12px;
        background: #fafbfc;
        border: 1px solid #eeeeee;
        box-shadow: 0px 0px 7px 1px rgba(0, 0, 0, 0.04);
        border-radius: 8px;

        .select {
          width: 1000px;
        }

        .total {
          margin-top: 10px;
          margin-left: 80px;
          font-size: 14px;

          .note {
            color: #ff3b30;
          }
        }
      }

      &__body {
        margin-top: 20px;
        width: 1110px;
        padding: 10px 12px;
        background: #fafbfc;
        border: 1px solid #eeeeee;
        box-shadow: 0px 0px 7px 1px rgba(0, 0, 0, 0.04);
        border-radius: 8px;

        .el-select {
          width: 300px;
        }
      }

      &__footer {
        margin-top: 20px;
        padding-bottom: 40px;

        .appointment-price {
          border-top: 1px solid #eee;
          border-bottom: 1px solid #eee;
          line-height: 50px;
          font-size: 18px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #333333;
          .note {
            font-size: 18px;
            color: #ff3b30;
            font-weight: bold;
            margin-left: 10px;
          }
        }

        .btns {
          margin-top: 20px;
          .cancel {
            display: inline-block;
            margin: 0 10px;
            cursor: pointer;
            width: 122px;
            height: 32px;
            background: #ffffff;
            border: 1px solid #3f8dfd;
            border-radius: 16px;
            text-align: center;
            font-size: 16px;
            line-height: 30px;
            color: #3f8dfd;
          }

          .ok {
            display: inline-block;
            margin: 0 10px;
            cursor: pointer;
            width: 122px;
            height: 32px;
            background: #3f8dfd;
            border-radius: 16px;
            color: #fff;
            text-align: center;
            line-height: 32px;
            font-size: 16px;
          }
        }
      }
    }
  }

  .appointment-modal {
    /deep/ .el-dialog__header {
      display: none;
    }
    /deep/ .el-dialog__body {
      padding: 0;
      overflow: unset;
    }

    &__close {
      cursor: pointer;
      position: absolute;
      right: 0;
      top: 0;
      width: 24px;
      height: 24px;
      line-height: 24px;
      text-align: center;
      color: #999999;
    }

    &__header {
      height: 40px;
      line-height: 40px;
      font-size: 16px;
      font-family: Microsoft YaHei;
      font-weight: bold;
      color: #333333;
      padding-left: 24px;
    }

    &__body {
      height: 200px;
      padding: 0 24px;

      .content {
        &__body {
          .icon-text {
            .icon {
              margin: 0 auto;
              border-radius: 50%;
              width: 64px;
              height: 64px;
              background: #34c759;
              text-align: center;
              line-height: 64px;
              font-size: 50px;
              color: #fff;
              font-weight: bold;
            }

            .text {
              font-size: 14px;
              font-family: Microsoft YaHei;
              font-weight: bold;
              color: #666666;
              text-align: center;
              margin-top: 15px;
            }
          }
          .confirm {
            margin: 35px auto 0;
            cursor: pointer;
            width: 96px;
            height: 40px;
            background: #3f8dfd;
            border-radius: 4px;
            text-align: center;
            line-height: 40px;
            color: #fff;
          }
        }
      }
    }
  }
  .commitment {
    width: 100%;
    height: 300px;
    overflow-y: auto;
    border: 1px solid #ddd;
  }
  .handCenter {
    width: 600px;
    height: 300px;
    background-color: #DCDFE6;
    border: 1px solid #DCDFE6;
  }
}
</style>
