<template>
  <view class="safeAreas">
    <nav-bar title="预约考试"></nav-bar>
    <view class="appointment">
      <view class="appointmentItem">
        <view class="title">考试地点：</view>
        <view class="place" @click="showAddress">
          <view class="name">{{ addressName }}</view>
          <view
            ><u-icon name="arrow-right" color="#999999" size="28"></u-icon
          ></view>
        </view>
      </view>
      <view class="appointmentItem" v-if="activeList.length">
        <view class="title">考试时间：</view>
        <view class="main">
          <view
            v-for="(item, index) in activeList"
            class="item"
            :key="index"
            @click="choItem(index)"
          >
            <view class="checkbox"
              ><u-checkbox
                v-if="item.status === 0"
                v-model="item.checked"
                shape="circle"
              ></u-checkbox
            ></view>
            <view class="box">
              <view
                :class="[
                  'time',
                  { active: item.checked },
                  { no: item.status !== 0 },
                ]"
                >{{
                  item.dataTime + " " + item.startTime + " ~ " + item.endTime
                }}</view
              >
              <view class="statusInfo" v-if="item.status !== 0">
                <template v-if="item.status === 2"> 预约名额已满 </template>
                <template v-if="item.status === 1">
                  此时段您已经有其他考试预约
                </template>
              </view>
            </view>
            <view class="num"
              >已报：{{ item.registration }}/{{ item.num }}</view
            >
          </view>
        </view>
      </view>
      <view v-else class="appointmentItem">
        <view class="title">
          <text v-if="addressName && addressName != '请选择'">
            该考试地点暂无考试时间，建议重新选择考试地点
          </text>
          <!-- <text v-else>
						当前考培地点无考前培训时间点
					</text> -->
        </view>
      </view>
      <!-- 考试疫情承诺书 -->
      <view class="appointmentItem">
        <view class="title"><text class="star_red">*</text> 考试疫情承诺书</view>
        <view class="commitment">
          本人参加“住房和城乡建设领域施工现场专业人员岗位”考试，愿意遵守疫情防控各项管理的相关要求，秉承对自己、对他人负责的原则，承担疫情防控社会责任，郑重作出以下承诺：<br/>
          一、充分理解并遵守考试期间考点各项防疫安全的要求。<br/>
          二、在考试前14天内，没有到过国内疫情中风险、高风险地区，未出境，不存在自境外回国情形。<br/>
          三、在考试前14天内，每日自觉监测体温，体温均未出现高于37.3度的情形，无发热和呼吸道门诊就诊史。<br/>
          四、在考试前14天内，未和新冠肺炎病例或疑似病例密切接触或间接接触，没有发烧、干咳、乏力、咳痰、气短、肌肉痛或关节痛、咽喉痛、头痛、寒颤、恶心或呕吐、鼻塞、腹泻、咳血、结膜充血等疑似新冠肺炎症状。<br/>
          五、如出现与前述第二、三、四项任何一项不符的情形之一的，本人将及时在考前向相关管理机构报告，自觉配合采取隔离或其他防疫措施，并根据情况，自愿放弃参加考试。<br/>
          六、考试当日自行做好防护工作，佩戴防护口罩。提前抵达考点，配合查验健康码、测量体温等。<br/>
          七、考试期间，将严格遵守应考人员考场守则及疫情防控相关管理要求，完成考试后立即离场，不扎堆，不聚集。<br/>
          八、本人承诺遵守《应考人员安全承诺书》中所有承诺内容，若因有瞒报、谎报造成新冠肺炎疫情传播的，一经查实，由本人承担相应的法律和经济责任。
        </view>
      </view>
      <view class="appointmentItem">
        <view class="title"><text class="star_red">*</text>签名板</view>
        <view class="dis_stys">
          <text style="color: #999999">请在下方签名区进行签名</text>
          <text @click="retDraw" mode="">清空</text>
        </view>
        <view class="handCenter">
           <!-- v-if="!form[item.fieldKey]" -->
          <canvas
            class="handWriting"
            disable-scroll="true"
            :catchtouchmove="true"
            @touchstart="uploadScaleStart"
            @touchmove="uploadScaleMove"
            @touchend="uploadScaleEnd"
            canvas-id="handWriting"
          ></canvas>
          <!-- <view
            v-else
            style="width: 100%; height: 100%; position: relative"
          >
            <view class="ctoples">图片</view>
            <image
              style="width: 100%; height: 100%"
              :src="$method.splitImgHost(form[item.fieldKey])"
              mode=""
            ></image>
          </view> -->
        </view>
      </view>
      <view class="btnMain">
        <view class="return" @click="backPage">上一步</view>
        <view class="sure" @click="sureOppoint">{{
          dataId === 1 ? "下一步" : dataId === 2 ? "确定预约" : "异常"
        }}</view>
      </view>
    </view>
    <!-- 弹框-->
    <u-popup v-model="address_show" mode="bottom" class="addModel">
      <view class="tipBox safeArea">
        <view class="line"></view>
        <view class="title">温馨提示</view>
        <u-line color="#EEEEEE" />
        <scroll-view class="addressList" :scroll-y="true">
          <view
            class="item"
            v-for="(item, index) in listData"
            :key="index"
            @click="choAddress(item, index)"
          >
            <u-checkbox
              class="checkbox"
              v-model="item.checked"
              shape="circle"
            ></u-checkbox>
            <view :class="['address', { active: item.checked }]">{{
              item.siteAddress
            }}</view>
          </view>
        </scroll-view>
        <u-line color="#EEEEEE" />
        <view class="btn" @click="sureAddress">确认</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import Handwriting from "@/common/signature.js";
export default {
  data() {
    return {
      orderGoodsId: 0,
      address_show: false,
      addressName: "请选择",
      addressId: null, //当前选中考试点ID
      listData: [], //考试地点数据
      activeList: [], //选中考试地点列表
      applyId: null, //考试计划ID
      goodsId: null, //商品ID
      applyStatus: null, //学员状态ID
      sysTime: 0,
      dataId: null, //跳转拷贝
      handwriting: '',
      lineColor: "black",
      slideValue: 30,
      openVerify: false, // 控制是否手动验证
      commitment_electr_signature: '',
      isUploading: false,
      siteId: '', // 考试id
      reportStatus: 0, // 是否线上签署疫情防控承诺书， 1是，0否
      baseAddress: '', // 签名转成base64
    };
  },
  async onLoad(option) {
    this.applyId = Number(option.applyId);
    this.goodsId = Number(option.goodsId);
    this.applyStatus = Number(option.applyStatus);
    this.dataId = Number(option.dataId);
    this.orderGoodsId = Number(option.orderGoodsId);
    this.reportStatus = option.reportStatus
    await this.commonSystemTime();
    this.getInfo();
  },
  onReady(res) {
    this.handwriting = new Handwriting({
      lineColor: this.lineColor,
      slideValue: this.slideValue, // 0, 25, 50, 75, 100
      canvasName: "handWriting",
    });
    // this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    commonSystemTime() {
      return new Promise((resolve) => {
        this.$api.commonSystemTime().then((res) => {
          this.sysTime = res.data.data;

          resolve();
        });
      });
    },
    //获取考试地点
    getInfo() {
      // apply/subscribeApplySite
      this.$api
        .getApplysubscribeApplySite({ applyId: this.applyId })
        .then((res) => {
          if (res.data.code === 200) {
            res.data.data.forEach((item, index) => {
              item.checked = false;
            });
            this.listData = res.data.data;
            console.log('this.listData:', this.listData)
          }
        });
    },
    showAddress() {
      this.address_show = true;
    },
    choAddress(item, index) {
      this.siteId = item.siteId
      this.listData.forEach((item, idx) => {
        this.$set(item, "checked", false);
        if (idx === index) {
          this.$set(item, "checked", true);
        }
      });
    },
    sureAddress() {
      var self = this;
      const index = this.listData.findIndex((item) => item.checked);
      if (index === -1) {
        uni.showToast({
          title: "请选择考试地点",
          icon: "none",
        });
        return;
      }
      this.siteId = this.listData[index].siteId
      console.log('siteId: ', this.siteId, index)
      if (this.addressId === this.listData[index].id) {
        this.address_show = false;
        return;
      }
      this.addressName = this.listData[index].siteAddress;
      console.log('addressName', this.addressName, this.listData)
      this.addressId = this.listData[index].id;
      var arrays = [];
      this.listData[index].examUserApplySiteTime.forEach((item) => {
        item.examApplySiteTimeTwoVo.forEach((items) => {
          arrays.push({
            examTime: item.examTime,
            startTimeC: items.startTime,
            endTimeC: items.endTime,
            dataTime: self.$method
              .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,
          });
        });
      });
      console.log('arrays', arrays)
      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(this.sysTime, "newTime");
        if (liTime > this.sysTime) {
          return item;
        }
      });

      console.log('----',this.activeList);
      this.address_show = false;
    },
    choItem(index) {
      const item = this.activeList[index];
      if (item.status !== 0) {
        return;
      }
      this.activeList.forEach((item, idx) => {
        item.checked = false;
        if (idx === index) {
          item.checked = true;
        }
      });
    },
    async sureOppoint() {
      if (this.isUploading) {
        return;
      }
      this.isUploading = true

      var self = this;
      if (self.addressId) {
        var ast = self.activeList.some((item) => {
          return item.checked === true;
        });
        console.log('ast',this.activeList, ast)
        if (ast) {
          if (this.reportStatus == 1) {
            await this.subCanvas()
            if (!this.commitment_electr_signature) {
              uni.showToast({
                title: "请签名",
                icon: "none",
              })
              return
            } else {
              // await this.submitApi()
              if (this.commitment_electr_signature) {
                uni.request({
                  url: this.commitment_electr_signature, //临时路径
                  responseType: 'arraybuffer', //设置返回的数据格式为arraybuffer
                  success: res => {
                    const base64 = "data:image/png;base64," + uni.arrayBufferToBase64(res.data)
                    console.log('sfs签名转成base64', base64)
                    this.baseAddress = base64
                    this.submits()
                  },
                  fail: err => {
                    console.log(err)
                  }
                })
              }
            }
          } else {
            this.submits()
          }
          
          
        } else {
          uni.showToast({
            title: "请选择考试时间",
            icon: "none",
          });
          this.isUploading = false
        }
      } else {
        uni.showToast({
          title: "请选择考试地点",
          icon: "none",
        });
        this.isUploading = false
      }
    },
    submits() {
      var copyData = JSON.parse(JSON.stringify(this.activeList));
      const index = copyData.findIndex((item) => item.checked);
      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.baseAddress
      }
      console.log('-----data', data, this.dataId)
      // return
      if (this.dataId === 1) {
        this.$store.commit("updateApplyData", data);
        this.$navTo.togo("/pages2/appointment/kporder", {
          applyId: this.applyId,
          applyStatus: this.applyStatus,
          goodsId: this.goodsId,
          orderGoodsId: this.orderGoodsId,
        });
      }
      if (this.dataId === 2) {
        this.$api.addApply(data).then((res) => {
          if (res.data.code === 200) {
            uni.reLaunch({
              url: `/pages2/appointment/appointment_success?subscribeId=${res.data.data}`,
            });
          } else {
            uni.showToast({
              icon: "none",
              title: res.data.msg,
            });
          }
        });
      }
      this.isUploading = false
    },
    backPage() {
      uni.navigateBack({
        delta: 1,
      });
    },
    retDraw() {
      this.handwriting.retDraw()
      this.commitment_electr_signature = ''
      // this.$set(this.form, "commitment_electr_signature", "");
      this.openVerify = false;
    },
    uploadScaleStart(event) {
      this.handwriting.uploadScaleStart(event);
    },
    uploadScaleMove(event) {
      this.handwriting.uploadScaleMove(event);
    },
    uploadScaleEnd(event) {
      this.handwriting.uploadScaleEnd(event);
    },
    async subCanvas() {
      console.log("签名-------");
      return new Promise((resolve, reject) => {
        if (this.commitment_electr_signature) {
          resolve();
          return;
        }
        this.handwriting.saveCanvas().then((res) => {
            if (this.handwriting.linePrack.length) {
              console.log('签名-----res', res)
              // this.$set(this.form, "commitment_electr_signature", res);
              this.commitment_electr_signature = res
            }
            resolve(res)
          })
          .catch((err) => {
            uni.showToast({
              title: "签名上传失败",
              icon: "error",
            });

          });
          this.isUploading = false
      });
    },
     //提交表单
    async submitApi() {
      if (this.commitment_electr_signature) {
        // this.commitment_electr_signature = await this.$method.uploadFile(
        //   this.commitment_electr_signature,
        //   0
        // );
         var res = await uni.request({
          url: this.commitment_electr_signature, //临时路径
          responseType: 'arraybuffer', //设置返回的数据格式为arraybuffer
          success: res => {
            const base64 = "data:image/png;base64," + uni.arrayBufferToBase64(res.data)
            console.log('sfs签名转成base64', base64)
            this.baseAddress = base64
          }
        })
        console.log('----commitment_electr_signature',res, this.commitment_electr_signature)
      }

    },
  },
};
</script>
<style>
page {
  background-color: #eaeef1;
}
.addModel .u-drawer-bottom {
  box-shadow: 0px 0px 16px 4px rgba(145, 156, 178, 0.1);
  border-radius: 32rpx 32rpx 0px 0px;
}
</style>
<style scoped lang="scss">
  .safeAreas {
    padding-bottom: 30rpx;
  }
.appointment {
  padding: 0 8rpx;
  .appointmentItem {
    margin: 24rpx 0 40rpx;
    .title {
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 1;
      margin-bottom: 16rpx;
      padding-left: 24rpx;
      .star_red {
        color: red;
      }
    }
    .place {
      height: 80rpx;
      background: #ffffff;
      border-radius: 16rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 24rpx;
    }
    .commitment {
      padding: 12rpx;
      height: 300rpx;
      background: #ffffff;
      overflow-y: auto;
    }
    .handCenter, .dis_stys, .commitment {
      margin: 0rpx 24rpx;
    }
    .dis_stys {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16rpx;
    }
    .handCenter {
      .handWriting {
        width: 100%;
        height: 400rpx;
        background: #fff;
      }
    }
  }
  .main {
    background: #ffffff;
    border-radius: 16rpx;
    padding: 32rpx 16rpx;
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
      .statusInfo {
        font-size: 24rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #ff3b30;
        padding-left: 24rpx;
      }
      .checkbox {
        width: 32rpx;
        height: 32rpx;
        display: flex;
        align-items: center;
      }
      .time {
        width: 430rpx;
        height: 80rpx;
        line-height: 80rpx;
        background: #f5f5f5;
        border: 2rpx solid #f5f5f5;
        border-radius: 16rpx;
        font-size: 30rpx;
        font-family: PingFang SC;
        font-weight: bold;
        text-align: center;
        color: #333333;
        margin: 0 18rpx 0 8rpx;
        &.active {
          background: #ebf5ff;
          border: 2rpx solid #007aff;
        }
        &.no {
          background: #ffdddb;
          border: 2rpx solid #ffdddb;
        }
      }
    }
  }
  .btnMain {
    display: flex;
    justify-content: center;
    text-align: center;
    .return {
      width: 200rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: #f5f5f5;
      border-radius: 40rpx;
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: bold;
      color: #007aff;
    }
    .sure {
      width: 438rpx;
      height: 80rpx;
      line-height: 80rpx;
      background: #007aff;
      border-radius: 40rpx;
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: bold;
      color: #ffffff;
      margin-left: 24rpx;
    }
  }
}
.tipBox {
  width: 100%;
  font-family: PingFang SC;
  .line {
    width: 80rpx;
    height: 8rpx;
    background: #999999;
    border-radius: 4rpx;
    margin: 8rpx auto;
  }
  .title {
    text-align: center;
    font-size: 24rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #999999;
    margin: 15rpx 0;
  }
  .main {
    font-size: 30rpx;
    font-weight: 500;
    color: #666666;
    line-height: 48rpx;
    margin-bottom: 40rpx;
  }
  .addressList {
    height: 500rpx;
    padding-top: 24rpx;
    .item {
      display: flex;
      align-items: center;
      padding: 0 24rpx;
      margin-bottom: 24rpx;
      .checkbox {
        width: 32rpx;
        height: 32rpx;
        display: flex;
        align-items: center;
        margin-right: 8rpx;
      }
      .address {
        width: 654rpx;
        height: 80rpx;
        line-height: 80rpx;
        background: #f5f5f5;
        border-radius: 16rpx;
        font-size: 30rpx;
        font-family: PingFang SC;
        font-weight: bold;
        color: #333333;
        padding: 0 24rpx;
        &.active {
          background: #ebf5ff;
          border: 2rpx solid #007aff;
        }
      }
    }
  }
  .btn {
    width: 200rpx;
    height: 64rpx;
    line-height: 64rpx;
    background: linear-gradient(0deg, #015eea, #00c0fa);
    border-radius: 32rpx;
    margin: 17rpx auto;
    font-size: 30rpx;
    font-family: PingFang SC;
    font-weight: 500;
    text-align: center;
    color: #ffffff;
  }
}
</style>
