<template>
  <div>
    <!--        顶部条-->
    <van-nav-bar
        class="navBar"
        title="拜访"
        left-arrow
        @click-left="onClickLeft"

    >
    </van-nav-bar>
    <!--        主体内容-->
    <div class="container">
      <div class="lineGrey"></div>
      <div class="card mt10">
        <div class="title f-blue">{{ storeName }}(<span style="color:#0057ba">{{ urlParameter.shopCode }}</span>)</div>
        <div class="info1">类型：{{ storeCategory }}</div>
        <div class="info1">地址：{{ addressLine }}</div>
        <div class="info1" v-if="hisTime==''||hisTime==undefined">上次拜访时间：{{ parseTime(hisTime) }}</div>
        <van-button type="info" style="background: rgb(0, 87, 186);color:#fff;  margin: 10px 0; border-radius: 5px;"
                    size="small" plain
                    class="centerBtn"
                    @click="visitFn(urlParameter.shopCode)">经营情况
        </van-button>
      </div>
      <div class="lineGrey"></div>
      <div class="card">
        <p style="text-align: center;">{{ msg }}</p>
      </div>
    </div>
    <br>
    <div id="allmap"></div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: "outstoreVisit",
  data() {
    return {
      visitModel: "1",
      storeId: "",
      rdId: "",
      lat: "",
      lon: "",
      cont: 0,
      list: [],
      storeGroupId: "",
      visitId: null,
      addressLine: "",
      storeCategory: "",
      storeName: "",
      contactName: "",
      shopCode: "",
      urlParameter: "",
      location: {
        lat: "34.6174",
        lon: "112.44039"
      },
      address: "",
      city: "",
      locationAccuracy: "",
      id: "89",
      closePag: true,
      msg: "",
      hisTime: ""
    }
  },
  created() {
    this.urlParameter = this.$route.query;
    this.storeId = this.$route.query.storeId + "";
    this.shopCode = this.$route.query.shopCode;
    this.addressLine = this.$route.query.addressLine + "";
    this.storeCategory = this.$route.query.storeCategory + "";
    this.storeName = this.$route.query.storeName + "";
    localStorage.setItem("visitModel", "1")
    setTimeout(() => {
      this.getLocation()
    })
  },
  methods: {
    // 定位
    getLocation() {
      this.visitId=this.$route.query.visitId
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      let url = window.location.href;
      let that = this;
      let wx = this.wx
      let qiyeData
      const instance = axios.create();
      instance.defaults.headers.common['userId'] = localStorage.getItem("loginName");
      instance.get(process.env.VUE_APP_BASE_API + 'mobile/wx/ticket',
          {
            params: {
              url: url,
              storeCode: that.shopCode
            }
          }).then(response => {
        if (response.status == 200) {
          var dataList = response.data
          if (dataList.code == 200) {
            this.cont = 3;
            var flat = true;
            var times = setInterval(() => {
              this.cont--
              if (this.cont == "0") {
                if (flat) {
                  loading1.clear()
                  clearInterval(times)
                  that.$dialog.alert({
                    message: '定位失败，请开启企微定位权限',
                  }).then(() => {
                    this.$router.go(-1)
                  });
                } else {
                  clearInterval(times)
                }
              }
            }, 1000)
            qiyeData = JSON.parse(dataList.data.ticket);
            wx.config({
              beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: qiyeData.appId, // 必填，企业微信的corpID
              timestamp: qiyeData.timestamp, // 必填，生成签名的时间戳
              nonceStr: qiyeData.nonceStr, // 必填，生成签名的随机串
              signature: qiyeData.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
              jsApiList: ["ready", "getLocation"] // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
            });
            wx.ready(function () {
              wx.getLocation({
                type: 'gcj02',
                success: function (res) {
                  flat = false;
                  loading1.clear()
                  var location = that.CJ02BD(res.latitude, res.longitude)
                  that.location = location;
                  that.lat = dataList.data.sfaStore.lat;
                  that.lon = dataList.data.sfaStore.lon;
                  that.storeId = dataList.data.sfaStore.storeId
                  that.hisTime = dataList.data.sfaStore.hisTime,
                      that.visitEntry = dataList.data.visitEntry
                  var routeDetailsId = null
                  if (dataList.data.rid != undefined) {
                    routeDetailsId = dataList.data.rid
                  }
                  // if (dataList.data.visitId != undefined) {
                  //   that.visitId = dataList.data.visitId
                  // }
                  localStorage.setItem('chainNameR', dataList.data.sfaStore.chainName)
                  if (that.lat == "" || that.lat == null) {
                    that.lat = that.location.lat
                    that.lon = that.location.lon
                  }
                  loading1.clear()
                  let PointSum = that.twoPointSum(that.lat, that.lon, location.lat, location.lon).toFixed(2)
                  if (PointSum > 500) {
                    that.visitModel = "5"
                    localStorage.setItem("visitModel", "5")
                    that.$dialog.confirm({
                      confirmButtonText: "确定",
                      cancelButtonText: "重新定位",
                      title: '系统提示',
                      message: '距离本店距离差距太大',
                      closeOnClickOverlay: true
                    }).then(() => {
                      that.$router.push({
                        path: "/taskList", query: {
                          storeId: that.storeId,
                          rdId: routeDetailsId,
                          lat: that.lat,
                          lon: that.lon,
                          visitId: that.visitId,
                          addressLine: dataList.data.sfaStore.addressLine,
                          storeCategory: that.storeCategory,
                          storeName: dataList.data.sfaStore.storeName,
                          hisTime: dataList.data.sfaStore.hisTime,
                          contactName: dataList.data.sfaStore.contactName,
                          storeCode: dataList.data.sfaStore.storeCode,
                          visitEntry: dataList.data.visitEntry,
                          visitModel: "5",
                          latNew: location.lat,
                          lonNew: location.lon,
                          PointSum: PointSum,
                          marklat:res.latitude,
                          marklon:res.longitude
                        }
                      })
                      localStorage.setItem('startTime', new Date());
                      localStorage.setItem('chainNameR', dataList.data.sfaStore.chainName)
                    })
                        .catch(() => {
                          that.getLocation()
                        });
                  } else {
                    // that.addVisits(dataList.data.visitEntry,routeDetailsId,PointSum)
                    that.$router.push({
                      path: "/taskList", query: {
                        storeId: that.storeId,
                        rdId: routeDetailsId,
                        lat: that.lat,
                        lon: that.lon,
                        hisTime: dataList.data.sfaStore.hisTime,
                        visitId: that.visitId,
                        addressLine: dataList.data.sfaStore.addressLine,
                        storeCategory: that.storeCategory,
                        storeName: dataList.data.sfaStore.storeName,
                        // hisTime:dataList.data.sfaStore.hisTime,
                        contactName: dataList.data.sfaStore.contactName,
                        storeCode: dataList.data.sfaStore.storeCode,
                        visitEntry: dataList.data.visitEntry,
                        visitModel: "5",
                        latNew: location.lat,
                        lonNew: location.lon,
                        PointSum: PointSum,
                        marklat:res.latitude,
                        marklon:res.longitude
                      }
                    })
                    localStorage.setItem('startTime', new Date());
                    localStorage.setItem('chainNameR', dataList.data.sfaStore.chainName)
                  }
                },
                fail: function () {
                  loading1.clear()
                  that.$dialog.alert({
                    message: 'GPS未开启',
                  }).then(() => {
                    that.getLocation()
                  });
                }
              });

            })
            wx.error(function (res) {
              loading1.clear()
              that.$dialog.alert({
                message: '定位失败，请开启企微定位权限',
              }).then(() => {
              });
            });
          } else {
            this.msg = dataList.msg
            this.$toast.fail(dataList.msg);
          }
        }
      });
    },
    visitFn() {
      this.$router.go(-1);
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  }
}
</script>
<style lang="scss" scoped>
.container {
  margin-bottom: 10px;
  background-color: white;
}

.card {
  background: #FFF;
  box-sizing: border-box;
  padding: 10px 16px;

  .title {
    line-height: 32px;
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }

  .subtitle {
    line-height: 24px;
    font-size: 14px;
    color: #7B7B7B;

    .status {
      float: right;
    }
  }

  .info {
    font-size: 14px;
    color: #484848;
    padding: 14px;
    border-bottom: 1px solid #f1f1f1;

    .arrow {
      float: right;
      display: inline-block;
      height: 20px;
      width: 20px;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      background: #0057ba;
      color: #FFF;
      font-weight: bold;
      font-size: 14px;
    }
  }

  .info1 {
    font-size: 14px;
    color: #666;
    line-height: 18px;
    padding: 4px 0;

    .arrow {
      float: right;
      display: inline-block;
      height: 20px;
      width: 20px;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      background: #0057ba;
      color: #FFF;
      font-weight: bold;
      font-size: 14px;
      margin-top: 9px;
    }
  }
}

.must {
  font-size: 18px;
  color: #f56c6c;
  margin-right: 2px;
}

.zw {
  display: inline-block;
  width: 7px;
  height: 100%;
}

.lineGrey {
  height: 10px;
  width: 100%;
  background: #f1f1f1;
}

.submitBtn {
  margin: 16px 0;
  font-size: 18px;
}

.border {
  border: 1px solid #dedede;
}

.ht30 {
  height: 30px;
}

.bodrder-b {
  border-bottom: 1px solid #dedede;
}

.card .f-blue {
  color: #0057ba;
}
</style>
<style>

.ht30 .van-radio__label {
  color: #8B8B8B;
}

.van-dialog__confirm, .van-dialog__confirm:active {
  color: #0057ba;
}
</style>