<template>
  <div class="main_box">
    <div class="wrapper">
      <div style="padding:20px;">
        <van-uploader
            v-model="fileList"
            :after-read="afterRead"
            :max-count="5"
            multiple
          ></van-uploader>
      </div>
      <div class="map_box">
        <div ref="mapContainer" class="map"></div>
        <div class="right-icon-box">
          <div @click="handleResetLocation">
            <van-image :src="focus_img" class="img" />
          </div>
        </div>
        <div class="qd_btn" @click="handleCxdw">
          <div>定位</div>
        </div>
        <div class="footer">
          <div>{{ nowAdress }}</div>
          <div>{{ `经度：${location.lng}, 纬度：${location.lat}` }}</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import navbar from "../../components/navbar/navbar.vue";
import { getTargetSign, signOut } from "@/service/api/visiting";
import { translateLocApi } from "@/service/api/myGrid.js";
import { debounce } from "lodash";
import { Tab, Icon, Button, Uploader, Field, Toast, Loading, Image, Form } from "vant";
import { custLeadAdd } from "@/service/api/filing";
export default {
  data() {
    return {
      focus_img: require("@/images/map/focus@3x.png"),
      loading: false,
      baseInfo: {},
      fileList: [],
      mapLoading: false,
      location: {
        lat: 30.248307,
        lng: 120.25551,
      },
      nowDate: "",
      timer: null,
      nowAdress: "浙江省杭州市萧山区风情大道XXX大厦",
      custType: "",
      signInfo: {
        signInAddress: "",
        signInTime: "",
        signOutAddress: "",
        signOutRemark: "",
        signOutTime: "",
      },
      remark: "",
      fileLists: [],
      baseform:{
        custType:"1",
        custName:"",
        address:"",
        lng:"",
        lat:"",
      }
    };
  },
  components: {
    navbar: navbar,
    VanTab: Tab,
    VanIcon: Icon,
    VanButton: Button,
    VanUploader: Uploader,
    VanField: Field,
    VanToast: Toast,
    VanLoading: Loading,
    VanImage: Image,
    VanForm: Form,
    VanField: Field,
  },
  mounted() {
    let that = this;
    if (window.wx) {
      wx.ready(() => {
        wx.getLocation({
          type: "gcj02",
          success: (res) => {
            console.log("1111");
            that.translateLocation({
              lat: res.latitude,
              lng: res.longitude,
            });
          },
          fail: (err) => {
            console.error("错误码：", err);
          },
        });
      });
    } else {
      this.initMap();
    }
    // this.custType = sessionStorage.getItem("custType");
    // this.baseInfo = JSON.parse(sessionStorage.getItem("baseInfo"));
    // this.getDate();
    // this.initTargetSign();
    // this.timer = setInterval(this.getDate, 1000);
  },
  // beforeDestroy() {
  //   clearInterval(this.timer);
  // },
  methods: {
    async translateLocation(params) {
      const res = await translateLocApi(params);
      console.log("2222");
      if (res.code == 200) {
        this.location = {
          lat: res?.data[1],
          lng: res?.data[0],
        };
        this.initMap();
      }
    },
    // initTargetSign() {
    //   let recordId = this.baseInfo.recordId;
    //   getTargetSign(recordId).then((res) => {
    //     if (res.code == 200) {
    //       this.signInfo = res.data;
    //     }
    //   });
    // },
    // 初始化地图
    initMap() {
      this.mapLoading = true;
      this.map = new BMapGL.Map(this.$refs.mapContainer);
      this.map.centerAndZoom(this.location, 15);
      this.addMarker(this.location)
      this.map.enableScrollWheelZoom();
      let myGeo = new BMapGL.Geocoder();
      myGeo.getLocation(
        new BMapGL.Point(this.location.lng, this.location.lat),
        (res) => {
          console.log(res, "ressssssssss");
          if (res) {
            this.nowAdress = res.address;
            this.baseform.address=this.nowAdress;
            this.$emit("callFn",res.address)
          }
        }
      );
      this.mapLoading = false;
    },
    addMarker(point) {
      this.map.clearOverlays();
      const marker = new BMapGL.Marker(point);
      // 在地图上添加点标记
      this.map.addOverlay(marker);
    },
    handleResetLocation() {
      this.map.centerAndZoom(this.location, 15);
    },
    handleCxdw() {
      let that = this;
      wx.ready(() => {
        wx.getLocation({
          type: "gcj02",
          success: (res) => {
            that.translateLocation({
              lat: res.latitude,
              lng: res.longitude,
            });
          },
          fail: (err) => {
            console.error("错误码：", err);
          },
        });
      });
    },
    afterRead(flies, detail) {},
    // 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()}`;
    //   }
    // },
    handleAddCancle(){
      this.$router.go(-1);
    },
    handleAddSave(){
      this.$refs.form.validate().then(() => {
        this.handleSingOut();
      })
    },
    handleSingOut() {
      this.loading = true;
      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));
            };
          }
        };
      });
      setTimeout(() => {
        let imgList = [];
        this.fileLists.forEach((item) => {
          imgList.push(this.base64ToFile(item, "image.png"));
        });
        const data = new FormData();
        imgList.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);
        // }
        // if (this.baseInfo.appointmentId) {
        //   data.append("appointmentId", this.baseInfo.appointmentId || '-1');
        // }
        // data.append("signOutAddress", this.nowAdress);
        // data.append("signOutTime", signDate + " " + this.nowDate);
        // data.append("signOutLat", this.location.lat);
        // data.append("signOutLng", this.location.lng);
        // data.append("signOutRemark", this.remark);
        data.append("custType", "1");
        data.append("custName", this.baseform.custName);
        data.append("address", this.baseform.address);
        data.append("lng", this.location.lng);
        data.append("lat", this.location.lat);
        custLeadAdd(data).then((res) => {
          if (res.code == 200) {
            this.loading = false;
            Toast.success("新增成功！");
            this.$router.push("/filingqkHome");
          }
        });
      }, 1000);
    },
    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 });
    },
    getDataFn(){
      return {
        fileList:this.fileList,
        location:this.location
      }
    }
  },
};
</script>
<style lang="less" scoped>
.wrapper {
  padding-top: 20px;
  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;
}

/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: 300px;
}

.map_box {
  position: relative;

  .right-icon-box {
    position: absolute;
    right: 0;
    top: 200px;
    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: 240px;
  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);
}

.qdls_box {
  border-top: 2px solid rgb(238, 238, 238);
  padding: 15px;
}

.qdls_one {
  display: flex;
  align-items: center;
}

.yuan {
  width: 10px;
  height: 10px;
  background-color: rgb(140, 140, 140);
  border-radius: 50%;
}

.dkqd {
  margin-left: 8px;
  font-weight: 600;
}

.qdsj {
  color: rgb(140, 140, 140);
}

.qdls_two {
  color: rgb(140, 140, 140);
  padding: 10px 19px;
  display: flex;
  font-size: 14px;
}

.qtls_one {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.qtsm {
  color: rgb(140, 140, 140);
  padding: 0 19px;
  display: flex;
  font-size: 14px;
}

.title {
  font-family: 600;
}

.qtsm_box {
  padding: 15px;

  /deep/ .van-cell {
    background-color: rgb(249, 249, 250);
    padding: 10px 0;
    margin-top: 10px;
  }
}

.footer_box {
  padding: 15px;
  color: rgb(140, 140, 140);
}

.footer_box_line {
  line-height: 30px;
}

.fullscren {
  padding-top: 200px;
}

.addFormBtn {
    margin-top: 50px;
    display: flex;
    justify-content: space-between;
    padding: 0 10px;

    /deep/ .van-button {
        width: 48%;
    }
}
</style>
