<template>
  <div>
    <!--        顶部条-->
    <van-nav-bar class="navBar" title="拜访" left-arrow @click-left="onClickLeft" />
    <!--        主体内容-->
    <div class="container">
      <div class="lineGrey"></div>
      <div class="card mt10">
        <div class="title f-blue">
          {{ storeName }}(<span style="color: #0057ba">{{ storeCode }}</span
          >)
        </div>
        <div class="info1">类型：{{ storeCategory }}</div>
        <div class="info1">地址：{{ addressLine }}</div>
        <div class="info1" v-if="notes != null">上次拜访备注：{{ notes }}</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(shopCode)"
          >经营情况</van-button
        >
      </div>
      <div style="color: #999; font-size: 12px; padding: 10px; background-color: #f5f5f5">
        <van-icon name="info-o" />&nbsp;今天拜访拍照内容，将同步传给部主管查阅。
      </div>
      <div class="card">
        <div
          class="info"
          v-for="(item, index) in list"
          :key="index"
          @click="addStoreVisit(item, index)">
          <span class="must" v-show="item.isMust == '0'">*</span>
          <p style="width: 94%; margin: 0; line-height: 24px; display: inline-block">
            {{ item.taskName }}
          </p>
          <span v-show="!item.success" class="arrow" style="background-color: #fff; color: #444"
            ><van-icon name="arrow"
          /></span>
          <span v-show="item.success" class="arrow" style="background-color: #0057ba"
            ><van-icon name="success"
          /></span>
        </div>
      </div>
    </div>
    <div class="tc" style="padding: 0 16px">
      <van-button class="submitBtn" block type="info" color="#0057ba" @click="endVisitsFn"
        >提交拜访</van-button
      >
    </div>
    <br />
    <div id="allmap"></div>
  </div>
</template>

<script>
import { getStoreGroupTask, endVisits, editDwellTime, suishenbangStoreSale } from '@/api/index';
import axios from 'axios';
export default {
  name: 'outstoreVisit',
  data() {
    return {
      notes: '',
      visitModel: '1',
      storeId: '',
      rdId: '',
      lat: '',
      lon: '',
      timer: null,
      flag: true,
      list: [],
      storeGroupId: '',
      visitId: null,
      addressLine: '',
      storeCategory: '',
      storeName: '',
      contactName: '',
      shopCode: '',
      storeCode: '',
      urlParameter: '',
      location: {
        lat: '34.6174',
        lon: '112.44039',
      },
      address: '',
      city: '',
      locationAccuracy: '',
      id: '89',
      visitEntry: '',
      hisTime: '',
      latNew: '',
      lonNew: '',
      PointSum: '',
    };
  },
  created() {
    this.urlParameter = this.$route.query;
    this.storeId = this.$route.query.storeId + '';
    this.rdId = this.$route.query.rdId + '';
    this.lat = this.$route.query.lat + '';
    this.lon = this.$route.query.lon + '';
    this.visitId = this.$route.query.visitId;
    this.addressLine = this.$route.query.addressLine + '';
    this.storeCategory = this.$route.query.storeCategory + '';
    this.storeName = this.$route.query.storeName + '';
    this.contactName = this.$route.query.contactName;
    this.visitEntry = this.$route.query.visitEntry + '';
    this.visitModel = this.$route.query.visitModel + '';
    this.latNew = this.$route.query.latNew + '';
    this.lonNew = this.$route.query.lonNew + '';
    this.hisTime = this.$route.query.hisTime + '';
    this.PointSum = this.$route.query.PointSum + '';
    this.storeCode = this.$route.query.storeCode + '';
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == '/outstoreVisit' && from.path == '/taskList') {
      this.editDwellTimes();
      localStorage.removeItem('visitModel');
      this.$router.go(-1);
    }
    next();
  },
  activated() {
    this.urlParameter = this.$route.query;
    this.storeId = this.$route.query.storeId + '';
    this.rdId = this.$route.query.rdId + '';
    this.lat = this.$route.query.lat + '';
    this.lon = this.$route.query.lon + '';
    this.visitId = this.$route.query.visitId;
    this.addressLine = this.$route.query.addressLine + '';
    this.storeCategory = this.$route.query.storeCategory + '';
    this.storeName = this.$route.query.storeName + '';
    this.contactName = this.$route.query.contactName;
    this.visitEntry = this.$route.query.visitEntry + '';
    this.visitModel = this.$route.query.visitModel + '';
    this.latNew = this.$route.query.latNew + '';
    this.lonNew = this.$route.query.lonNew + '';
    this.hisTime = this.$route.query.hisTime + '';
    this.PointSum = this.$route.query.PointSum + '';
    this.storeCode = this.$route.query.storeCode + '';
    this.list = [];
    if (localStorage.getItem('visitId') != null) {
      this.visitId = localStorage.getItem('visitId');
      setTimeout(() => {
        this.addVisits();
      });
    } else {
      setTimeout(() => {
        this.addVisits();
      });
    }
  },
  methods: {
    visitFn(val) {
      this.$router.go(-2);
    },
    // 停留时间
    editDwellTimes() {
      let dwellTime = this.weekend(localStorage.getItem('startTime'), new Date()) + '';
      editDwellTime({ dwellTime: dwellTime, visitsId: this.visitId }).then((res) => {
        if (res.code == 200) {
          localStorage.removeItem('visitId');
        }
      });
    },
    // 获取任务组
    getLocation() {
      this.list = [];
      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) {
              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) {
                    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.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;
                    }
                    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: '距离本店距离差距太大',
                        })
                        .then(() => {
                          that.addVisits(dataList.data.visitEntry, routeDetailsId, PointSum);
                        })
                        .catch(() => {
                          that.getLocation();
                        });
                    } else {
                      that.addVisits(dataList.data.visitEntry, routeDetailsId, PointSum);
                    }
                  },
                  fail: function () {
                    that.$dialog
                      .alert({
                        message: 'GPS未开启',
                      })
                      .then(() => {
                        that.getLocation();
                      });
                  },
                });
              });
            } else {
              this.$toast.fail(dataList.msg);
            }
          }
        });
    },
    addVisits() {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      var that = this;
      var map = new TMap.Map('allmap', {
        zoom: 14,
        center: new TMap.LatLng(39.986785, 116.301012),
      });
      var geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类
      var markers = new TMap.MultiMarker({
        map: map,
        geometries: [],
      });

      markers.setGeometries([]);
      var input = [that.urlParameter.marklat, that.urlParameter.marklon];
      var location = new TMap.LatLng(Number(input[0]), Number(input[1]));
      map.setCenter(location);
      markers.updateGeometries([
        {
          id: 'main', // 点标注数据数组
          position: location,
        },
      ]);
      geocoder.getAddress({ location: location }).then(
        function (result) {
          var addresses = result.result.formatted_addresses;
          let address_component = result.result.address_component;
          let province = address_component.province;
          let city = address_component.city;
          let district = address_component.district;
          console.log('province=' + province);
          console.log('city=' + city);
          console.log('district=' + district);
          var params = {
            storeId: that.storeId,
            storeCode: that.storeCode,
            visitEntry: that.visitEntry,
            lat: that.lat,
            lon: that.lon,
            visitSource: '1',
            visitModel: that.visitModel,
            routeDetailsId: that.rdId,
            locationCity: '',
            locationRemark: addresses.recommend,
            locationAccuracy: that.PointSum,
            province: address_component.province,
            city: address_component.city,
            district: address_component.district,
          };
          that.locationAccuracy = that.PointSum;
          that.city = '';
          that.address = '';
          localStorage.setItem('address', '');
          if (that.visitId != null) {
            params.id = that.visitId;
          }
          that.list = [];
          getStoreGroupTask(params).then((res) => {
            if (res.code == 200) {
              loading1.clear();
              localStorage.setItem('visitId', res.data.visitId);
              that.notes = res.data.notes;
              that.visitId = res.data.visitId;
              that.list = res.data.sfaTaskList;
              that.storeGroupId = res.data.storeGroupId;
            } else {
              that.$toast(res.msg);
            }
          });
        },
        function (err) {
          var params = {
            storeId: that.storeId,
            storeCode: that.storeCode,
            visitEntry: that.visitEntry,
            lat: that.lat,
            lon: that.lon,
            visitSource: '1',
            visitModel: that.visitModel,
            routeDetailsId: that.rdId,
            locationCity: '',
            locationRemark: '',
            locationAccuracy: that.PointSum,
          };
          that.locationAccuracy = that.PointSum;
          that.city = '';
          that.address = '';
          localStorage.setItem('address', '');
          if (that.visitId != null) {
            params.id = that.visitId;
          }
          that.list = [];
          getStoreGroupTask(params).then((res) => {
            if (res.code == 200) {
              loading1.clear();
              localStorage.setItem('visitId', res.data.visitId);
              that.notes = res.data.notes;
              that.visitId = res.data.visitId;
              that.list = res.data.sfaTaskList;
              that.storeGroupId = res.data.storeGroupId;
            } else {
              that.$toast(res.msg);
            }
          });
        }
      );
    },
    // 任务填写
    addStoreVisit(val, index) {
      if (this.flag) {
        this.flag = false;
        this.timer = null;
        this.timer = setTimeout(() => {
          this.flag = true;
        }, 2000);
        this.$router.push({
          path: '/addStoreVisit',
          query: {
            visitSource: '1',
            storeId: this.storeId,
            storeCode: this.storeCode,
            visitId: this.visitId,
            visitEntry: this.visitEntry,
            ids: index,
            taskId: val.taskId,
            storeGroupId: this.storeGroupId,
            taskType: val.taskType,
            photoType: val.photoType,
            lat: this.lat,
            lon: this.lon,
            visitModel: this.visitModel,
            locationCity: this.city,
            locationRemark: this.address,
            locationAccuracy: this.locationAccuracy,
          },
        });
      }
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    weekend(time1) {
      var arrtime1 = new Date(time1).getTime();
      var arrtime2 = new Date().getTime();
      return Math.round((arrtime2 - arrtime1) / 1000);
    },
    // 任务提交
    endVisitsFn() {
      if (this.list.length == 0) {
        this.$toast('暂无任务提交');
        return;
      }
      for (var vl = 0; vl < this.list.length; vl++) {
        if (this.list[vl].isMust == '0') {
          if (!this.list[vl].success) {
            this.$toast(this.list[vl].taskName + '任务未完成');
            return;
          }
        }
      }
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      let dwellTime = this.weekend(localStorage.getItem('startTime'), new Date());
      // dwellTime:dwellTime,
      if (this.flag) {
        this.flag = false;
        this.timer = null;
        this.timer = setTimeout(() => {
          this.flag = true;
        }, 5000);
        endVisits({
          storeGroupId: this.storeGroupId,
          dwellTime: dwellTime,
          id: this.visitId,
          storeCode: this.$route.query.storeCode,
          visitModel: this.$route.query.visitModel,
          visitSource: '1',
        }).then((res) => {
          loading1.clear();
          this.flag = true;
          if (res.code == 200) {
            this.$router.go(-2);
          } else {
            this.$toast(res.msg);
          }
        });
      }
    },
  },
};
</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;
    position: relative;
    .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;
      position: absolute;
      margin-top: -10px;
      right: 0;
      top: 50%;
    }
  }
  .info1 {
    font-size: 14px;
    color: #666;
    line-height: 18px;
    padding: 4px 0;
    position: relative;
    .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;
      position: absolute;
      margin-top: -10px;
      right: 0;
      top: 50%;
    }
  }
}
.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;
}
.bodrder-b {
  border-bottom: 1px solid #dedede;
}
.card .f-blue {
  color: #0057ba;
}
</style>
<style>
#allmap {
  width: 20px;
  height: 20px;
  left: -1000px;
  position: relative;
}
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #0057ba;
}
</style>
