<template>
  <div class="main_box">
    <navbar title="打卡签到"></navbar>
    <van-loading
      v-if="loading"
      class="fullscren"
      type="spinner"
      size="24px"
      vertical
      >加载中...</van-loading
    >
    <div class="wrapper" v-if="!loading">
      <div class="wapper_top">
        <div class="top_line_one">
          <div
            :class="
              baseInfo.custGender == '男' ? 'userMan_box' : 'userWoMan_box'
            "
            v-if="custType == '0'"
          >
            <van-icon name="manager item_user"></van-icon>
          </div>
          <div class="icon_box" v-if="custType == '1'">
            <img
              src="../../images/home/sh.png"
              alt=""
              style="width: 30px; height: 30px"
            />
          </div>
          <div class="userMan_box" v-if="custType == '2'">
            <img src="../../images/part_one/icon_company.png" alt="" />
          </div>
          <div class="item_name">
            <div>{{ baseInfo.custName }}</div>
            <div class="top_line_two">
              <span>证件号：</span>
              <span v-if="custType == '0'">{{ baseInfo.custIdc }}</span>
              <span v-if="custType == '1' || custType == '2'">{{
                baseInfo.socialCreditCode
              }}</span>
            </div>
          </div>
        </div>
        <van-form>
          <van-field name="fileList" label="签到照片">
            <template #input>
              <van-uploader
                v-model="fileList"
                :max-count="5"
                multiple
              ></van-uploader>
            </template>
          </van-field>
          <van-field
            name="remark"
            label="备注"
          >
            <template #input>
              <van-field
                v-model="remark"
                rows="5"
                type="textarea"
                autosize
                style="border: 1px solid #ccc"
              ></van-field>          
            </template>
          </van-field>
        </van-form>
      </div>
      <div class="map_box">
        <div class="qd_btn" @click="handleSignIn">
          <div>签到</div>
          <div class="time">{{ nowDate }}</div>
        </div>
      </div>
    </div>
    <van-dialog v-model="show" title="跳转提示" message="请问是否跳转走访反馈进行填写" show-cancel-button @cancel="handleBack()" @confirm="handlePush()">
    </van-dialog>
  </div>
</template>
<script>
import navbar from "../../components/navbar/navbar.vue";
import { signIn, uploadImage, getImage, nonOnSitesignIn } from "@/service/api/visiting";
import { translateLocApi } from "@/service/api/myGrid.js";
import { debounce } from "lodash";
import {
  Tab,
  Icon,
  Button,
  Uploader,
  Toast,
  Loading,
  Image as VantImage,
  Form,
  Field,
  Dialog
} from "vant";
export default {
  data() {
    return {
      loading: false,
      baseInfo: {
        custName: "",
        custIdc: "",
      },
      fileList: [],
      headerFilesList: [],
      mapLoading: false,
      nowDate: "",
      timer: null,
      custType: "",
      campaignId: "",
      fileLists: [],
      imgList: [],
      remark: '',
      show: false,
      signData: []
    };
  },
  components: {
    navbar: navbar,
    VanTab: Tab,
    VanIcon: Icon,
    VanButton: Button,
    VanUploader: Uploader,
    VanToast: Toast,
    VanLoading: Loading,
    VanImage: VantImage,
    VanForm: Form,
    VanField: Field,
  },
  mounted() {
    let that = this;
    this.campaignId = sessionStorage.getItem("campaignId");
    this.custType = sessionStorage.getItem("custType");
    this.baseInfo = JSON.parse(sessionStorage.getItem("baseInfo"));
    this.getDate();
    this.timer = setInterval(this.getDate, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    handleChangeImage() {
      const compressList2 = [];
      this.headerFilesList.forEach(async (item) => {
        compressList2.push(this.compressImage(item));
      });

      Promise.all(compressList2).then((res) => {
        const data = new FormData();
        data.append("custId", this.baseInfo.custId);

        res.forEach((file, index) => {
          data.append("imageList", file);
        });

        uploadImage(data).then((res) => {
          if (res.code === 200) {
            Toast.success('修改成功')
            // this.getCommericalImage()
          }
        })
      });
    },
    getDate() {
      const now = new Date();
      const timeStr = now.toLocaleTimeString();
      this.nowDate = timeStr;
    },
    formatDate(date) {
      if (date.getMonth() + 1 < 10) {
        return `${date.getYear() + 1900}-0${
          date.getMonth() + 1
        }-${date.getDate()}`;
      } else {
        return `${date.getYear() + 1900}-${
          date.getMonth() + 1
        }-${date.getDate()}`;
      }
    },
    async handleSignIn() {
      this.loading = true;

      const compressList1 = [];
      this.fileList.forEach(async (item) => {
        compressList1.push(this.compressImage(item));
      });

      Promise.all(compressList1).then((res) => {
        const data = new FormData();
        res.forEach((item, index) => {
          data.append(`imageList[${index}]`, item);
        });
        const now = new Date();
        let signDate = this.formatDate(now);

        if (this.baseInfo.recordId) {
          data.append("recordId", this.baseInfo.recordId);
        }
        data.append("campaignId", this.campaignId);
        if (this.campaignId === '-1') {
          data.append("custType", this.baseInfo.custType)
          data.append("appointmentId", this.baseInfo.appointmentId || '-1')
        }
        data.append("custId", this.baseInfo.custId);
        data.append("custName", this.baseInfo.custName);
        data.append("signInTime", signDate + " " + this.nowDate);
        data.append("signOutRemark", this.remark);
        nonOnSitesignIn(data).then((res) => {
          this.loading = false;
          this.signData = res.data
          if (res.code == 200) {
            Toast.success(res.msg);
            this.show = true
            // this.$router.push("/visitingTaskDetails");
          }
        });
      });

      // this.fileList.forEach((item) => {
      //   let file = item.file;
      //   let type = file.type.split("/")[0];
      //   if (type != "image") {
      //     Toast("请上传jpg/png/jpeg格式的图片！");
      //     return;
      //   }
      //   let reader = new FileReader();
      //   reader.readAsDataURL(file);
      //   reader.onload = (e) => {
      //     if (file.size / 1024 / 1024 < 0.3) {
      //       this.fileLists.push(reader.result);
      //     } else {
      //       let scaleNum = 1;
      //       if (file.size / 1024 / 1024 < 1) {
      //         scaleNum = 3;
      //       } else if (
      //         file.size / 1024 / 1024 > 1 &&
      //         file.size / 1024 / 1024 < 2
      //       ) {
      //         scaleNum = 8;
      //       } else {
      //         scaleNum = 10;
      //       }
      //       const img = new Image();
      //       img.src = e.target.result;
      //       img.onload = () => {
      //         const canvas = document.createElement("canvas");
      //         const ctx = canvas.getContext("2d");
      //         canvas.width = img.width / scaleNum;
      //         canvas.height = img.height / scaleNum;
      //         ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      //         this.fileLists.push(canvas.toDataURL("image/png", 0.5));
      //       };
      //     }
      //   };
      // });
    },
    handlePush() {
        if (this.signData.feedbackType === "2") 
          {
            this.$router.push({
              path: "/customVisit",
              query: {
                feedbackId: this.signData.feedbackId,
                feedbackTemplateId: this.signData.feedbackTemplateId,
                recordId: this.signData.recordId,
              },
            });
        } else {
          let visitType = sessionStorage.getItem("visitType");
          this.baseInfo.recordId = this.signData.recordId
          this.baseInfo.feedbackId = this.signData.feedbackId
          this.baseInfo.feedbackTemplateId = this.signData.feedbackTemplateId
          this.baseInfo.feedbackType = this.signData.feedbackType
          sessionStorage.setItem("baseInfo", JSON.stringify(this.baseInfo))
          //预约走访任务特殊处理
          if(this.campaignId == "-1"){
            if(this.baseInfo.custType == 0){
              visitType="个人走访"
            }else{
              visitType="商户走访"
            }
          }
          if (visitType == "催收走访") {
            this.$router.push("/collectionVisit");
          } else if (visitType == "个人走访") {
            this.$router.push("/personalVisit");
          } else if (
            visitType == "商户走访" ||
            visitType == "域外商会走访" ||
            visitType == "收单商户走访" ||
            visitType == "企业走访"
          ) {
            this.$router.push("/firmVisit");
          }
        }
      },
      handleBack() {
        this.$router.push("/visitingTaskDetails");
      },
    compressImage(image) {
      return new Promise((resolve) => {
        const file = image.file;
        const type = file.type.split("/")[0];
        if (type != "image") {
          Toast("请上传jpg/png/jpeg格式的图片！");
          return;
        }
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          if (file.size / 1024 / 1024 < 0.2) {
            resolve(this.base64ToFile(reader.result, file.name || "image.png"));
          } else {
            let scaleNum = 1;
            if (file.size / 1024 / 1024 < 1) {
              scaleNum = 3;
            } else if (
              file.size / 1024 / 1024 > 1 &&
              file.size / 1024 / 1024 < 2
            ) {
              scaleNum = 8;
            } else {
              scaleNum = 10;
            }
            const img = new Image();
            img.src = e.target.result;
            img.onload = () => {
              const canvas = document.createElement("canvas");
              const ctx = canvas.getContext("2d");
              canvas.width = img.width / scaleNum;
              canvas.height = img.height / scaleNum;
              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
              resolve(
                this.base64ToFile(
                  canvas.toDataURL("image/png", 0.5),
                  file.name || "image.png"
                )
              );
            };
          }
        };
      });
    },
    base64ToFile(base64String, filename) {
      console.log(1111);
      const arr = base64String.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
  },
};
</script>
<style lang="less" scoped>
.wrapper {
  padding-top: 46px;
  min-height: 100vh;
  font-size: 16px;
  padding-bottom: 60px;
  background-color: #fff;
}

.wapper_top {
  padding: 15px;
}

.top_line_one {
  display: flex;
  justify-content: flex-start;
  align-items: start;
}

.item_name {
  font-size: 18px;
  font-weight: 600;
  margin-left: 10px;
  flex-wrap: wrap;
  word-break: break-all;
}

.userMan_box {
  background-color: rgb(35, 114, 235);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px 5px;
}

.userWoMan_box {
  background-color: rgb(252, 123, 80);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 5px 5px;
}

.item_user {
  font-size: 20px;
  color: #fff;
}

.top_line_two {
  font-size: 12px;
  color: rgb(140, 140, 140);
  margin-top: 10px;
}

::v-deep .van-cell {
  padding: 10px 0;
}

/deep/ .van-uploader__upload-icon {
  color: rgb(35, 114, 235);
}

/deep/ .van-uploader__upload {
  background-color: rgb(236, 242, 255);
}

.upDiv {
  margin-top: 15px;
}

.map {
  width: 100%;
  height: 400px;
}

.map_box {
  position: relative;

  .right-icon-box {
    position: absolute;
    right: 0;
    top: 300px;
    z-index: 300;
    div {
      width: 40px;
      height: 40px;
      // background: #fff;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      &:last-child {
        margin-top: 20px;
      }
      .img {
        background: #fff;
        border-radius: 4px;
        padding: 5px;
      }
    }
  }
}

.qd_btn {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: rgb(35, 114, 235);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  position: absolute;
  top: 340px;
  left: 34%;
  z-index: 999;
}

.time {
  margin-top: 10px;
  font-size: 12px;
}

.footer {
  margin-top: 80px;
  text-align: center;
  font-size: 12px;
  color: rgb(140, 140, 140);
}

.dw {
  margin-top: 10px;
  color: rgb(35, 114, 235);
}

.fullscren {
  padding-top: 200px;
}
</style>
