<template>
  <div class="success">
    <van-nav-bar class="navBar" title="下单成功" />
    <div
      style="
        background-color: rgb(74, 202, 109);
        color: #fff;
        width: 132px;
        height: 132px;
        border-radius: 106px;
        text-align: center;
        line-height: 190px;
        margin: 38% auto 80px;
      ">
      <van-icon name="success" size="80" />
    </div>
    <van-row gutter="20" style="display: flex; justify-content: center">
      <van-col
        ><van-button
          icon="revoke"
          style="width: 120px"
          size="small"
          round
          type="primary"
          @click="goback"
          >返回</van-button
        >
      </van-col>
      <!-- <van-col span="12"
        ><van-button
          icon="guide-o"
          style="width: 120px"
          size="small"
          round
          type="info"
          @click="visite"
          >去拜访</van-button
        ></van-col
      > -->
    </van-row>
    <van-row
      gutter="20"
      style="display: flex; justify-content: center"
      v-if="fromValue && this.fromValue.storeId">
      <van-col>
        <van-button
          style="width: 120px"
          size="small"
          round
          type="primary"
          @click="gobackStoreDetail"
          >上传陈列照
        </van-button>
      </van-col>
    </van-row>
    <div class="tips">
      <span>该门店可拜访和下单，待上传产品陈列照、主管审核后，才能建店成功</span>
    </div>
  </div>
</template>

<script>
import { addstoreRegister, addVisitsPosition, checkVisit, mobileReposition } from '@/api';
import axios from 'axios';

export default {
  name: 'success',
  data() {
    return {
      fromValue: null,
      cont: 0,
      timer: null,
      flag: true,
      lat: null,
      lon: null,
    };
  },
  activated() {
    this.addstoreRegister();
  },
  methods: {
    addstoreRegister() {
      console.log('this.$route.query=' + JSON.stringify(this.$route.query));
      console.log('storeCode=' + this.$route.query.storeCode);
      addstoreRegister({
        storeCode: this.$route.query.storeCode,
        orderNo: this.$route.query.orderNo,
      }).then((res) => {
        this.fromValue = res.data;
      });
    },
    goback() {
      window.location.replace(window.location.origin + this.locationOrigin + '/My/index');
    },
    // 返回订单详情也
    gobackStoreDetail() {
      // window.location.replace(
      //   window.location.origin + '/mobile/storeDetail?id=' + this.fromValue.storeId
      // );
      localStorage.setItem('successStoreId', this.fromValue.storeId);
      // 跳转到列表在跳到详情页在跳编辑页
      window.location.replace(
        window.location.origin + this.locationOrigin + '/storemanagementlist?source=successPage',
      );
    },
    visite() {
      var that = this;
      checkVisit({ storeId: this.fromValue.storeId }).then((response) => {
        localStorage.setItem('startTime', new Date());
        localStorage.setItem('ORGName', this.fromValue.deptName);
        localStorage.setItem('chainNameR', this.fromValue.storeName);
        let loading1 = this.$toast.loading({
          duration: 0,
          message: '加载中...',
          forbidClick: true,
        });
        let url = window.location.href;
        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,
            },
          })
          .then((response) => {
            if (response.status == 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(() => {});
                  } else {
                    clearInterval(times);
                  }
                }
              }, 1000);
              qiyeData = response.data.data;
              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);
                    if (that.fromValue.lat == '' || that.fromValue.lat == null) {
                      that.lat = location.lat;
                      that.lon = location.lon;
                    } else {
                      that.lat = that.fromValue.lat;
                      that.lon = that.fromValue.lon;
                    }
                    let PointSum = that
                      .twoPointSum(that.lat, that.lon, location.lat, location.lon)
                      .toFixed(2);
                    if (PointSum > 500 && localStorage.getItem('postType') != 'GZ') {
                      if (that.fromValue.mobileRepositionBy != null) {
                        that.$dialog
                          .alert({
                            title: '系统提示',
                            message:
                              '偏差过大，不允许拜访。本店定位已修改过一次，若需再次调整，请联系大区市场推广部。',
                          })
                          .then(() => {
                            // on close
                          });
                      } else {
                        that.$dialog
                          .confirm({
                            confirmButtonText: '初始化定位',
                            cancelButtonText: '取消拜访',
                            title: '系统提示',
                            message: '偏差过大，不允许拜访。可修改本店定位，但只能修改一次.',
                            closeOnClickOverlay: true,
                          })
                          .then(() => {
                            mobileReposition({
                              storeId: that.fromValue.storeId,
                              lat: location.lat,
                              lon: location.lon,
                            }).then((res) => {
                              if (res.code == 200) {
                                let PointSumval = that
                                  .twoPointSum(
                                    location.lat,
                                    location.lon,
                                    location.lat,
                                    location.lon,
                                  )
                                  .toFixed(2);
                                that.$dialog
                                  .alert({
                                    title: '系统提示',
                                    message: '本信息定位已更新成功!',
                                  })
                                  .then(() => {
                                    window.location.replace(
                                      window.location.origin +
                                        this.locationOrigin +
                                        '/suishenbangOutstoreVisit?PointSum=' +
                                        PointSumval +
                                        '&visitModel=1&tabVal=1&hisTime=null&pageType=out&visitId=null&rdId=null&storeId=' +
                                        that.fromValue.storeId +
                                        '&lat=' +
                                        location.lat +
                                        '&lon=' +
                                        location.lon +
                                        '&addressLine=' +
                                        that.fromValue.addressLine +
                                        '&storeCategory=' +
                                        that.fromValue.storeCategory +
                                        '&storeName=' +
                                        that.fromValue.storeName +
                                        '&contactName=' +
                                        that.fromValue.contactName +
                                        '&storeCode=' +
                                        that.fromValue.storeCode +
                                        '&latNew=' +
                                        location.lat +
                                        '&lonNew=' +
                                        location.lon +
                                        '&marklat=' +
                                        res.latitude +
                                        '&marklon=' +
                                        res.longitude,
                                    );
                                  });
                                localStorage.setItem('startTime', new Date());
                                localStorage.setItem('ORGName', that.fromValue.deptName);
                                localStorage.setItem('chainNameR', that.fromValue.storeName);
                              } else {
                                that.$toast(res.msg);
                              }
                            });
                          });
                      }
                    } else {
                      if (that.fromValue.lat == '' || that.fromValue.lat == null) {
                        that.$dialog
                          .confirm({
                            confirmButtonText: '确定拜访',
                            cancelButtonText: '取消拜访',
                            title: '系统提示',
                            message:
                              '该信息没有经纬度，此次拜访会保存定位点作为信息经纬度，但只能设定一次，下次拜访时判断是否偏差过大。',
                            closeOnClickOverlay: true,
                          })
                          .then(() => {
                            window.location.replace(
                              window.location.origin +
                                this.locationOrigin +
                                '/suishenbangOutstoreVisit?PointSum=' +
                                PointSumval +
                                '&visitModel=1&tabVal=1&hisTime=null&pageType=out&visitId=null&rdId=null&storeId=' +
                                that.fromValue.storeId +
                                '&lat=' +
                                location.lat +
                                '&lon=' +
                                location.lon +
                                '&addressLine=' +
                                that.fromValue.addressLine +
                                '&storeCategory=' +
                                that.fromValue.storeCategory +
                                '&storeName=' +
                                that.fromValue.storeName +
                                '&contactName=' +
                                that.fromValue.contactName +
                                '&storeCode=' +
                                that.fromValue.storeCode +
                                '&latNew=' +
                                location.lat +
                                '&lonNew=' +
                                location.lon +
                                '&marklat=' +
                                res.latitude +
                                '&marklon=' +
                                res.longitude,
                            );
                          })
                          .catch(() => {});
                      } else {
                        window.location.replace(
                          window.location.origin +
                            this.locationOrigin +
                            '/suishenbangOutstoreVisit?PointSum=0&visitModel=1&tabVal=1&hisTime=null&pageType=out&visitId=null&rdId=null&storeId=' +
                            that.fromValue.storeId +
                            '&lat=' +
                            that.fromValue.lat +
                            '&lon=' +
                            that.fromValue.lon +
                            '&addressLine=' +
                            that.fromValue.addressLine +
                            '&storeCategory=' +
                            that.fromValue.storeCategory +
                            '&storeName=' +
                            that.fromValue.storeName +
                            '&contactName=' +
                            that.fromValue.contactName +
                            '&storeCode=' +
                            that.fromValue.storeCode +
                            '&latNew=' +
                            that.fromValue.lat +
                            '&lonNew=' +
                            that.fromValue.lon +
                            '&marklat=' +
                            res.latitude +
                            '&marklon=' +
                            res.longitude,
                        );
                      }
                      localStorage.setItem('startTime', new Date());
                      localStorage.setItem('ORGName', that.fromValue.deptName);
                      localStorage.setItem('chainNameR', that.fromValue.storeName);
                    }
                    addVisitsPosition({
                      storeId: that.fromValue.storeId,
                      visitsId: '',
                      lon: res.longitude,
                      lat: res.latitude,
                      sourceLon: location.lon,
                      sourceLat: location.lat,
                      positionDesc: '',
                      accuracy: res.accuracy,
                    });
                  },
                  fail: function () {
                    loading1.clear();
                    that.$dialog.alert({
                      message: 'GPS未开启',
                    });
                  },
                });
              });
              wx.error(function (res) {
                loading1.clear();
                that.$dialog
                  .alert({
                    message: '定位失败，请开启企微定位权限',
                  })
                  .then(() => {});
              });
            }
          });
      });
    },
  },
};
</script>

<style scoped lang="scss">
.success {
  .van-row {
    padding: 5px 0;
  }
}
.tips {
  display: flex;
  flex-direction: column;
  align-items: center;
  span {
    width: 80%;
    font-size: 14px;
    color: #0057ba;
    display: flex;
    align-items: center;
    padding: 5px 0;
  }
}
</style>
