<template>
  <div class="noVisit">
    <div class="header">
      <van-nav-bar class="navBar" title="未拜访门店" left-arrow @click-left="onClickLeft" />
    </div>
    <div class="content">
      <van-collapse v-model="activeName" accordion @change="collapseCange">
        <van-collapse-item v-for="(val, key, ind) in list" :key="ind" :name="key">
          <template #title>
            <div class="title">{{ key | storeType }}</div>
            <div class="num">{{ val.storeNum }}家</div>
          </template>
          <div class="itemContent">
            <template v-if="val.storeList.length">
              <div class="item" v-for="(item, index) in val.storeList" :key="index">
                <div class="itemLeft">
                  <div class="storeName">{{ item.storeName }}</div>
                  <div class="address">
                    <van-icon name="location-o" />
                    {{ item.addressLine }}
                    <!-- <img v-if="item.distance" style="width: 36px" :src="sbpmdh" @click="linkapp(item)" /> -->
                  </div>
                  <div class="distance" v-if="item.distance">
                    (距离{{ Micrometer(item.distance) }}m)
                  </div>
                </div>
                <div class="itemRight">
                  <div
                    class="statstext"
                    :style="{
                      'background-color': item.stateString == '未拜访' ? '#ed5c68' : 'white',
                    }">
                    <van-icon
                      v-if="item.stateString == '拜访中'"
                      :name="times"
                      color="#ee0a24"
                      size="32" />
                    {{ item.stateString == '未拜访' ? '未拜访' : '' }}
                  </div>
                  <div class="toVisit" @click="storeVisit(item)">
                    进入拜访 <van-icon name="arrow" />
                  </div>
                </div>
              </div>
            </template>
            <template v-else><div style="text-align: center">暂无数据</div></template>
          </div>
        </van-collapse-item>
      </van-collapse>
    </div>
  </div>
</template>
<script>
import {
  selectUserStoreNoVisits,
  mobileReposition,
  checkVisit,
  addVisitsPosition,
} from '@/api/index';
import { checkStoreAddressByStoreCode } from '@/api/visitstore';
import { getPosition, getTicketFun } from '@/utils/TXApiFun';
import sbpmdh from '@/assets/sbpmdh.png';
import times from '@/assets/Icon/times.png';
import { mapState } from 'vuex';
import store from '@/store';
export default {
  name: 'noVisit',
  computed: {
    ...mapState({
      activaTypeStore: (state) => state.user.activaTypeStore,
    }),
  },
  data() {
    return {
      sbpmdh: sbpmdh,
      times: times,
      activeName: '',
      list: {},
      TXPiont: {}, //腾讯定位数据
      TXisBD: {}, // 腾讯定位数据转百度
      activatStoreVal: {}, //当前点击门店数据
      visitRoutePath: '', //拜访页面路径
      clickIsFlage: true,
    };
  },
  filters: {
    storeType(value) {
      let type = '';
      if (value == 'keKong') {
        type = '可控店';
      } else if (value == 'jinPai') {
        type = '金牌店';
      } else if (value == 'tongA') {
        type = '同城A';
      } else if (value == 'tongB') {
        type = '同城B';
      }
      return type;
    },
  },
  activated() {
    // 授权
    getTicketFun().then(() => {
      // 获取定位
      getPosition()
        .then((res) => {
          let { TXisBD } = res;
          this.getList(TXisBD);
        })
        .catch((error) => {
          this.$dialog.alert({
            message: error,
          });
        });
    });
    this.activeName = this.activaTypeStore || '';
  },
  methods: {
    collapseCange(value) {
      store.dispatch('setActivaTypeStore', value);
    },
    getList(TXisBD) {
      selectUserStoreNoVisits({
        lat: TXisBD.lat,
        lon: TXisBD.lon,
      }).then((res) => {
        this.list = res.data;
        console.log(this.list);
      });
    },
    tabChange(val) {},
    // 进入拜访
    storeVisit(val) {
      if (!this.clickIsFlage) return;
      this.clickIsFlage = false;
      this.toastLoading(0, '加载中...', true);
      // 删除拜访id
      localStorage.removeItem('visitId');
      checkVisit({ storeId: val.storeId }).then((res) => {
        if (res.code == 200) {
          this.activatStoreVal = val;
          // 拜访页面分为 计划外、计划内; 0计划内 1计划外
          this.visitRoutePath =
            this.activatStoreVal.visitEntry == '1'
              ? '/suishenbangOutstoreVisit'
              : '/storeVisitpage';
          if (val.stateString.indexOf('拜访中') != -1) {
            this.clickIsFlage = true;
            localStorage.setItem('startTime', new Date());
            localStorage.setItem('ORGName', this.activatStoreVal.deptName);
            localStorage.setItem('chainNameR', this.activatStoreVal.storeName);
            this.$router.push({
              path: this.visitRoutePath,
              query: {
                storeId: this.activatStoreVal.storeId,
                rdId: this.activatStoreVal.rdId,
                lat: this.activatStoreVal.lat,
                lon: this.activatStoreVal.lon,
                visitId: this.activatStoreVal.visitId,
                pageType: 'out',
                addressLine: this.activatStoreVal.addressLine,
                storeCategory: this.activatStoreVal.storeCategoryName,
                storeName: this.activatStoreVal.storeName,
                hisTime: this.activatStoreVal.hisTime,
                contactName: this.activatStoreVal.contactName,
                storeCode: this.activatStoreVal.storeCode,
                tabVal: this.tabVal,
                visitModel: '1',
                latNew: this.activatStoreVal.lat,
                lonNew: this.activatStoreVal.lon,
                PointSum: 0,
                marklat: this.activatStoreVal.lat,
                marklon: this.activatStoreVal.lon,
                from: 'outPlan',
              },
            });
          } else {
            // 拜访时重新获取定位
            getPosition()
              .then((res) => {
                let { TXisBD, resData } = res;
                this.TXisBD = TXisBD;
                this.TXPiont = resData;
                localStorage.setItem('lat', TXisBD.lat);
                localStorage.setItem('lon', TXisBD.lon);
                this.checkStoreAddressByStoreCodeFun();
              })
              .catch((error) => {
                this.clickIsFlage = true;
                this.$dialog.alert({
                  message: error,
                });
              });
          }
        } else {
          this.toastLoading().clear();
          this.clickIsFlage = true;
          this.$dialog.alert({
            message: res.msg,
          });
        }
      });
    },
    checkStoreAddressByStoreCodeFun() {
      this.toastLoading(0, '加载中...', true);
      let PointSumval = this.twoPointSum(
        this.TXisBD.lat,
        this.TXisBD.lon,
        this.TXisBD.lat,
        this.TXisBD.lon
      ).toFixed(2);
      // GZ:工装店铺 直接进入拜访
      if (localStorage.getItem('postType') == 'GZ') {
        localStorage.setItem('startTime', new Date());
        localStorage.setItem('ORGName', this.activatStoreVal.deptName);
        localStorage.setItem('chainNameR', this.activatStoreVal.storeName);
        this.toSuishenbangOutstoreVisit(PointSumval);
        return;
      }
      checkStoreAddressByStoreCode({
        storeCode: this.activatStoreVal.storeCode,
        lon: this.TXisBD.lon,
        lat: this.TXisBD.lat,
      })
        .then((response) => {
          this.clickIsFlage = true;
          // 门店校验 地址不通过
          if (response.code != 200) {
            this.toastLoading().clear();
            // updateAddress : ，1：同城AB+金牌,去修改地址;2:非金牌店铺，非同城店铺偏差过大不允许拜访，可以重置定位;0非金牌店铺，非同城店铺 位置信息不存在 可以继续拜访
            if (response.data) {
              if (response.data.updateAddress == 0) {
                // 非金牌店铺，非同城店铺 位置信息不存在 可以继续拜访
                this.$dialog
                  .confirm({
                    confirmButtonText: '确定拜访',
                    cancelButtonText: '取消拜访',
                    title: '系统提示',
                    message:
                      '该客户没有经纬度，此次拜访会保存定位点作为客户经纬度，下次拜访时判断是否偏差过大。',
                    closeOnClickOverlay: true,
                  })
                  .then(() => {
                    this.toSuishenbangOutstoreVisit(PointSumval);
                  });
              } else if (response.data.updateAddress == 1) {
                // 同城AB+金牌,去修改地址
                // addressUpdateTimesOver: true=已经达到最大次数，不让修改; false=没有达到可以修改
                if (!response.data.addressUpdateTimesOver) {
                  this.$dialog
                    .confirm({
                      title: '系统提示',
                      message: response.msg + '请立即修改后再拜访',
                      messageAlign: 'left',
                      confirmButtonText: '立即修改',
                      cancelButtonText: '取消',
                    })
                    .then(() => {
                      this.$router.push({
                        path: '/storeDetail',
                        query: {
                          id: this.activatStoreVal.storeId,
                          type: 'address',
                          storeAddressId: this.activatStoreVal.storeAddressId,
                        },
                      });
                    });
                } else {
                  this.$dialog.confirm({
                    title: '系统提示',
                    message: '已经达到最大修改次数',
                    messageAlign: 'left',
                    confirmButtonText: '确定',
                  });
                }
              } else if (response.data.updateAddress == 2) {
                // 1.非金牌店铺，非同城店铺 位置偏差过大 重置经纬度
                this.resetCoord(PointSumval);
                return;
              }
            } else {
              this.$dialog.confirm({
                title: '系统提示',
                message: response.msg,
                showCancelButton: false,
                confirmButtonText: '确定',
              });
            }
          } else {
            // 门店编码校验门店地址通过 进入拜访
            this.toSuishenbangOutstoreVisit(PointSumval);
          }
        })
        .catch((error) => {
          this.clickIsFlage = true;
        });
    },
    // 进入拜访
    toSuishenbangOutstoreVisit(PointSumval) {
      addVisitsPosition({
        storeId: this.activatStoreVal.storeId,
        visitsId: '',
        lon: this.TXPiont.longitude,
        lat: this.TXPiont.latitude,
        sourceLon: this.TXisBD.lon,
        sourceLat: this.TXisBD.lat,
        positionDesc: '',
        accuracy: this.TXPiont.accuracy,
      });
      this.clickIsFlage = true;
      this.toastLoading().clear();
      this.$router.push({
        path: this.visitRoutePath,
        query: {
          storeId: this.activatStoreVal.storeId,
          rdId: this.activatStoreVal.rdId,
          lat: this.TXisBD.lat,
          lon: this.TXisBD.lon,
          visitId: this.activatStoreVal.visitId,
          pageType: 'out',
          addressLine: this.activatStoreVal.addressLine,
          storeCategory: this.activatStoreVal.storeCategoryName,
          storeName: this.activatStoreVal.storeName,
          hisTime: this.activatStoreVal.hisTime,
          contactName: this.activatStoreVal.contactName,
          storeCode: this.activatStoreVal.storeCode,
          tabVal: this.tabVal,
          visitModel: '1',
          latNew: this.TXisBD.lat,
          lonNew: this.TXisBD.lon,
          PointSum: PointSumval,
          marklat: this.TXPiont.latitude,
          marklon: this.TXPiont.longitude,
          from: 'outPlan',
        },
      });
    },
    // 重置经纬度
    resetCoord(PointSumval) {
      this.$dialog
        .confirm({
          confirmButtonText: '初始化定位',
          cancelButtonText: '取消拜访',
          title: '系统提示',
          message: '偏差过大，不允许拜访。可修改本店定位.',
          closeOnClickOverlay: true,
        })
        .then(() => {
          mobileReposition({
            storeId: this.activatStoreVal.storeId,
            lat: this.TXisBD.lat,
            lon: this.TXisBD.lon,
          }).then((response) => {
            if (response.code == 200) {
              this.$dialog
                .alert({
                  title: '系统提示',
                  message: '本信息定位已更新成功!',
                })
                .then(() => {
                  this.toSuishenbangOutstoreVisit(PointSumval);
                });
              localStorage.setItem('startTime', new Date());
              localStorage.setItem('ORGName', this.activatStoreVal.deptName);
              localStorage.setItem('chainNameR', this.activatStoreVal.storeName);
            } else {
              this.$toast(response.msg);
            }
          });
        });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
.noVisit {
  height: 100%;
  width: 100%;
  /* overflow-y: auto; */
  .content {
    padding: 8px 10px;
    .item {
      background: #deedff;
      padding: 8px;
      margin: 10px 0;
      border-radius: 5px;
      display: flex;
      .storeName {
        font-size: 15px;
        font-weight: bold;
        color: #333;
        padding: 3px 0;
      }
      .address,
      .distance {
        font-size: 14px;
        color: #909090;
        padding: 3px 0;
      }
      .distance {
        padding-left: 12px;
      }
      .itemLeft {
        flex: 1;
      }
      .itemRight {
        width: 25%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: end;
        .statstext {
          background-color: #0057ba;
          padding: 2px 6px 2px 12px;
          border-bottom-left-radius: 60px;
          border-top-left-radius: 60px;
          color: #fff;
          width: 60px;
          margin-right: -8px;
          .van-icon__image {
            height: 0.7em;
          }
        }
        .toVisit {
          height: 40%;
          font-size: 15px;
          color: #1989fa;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: end;
        }
      }
    }
  }
  .van-collapse-item {
    border-bottom: 1px solid #dcdcdc;
  }
}
</style>
<style lang="scss">
.noVisit {
  .van-cell__title {
    font-size: 15px;
    font-weight: bold;
    color: #333;
    display: flex;
    justify-content: space-between;
    .num {
      color: #909090;
      margin-right: 5px;
    }
  }
  .van-collapse-item__wrapper {
    border-top: 1px solid #dcdcdc;
  }
  .van-collapse-item__title--expanded {
    position: sticky;
    top: 0px;
    z-index: 10;
  }
}
</style>
