<template>
  <div class="bgcolor home">
    <div class="header">
      <van-nav-bar class="navBar" :title="$route.meta.title">
        <template #left>
          <span @click="login" style="display: block; width: 50px; height: 100%"></span>
        </template>
        <template #right>
          <span @click="searchFn">筛选<van-icon name="arrow-down" /></span>
        </template>
      </van-nav-bar>
      <div class="searchDiv">
        <van-search
          v-model="chainsName"
          left-icon="search"
          show-action
          placeholder="搜索名称/编号"
          @clear="clearFn">
          <template #action>
            <div @click="onSearchm">搜索</div>
          </template>
        </van-search>
      </div>
      <van-tabs class="myTab" type="card" v-model="tabVal" color="#0057ba" @change="tabChange">
        <van-tab title="销售部" name="0" :disabled="disabled"></van-tab>
        <van-tab title="我的" name="1" :disabled="disabled"></van-tab>
      </van-tabs>
    </div>
    <div class="content" id="content" @touchmove="handleTouch">
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <van-list
          class="myList"
          v-model="loading"
          :finished="finished"
          finished-text="--已经到底了--"
          @load="onLoad">
          <div class="cellcontent" v-for="(item, index) in list" :key="index" v-if="list.length">
            <van-cell>
              <div class="card">
                <div class="title titlero">
                  <span @click="goOtherSystem(item)" :style="setStroeNameStyle(item)">
                    <span>{{ item.chainName }}</span>
                    (<span>{{ item.chainCode }}</span
                    >)
                  </span>
                  <span class="btn" :data-clipboard-text="item.chainCode">
                    <van-icon
                      :name="require('@/assets/icon/paste.png')"
                      color="#ee0a24"
                      size="20"
                      style="top: 6px; margin-left: 4px" />
                  </span>
                </div>
                <div class="info" style="position: relative">
                  身份类型：{{ item.typeName2 }}
                  <div style="position: absolute; bottom: 0px; right: 0px" v-if="false">
                    <!-- 凤凰客户 -->
                    <el-popover
                      popper-class="zpover"
                      placement="bottom"
                      width="120"
                      trigger="click"
                      content="该客户为凤凰客户">
                      <div
                        v-if="item.storeLabels && item.storeLabels.fhCustomer"
                        class="visitStoreIco"
                        style="background-color: #fff"
                        slot="reference">
                        <van-icon :name="require('@/assets/icon/fenghuangjihua.png')" size="26" />
                      </div>
                    </el-popover>
                    <!-- 本月已出货 -->
                    <el-popover
                      popper-class="zpover"
                      placement="bottom"
                      width="120"
                      trigger="click"
                      content="本月已出货">
                      <div
                        v-if="item.storeLabels && item.storeLabels.fhCustomer"
                        class="visitStoreIco"
                        style="background-color: #fff"
                        slot="reference">
                        <van-icon :name="require('@/assets/icon/fenghuangjihua.png')" size="26" />
                      </div>
                    </el-popover>
                    <el-popover
                      popper-class="zpover zpover6"
                      placement="bottom-start"
                      trigger="click">
                      <div>
                        <p>
                          本店{{ timeData }}下单SKU数：<a
                            @click="linkList(item)"
                            style="text-decoration: underline"
                            >点击查看详情</a
                          >
                        </p>
                      </div>
                      <div
                        class="visitStoreIco"
                        style="background-color: #fff; position: relative"
                        slot="reference">
                        <p
                          style="
                            width: 100%;
                            position: absolute;
                            z-index: 1;
                            top: 0.2px;
                            width: 22px;
                            margin: 0;
                            margin-left: 3.6px;
                            text-align: center;
                            font-size: 12px;
                          ">
                          <!-- {{ item.storeLabels.zysslNums }} -->
                          111
                        </p>
                        <van-icon :name="require('@/assets/icon/ord.png')" size="26" />
                      </div>
                    </el-popover>
                    <!-- <el-popover
                      popper-class="zpover zpover5"
                      placement="bottom"
                      width="200"
                      trigger="click">
                      <div v-if="item.storeLabels">
                        <p>已参加:</p>
                        <p v-for="tt in (item.storeLabels.targetOne + '').split(';')">
                          {{ tt }}
                        </p>
                      </div>
                      <div
                        class="visitStoreIco"
                        v-if="item.storeLabels.targetOne"
                        style="background-color: #fff"
                        slot="reference">
                        <van-icon :name="targetOne" size="26" />
                      </div>
                    </el-popover>
                    <el-popover
                      popper-class="zpover"
                      placement="bottom"
                      width="120"
                      trigger="click"
                      content="调色机5天未联网">
                      <div
                        v-if="item.storeLabels.ccmOffline"
                        class="visitStoreIco"
                        style="background-color: #fff"
                        slot="reference">
                        <van-icon :name="Network" size="26" />
                      </div>
                    </el-popover>
                    <el-popover
                      popper-class="zpover"
                      placement="bottom"
                      width="200"
                      trigger="click"
                      content="同城店近60天未下单">
                      <div
                        v-if="item.storeLabels.fxNoOrder"
                        class="visitStoreIco"
                        style="background-color: #fff"
                        slot="reference">
                        <van-icon :name="order60" size="26" />
                      </div>
                    </el-popover>
                    <el-popover
                      popper-class="zpover"
                      placement="bottom"
                      width="200"
                      trigger="click"
                      content="金牌店近30天未下单">
                      <div
                        v-if="item.storeLabels.noOrder"
                        class="visitStoreIco"
                        style="background-color: #fff"
                        slot="reference">
                        <van-icon :name="order" size="26" />
                      </div>
                    </el-popover>
                    <el-popover
                      popper-class="zpover"
                      placement="bottom"
                      width="200"
                      trigger="click"
                      content="本店本月进过专业时时丽">
                      <div
                        class="visitStoreIco"
                        v-if="item.storeLabels.zyssl"
                        style="background-color: #ed5c68"
                        slot="reference">
                        专
                      </div>
                    </el-popover>
                    <el-popover
                      popper-class="zpover zpover1"
                      placement="bottom"
                      width="200"
                      trigger="click"
                      content="本店本月进过超好贴">
                      <div
                        v-if="item.storeLabels.chtczj"
                        class="visitStoreIco"
                        style="background-color: #0057ba"
                        slot="reference">
                        超
                      </div>
                    </el-popover>
                    <el-popover
                      placement="bottom"
                      popper-class="zpover zpover1 zpover1sb"
                      :disabled="!item.userVisitTimesMap"
                      trigger="click">
                      <div
                        v-if="item.storeLabels.visitTimes && item.storeLabels.visitTimes > 0"
                        class="visitStoreIco"
                        slot="reference"
                        style="background-color: #fff; position: relative">
                        <p
                          style="
                            width: 100%;
                            position: absolute;
                            z-index: 10;
                            top: -2px;
                            margin: 0;
                            text-align: center;
                            font-size: 12px;
                          ">
                          {{ item.storeLabels.visitTimes }}
                        </p>
                        <van-icon :name="ordernum" size="26" />
                      </div>
                      <el-table :data="item.userVisitTimesMap" border max-height="180px">
                        <el-table-column label="业务员" prop="userName" />
                        <el-table-column label="拜访次数" prop="visitTimes" width="110px" />
                      </el-table>
                    </el-popover> -->
                  </div>
                </div>
                <div class="info">实际经营者：{{ item.customerManager }}</div>
                <div class="info">开户日期：{{ formatCompactDate(item.openDate) }}</div>
                <div class="info">是否冻结：{{ item.freeze }}</div>
                <div class="info">是否关户：{{ item.close }}</div>
              </div>
              <div
                class="statstext"
                v-if="item.stateString == '未拜访'"
                style="background-color: #ed5c68">
                未拜访
              </div>
              <div
                class="statstext"
                v-if="item.stateString == '拜访中'"
                style="background-color: white">
                <van-icon :name="require('@/assets/icon/times.png')" color="#ee0a24" size="32" />
              </div>
              <div class="statstext" v-if="item.stateString == '已拜访'">已拜访</div>
              <div class="btnbox">
                <van-row>
                  <van-col span="5" v-if="item.stateString != '已拜访'" @click="storeVisit(item)">
                    <img
                      :src="require('@/assets/icon/call.png')"
                      style="margin: 0 auto; height: 18px; display: block" />
                    <p style="text-align: center; margin: 0; font-size: 12px">进入拜访</p>
                  </van-col>
                  <van-col
                    span="5"
                    v-if="item.stateString != '已拜访'"
                    @click="abnormalVisit(item)">
                    <img
                      :src="require('@/assets/icon/yichang.png')"
                      style="margin: 0 auto; height: 18px; display: block" />
                    <p style="text-align: center; margin: 0; margin-top: 1px; font-size: 12px">
                      异常拜访
                    </p>
                  </van-col>
                  <!-- <van-col span="5" v-if="item.stateString == '已拜访'" @click="Visit(item)">
                    <img
                      :src="require('@/assets/icon/bfxx.png')"
                      style="margin: 0 auto; height: 18px; display: block" />
                    <p style="text-align: center; margin: 0; margin-top: 1px; font-size: 12px">
                      拜访信息
                    </p>
                  </van-col> -->
                  <van-col span="5" @click="visitFn(item)">
                    <img
                      :src="require('@/assets/icon/kehuxinxi-2.png')"
                      style="margin: 0 auto; width: 18px; display: block" />
                    <p style="text-align: center; margin: 0; margin-top: 1px; font-size: 12px">
                      客户门店
                    </p>
                  </van-col>
                </van-row>
              </div>
            </van-cell>
            <div class="lineGrey"></div>
          </div>
          <van-empty v-if="list.length == 0" />
        </van-list>
      </van-pull-refresh>
    </div>
    <van-popup v-model="showPicker" position="bottom" class="textsize">
      <van-row
        style="
          /* position: fixed; */
          /* top: 0; */
          width: 100%;
          z-index: 998;
          background-color: #fff;
          border-bottom: 1px solid #ccc;
          height: 50px;
        ">
        <van-col span="3" style="text-align: center; margin: 14px 0" @click="showPicker = false">
          <van-icon name="cross" size="20" color="#909399" />
        </van-col>
        <van-col span="13"> </van-col>
        <van-col span="4" style="text-align: center; line-height: 36px" @click="onConfirm">
          <div style="color: #0057ba">
            <van-button type="info" size="small" color="#0057ba">筛选</van-button>
          </div></van-col
        >
        <van-col span="4" style="text-align: center; line-height: 36px" @click="onsets">
          <van-button type="default" size="small" style="height: 28px">重置</van-button>
        </van-col>
      </van-row>
      <!-- <div style="height: 48px; width: 100%"></div> -->
      <div class="searchcheck" @touchmove="handleTouch">
        <p class="searchchecktitle">&nbsp;主经销商</p>
        <van-row>
          <van-col span="24">
            <div @click="moreTypeShowFn">
              <van-field
                style="
                  margin-top: -6px;
                  border-radius: 6px;
                  border: 1px solid #ccc;
                  overflow: hidden;
                "
                readonly
                v-model="chainName"
                label=""
                placeholder="请选择经销商" />
            </div>
          </van-col>
        </van-row>
        <p class="searchchecktitle" @click="isMonthVisited = !isMonthVisited">
          &nbsp;本月是否拜访<van-icon name="arrow-down" style="float: right" />
        </p>
        <van-radio-group v-model="monthVisited" direction="horizontal" class="monthVisited">
          <template v-if="isMonthVisited">
            <van-radio name="1">已拜访</van-radio>
            <van-radio name="0">未拜访</van-radio>
          </template>
        </van-radio-group>
        <van-checkbox-group v-model="result" direction="horizontal">
          <p class="searchchecktitle" @click="otherfxdShow = !otherfxdShow">
            &nbsp;身份类型<van-icon name="arrow-down" style="float: right" />
          </p>
          <div v-if="otherfxdShow" style="margin: 0 14px; width: 100%">
            <p class="searchchecktitle1" @click="otherfxdShow1 = !otherfxdShow1">
              片区经销商<van-icon name="arrow-down" style="float: right" />
            </p>
            <div v-if="otherfxdShow1">
              <div v-for="(item1, index1) in PQChain" :key="200 + index1" class="checkbox1">
                <div class="child">
                  <van-checkbox :name="item1.dictValue">{{ item1.dictLabel }}</van-checkbox>
                </div>
              </div>
              <div style="height: 2px; background-color: #f5f5f5; width: 100%; clear: both"></div>
            </div>
            <p class="searchchecktitle1" @click="otherfxdShow2 = !otherfxdShow2">
              非片区经销商<van-icon name="arrow-down" style="float: right" />
            </p>
            <div v-if="otherfxdShow2">
              <div v-for="(itemlj, indexlj) in FPQChain" :key="400 + indexlj" class="checkbox1">
                <div class="child">
                  <van-checkbox :name="itemlj.dictValue">{{ itemlj.dictLabel }}</van-checkbox>
                </div>
              </div>
              <div style="clear: both"></div>
            </div>
          </div>
          <div style="height: 2px; background-color: #f5f5f5; width: 100%; clear: both"></div>
        </van-checkbox-group>
      </div>
    </van-popup>
    <van-popup v-model="moreTypeShow" position="bottom" style="height: 80%">
      <van-row style="background-color: #f5f5f5">
        <van-col span="20">
          <van-field
            left-icon="search"
            style="margin-top: 2px; border-radius: 6px; overflow: hidden"
            v-model="CustomerName"
            label=""
            placeholder="请输入关键词"
            clearable />
        </van-col>
        <van-col span="4" style="text-align: center; line-height: 48px" @click="getCustomer">
          <div style="background-color: #0057ba; color: #fff">搜索</div></van-col
        >
      </van-row>
      <van-picker
        show-toolbar
        :columns="chainsData"
        value-key="mainCustomerName"
        @confirm="onConfirmChainsList"
        @cancel="moreTypeShow = false"
        visible-item-count="10" />
    </van-popup>
    <van-popup v-model="SKUDateShow">
      <div v-for="item in SKUList">
        <p style="font-weight: bold; font-size: 14px">&nbsp;&nbsp;&nbsp;{{ item.m01Name }}</p>
        <el-table :data="item.productDetailList" border style="width: 100%">
          <el-table-column label="物料名称" prop="productName" />
          <el-table-column label="规格" prop="productSku" />
        </el-table>
      </div>
    </van-popup>
    <!-- 测试用 -->
    <!-- 下单系统 -->
    <div
      class="storeSystem"
      v-if="objectPath"
      style="
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 9999999;
        display: flex;
        flex-direction: column;
      ">
      <div
        style="
          position: relative;
          z-index: 1;
          display: flex;
          align-items: center;
          height: 46px;
          background-color: #fff;
          font-size: 16px;
          font-weight: bold;
          justify-content: center;
        ">
        下单系统
      </div>
      <object style="flex: 1" :data="objectPath" type="text/html" width="100%"></object>
    </div>
    <tab-bar tabBarActive="agentList"></tab-bar>
  </div>
</template>

<script>
import { addVisitsPosition, mobileReposition, buryingPoint, getItemList } from '@/api/index';
import { getPosition, getTicketFun } from '@/utils/TXApiFun';
import { mapState } from 'vuex';
import store from '@/store';
import { scrollTopMixins } from '@/mixin/scrollTop';
import {
  queryMyChainsGroupList,
  queryMyChainsGroupListByDept,
  checkChainsAddressByChainCode,
  getMainchains,
} from '@/api/agentList';
import tabBar from '@/components/tabBar';
export default {
  name: 'outsidelist',
  mixins: [scrollTopMixins],
  computed: {
    ...mapState({
      deviceOutsidePage: (state) => state.isRefreshPage.deviceOutsidePage,
    }),
  },
  components: { tabBar },
  data() {
    return {
      otherShow: false,
      chainName: '',
      chainCode: '',
      showPopover: false,
      moreTypeShow: false,
      storeLabelTypes: [],
      disabled: false,
      timer: null,
      flag: true,
      show: false,
      tabVal: '1',
      list: [],
      cont: 0,
      loading: false,
      showPicker: false,
      finished: false,
      otherbqShow: true,
      otherkkdShow: true,
      otherfxdShow: true,
      otherfxdShow2: true,
      otherfxdShow1: true,
      typeName: '搜索',
      visitEndId: '',
      pageSize: 12,
      pageNum: 1,
      listActive: null,
      query: '',
      chainsName: '',
      storeType: '',
      endShow: false,
      storeCategory: '',
      fromValue: {},
      storeTypeList: [],
      PQChain: [],
      FPQChain: [],
      chainsData: [],
      serachstype: '',
      addShow1: false,
      result: [],
      StoreLabels: [],
      CustomerName: '',
      lat: '',
      lon: '',
      objectPath: '',
      isLoading: false,
      monthVisited: '', //本月是否拜访
      isMonthVisited: true,
      num: 1,
      timeData: '',
      SKUDateShow: false,
      SKUList: [],
    };
  },
  created() {
    // 当前tabs，0：销售部；1：我的
    this.tabVal = localStorage.getItem('tabVal') == '0' ? '0' : '1';
    store.dispatch('setDeviceOutsidePage', false);
    this.getMonth();
  },
  mounted() {
    if (this.deviceOutsidePage) this.initData();
  },
  mounted() {
    // 上拉边界下拉出现白色空白
    let node = document.getElementsByClassName('home')[0];
    node.addEventListener(
      'touchmove',
      (e) => {
        if (e._isScroller) return;
        e.preventDefault();
      },
      {
        passive: false,
      }
    );
  },
  methods: {
    getMonth() {
      // 获取当前日期
      var currentDate = new Date();

      // 获取当前月份
      var currentMonth = currentDate.getMonth();

      // 获取当前年份
      // var currentYear = currentDate.getFullYear();

      var previousMonthDate1 = new Date();
      if (currentDate.getDate() == 1) {
        previousMonthDate1.setMonth(currentMonth - 1);
      } else {
      }
      var previousMonth1 = previousMonthDate1.getMonth();
      var previousYear1 = previousMonthDate1.getFullYear();

      // 计算前三个月的年份和月份
      var previousMonthDate = new Date();
      if (currentDate.getDate() == 1) {
        previousMonthDate.setMonth(currentMonth - 3);
      } else {
        previousMonthDate.setMonth(currentMonth - 2);
      }
      1;
      var previousMonth = previousMonthDate.getMonth();
      var previousYear = previousMonthDate.getFullYear();

      //前三个月
      if (previousYear1 == previousYear) {
        var formattedPreviousMonth1 = previousYear1 + '-' + (previousMonth1 + 1);
        // 格式化年份和月份
        var formattedPreviousMonth = previousYear + '-' + (previousMonth + 1);
        this.timeData =
          formattedPreviousMonth.split('-')[1] + '-' + formattedPreviousMonth1.split('-')[1] + '月';
      } else {
        var formattedPreviousMonth1 = previousYear1 + '年' + (previousMonth1 + 1) + '月';
        // .toString().padStart(2, '0');
        // 格式化年份和月份
        var formattedPreviousMonth = previousYear + '年' + (previousMonth + 1) + '月';
        this.timeData = formattedPreviousMonth + '-' + formattedPreviousMonth1;
      }
    },
    onRefresh() {
      this.onSearch();
      this.isLoading = false;
    },
    handleTouch(e) {
      e._isScroller = true;
    },
    initData() {
      // 筛选-门店标签
      if (localStorage.getItem('outvstoreLabelTypes') != null) {
        this.storeLabelTypes = localStorage.getItem('outvstoreLabelTypes').split(',');
      } else {
        this.storeLabelTypes = [];
      }
      this.chainName = localStorage.getItem('outvchainName'); //筛选-经销商名称搜索
      this.chainCode = localStorage.getItem('outvchainCode'); //筛选-经销商Code
      // 筛选-店型选择
      if (localStorage.getItem('outvstoreCategoryList') != null) {
        this.result = localStorage.getItem('outvstoreCategoryList').split(',');
      } else {
        this.result = [];
      }
      this.query = this.$route.query; // 路由参数
      localStorage.removeItem('visitId');
      if (localStorage.getItem('postType') == 'GZ') {
        this.addShow1 = false;
        this.otherShow = true; //筛选-其他
      } else {
        this.addShow1 = true;
        this.otherShow = false; //筛选-其他
      }
      this.onSearch();
    },
    setStroeNameStyle(item) {
      return { color: '#0057ba', 'text-decoration': 'underline' };
    },
    clearFn() {
      this.chainsName = '';
      localStorage.setItem('outvstoreName', '');
    },
    moreTypeShowFn() {
      this.moreTypeShow = true;
      this.getCustomer();
    },
    buryingPoint(val) {
      buryingPoint(val);
    },
    getCustomer() {
      getMainchains({ mainChainsName: this.CustomerName }).then((request) => {
        this.chainsData = request.data;
        this.chainsData.push({});
        this.chainsData.pop();
      });
    },
    onConfirmChainsList(value) {
      if (value.mainCustomerName != undefined) {
        this.chainName = value.mainCustomerName;
        this.chainCode = value.mainCustomerCode;
      }
      this.showPickerChainsList = false;
      this.moreTypeShow = false;
    },
    onConfirm(value) {
      this.showPicker = false;
      this.onSearchm();
    },
    onsets() {
      this.result = [];
      this.storeLabelTypes = [];
      this.chainName = '';
      this.chainCode = '';
      this.monthVisited = '';
      this.onSearch();
    },
    setChainTypeList() {
      if (store.getters.chainsType) {
        this.PQChain = store.getters.chainsType.filter((val) => val.remark == 'pq');
        this.FPQChain = store.getters.chainsType.filter((val) => val.remark == 'fp');
      }
    },
    searchFn() {
      //获取门店类型  //获取门店标签
      Promise.all([this.setChainTypeList()]).then(() => {
        this.showPicker = true;
        this.CustomerName = '';
      });
    },
    getUserOrgStoreList() {
      this.storeType = localStorage.getItem('storeType');
      this.endShow = false;
      if (this.refreshing) {
        this.list = [];
        this.refreshing = false;
      }
      this.disabled = true;
      this.toastLoading(0, '加载中...', true);
      queryMyChainsGroupListByDept({
        lat: this.lat,
        lon: this.lon,
        pageNum: this.pageNum,
        typeCode2List: this.result.join(','),
        pageSize: this.pageSize,
        chainsName: this.chainsName.trim(),
        monthVisited: this.monthVisited, //本月是否拜访1=拜访，0=未拜访
        mainCustomerCode: this.chainCode, //主经销商编号
      }).then((res) => {
        this.disabled = false;
        this.toastLoading().clear();
        this.loading = false;
        if (res.code == 200) {
          if (this.pageNum == '1') {
            this.list = [];
          }

          this.list = this.list.concat(res.rows);
          if (this.list.length >= res.total) {
            this.finished = true;
          } else {
            this.finished = false;
          }
          this.pageNum = this.pageNum + 1;
          this.list.forEach((item) => {
            if (item.stateString.indexOf('拜访中') != -1) {
              this.endShow = true;
              this.visitEndId = item.visitId;
              return;
            }
          });
        } else {
          this.$toast(res.msg);
        }
      });
    },
    getUserOutPlaListFun() {
      this.storeType = localStorage.getItem('storeType');
      this.disabled = true;
      this.toastLoading(0, '加载中...', true);
      this.endShow = false;
      if (this.refreshing) {
        this.list = [];
        this.refreshing = false;
      }
      queryMyChainsGroupList({
        lat: this.lat,
        lon: this.lon,
        pageNum: this.pageNum,
        typeCode2List: this.result.join(','),
        pageSize: this.pageSize,
        chainsName: this.chainsName.trim(),
        monthVisited: this.monthVisited, //本月是否拜访1=拜访，0=未拜访
        mainCustomerCode: this.chainCode, //主经销商编号
      }).then((res) => {
        this.disabled = false;
        this.toastLoading().clear();
        this.loading = false;
        if (res.code == 200) {
          this.list = this.list.concat(res.rows);
          if (this.list.length >= res.total) {
            this.finished = true;
          } else {
            this.finished = false;
          }
          this.pageNum = this.pageNum + 1;
          this.list.forEach((item) => {
            if (item.stateString.indexOf('拜访中') != -1) {
              this.endShow = true;
              this.visitEndId = item.visitId;
              return;
            }
          });
        } else {
          this.finished = true;
          this.$toast(res.msg);
        }
      });
    },
    // 进入拜访
    storeVisit(val) {
      this.toastLoading(0, '加载中...', true);
      localStorage.setItem('tabVal', this.tabVal);
      localStorage.removeItem('visitId');
      this.buryingPoint({
        systemModel: '计划外',
        buryingPointType: 1,
        buryingPointValue: val.chainName + '(' + val.chainCode + ')',
        buryingPointName: '进店拜访',
        buryingPointPosition: this.tabVal == 1 ? '我的' : '销售部',
      });
      getPosition()
        .then((res) => {
          let { TXisBD, resData } = res;
          this.lat = TXisBD.lat;
          this.lon = TXisBD.lon;
          localStorage.setItem('lat', this.lat);
          localStorage.setItem('lon', this.lon);
          // var location = this.CJ02BD(res.latitude, res.longitude);
          if (val.stateString.indexOf('拜访中') != -1) {
            localStorage.setItem('startTime', new Date());
            localStorage.setItem('ORGName', val.deptName);
            localStorage.setItem('chainNameR', val.chainName);
            localStorage.removeItem('visitId'); //删除上次拜访id
            this.toastLoading().clear();
            this.$router.push({
              path: '/visitPage',
              query: {
                typeName2: val.typeName2,
                chainId: val.chainId,
                rdId: val.rdId,
                customerManager: val.customerManager,
                openDate: val.openDate,
                close: val.close,
                freeze: val.freeze,
                lat: TXisBD.lat,
                lon: TXisBD.lon,
                visitId: val.visitId,
                pageType: 'out',
                addressLine: val.addressLine,
                storeCategory: val.storeCategory,
                chainName: val.chainName,
                hisTime: val.hisTime,
                contactName: val.contactName,
                chainCode: val.chainCode,
                tabVal: this.tabVal,
                visitModel: '1',
                latNew: TXisBD.lat,
                lonNew: TXisBD.lon,
                PointSum: '0',
                marklat: resData.latitude,
                marklon: resData.longitude,
                from: 'outPlan',
              },
            });
          } else {
            this.checkStoreAddressByStoreCodeFun(val, TXisBD, resData);
          }
        })
        .catch((error) => {
          this.toastLoading().clear();
          this.$dialog.alert({
            message: error,
          });
        });
    },
    checkStoreAddressByStoreCodeFun(val, location, res) {
      checkChainsAddressByChainCode({
        chainCode: val.chainCode,
        lon: location.lon,
        lat: location.lat,
      })
        .then((response) => {
          this.toastLoading().clear();
          if (val.lat == '' || val.lat == null) {
            this.lat = location.lat;
            this.lon = location.lon;
          }
          let PointSumval = this.twoPointSum(
            location.lat,
            location.lon,
            location.lat,
            location.lon
          ).toFixed(2);
          //  直接进入拜访 不校验经纬度
          // localStorage.setItem('startTime', new Date());
          // localStorage.setItem('ORGName', val.deptName);
          // localStorage.setItem('chainNameR', val.chainName);
          // this.toSuishenbangOutstoreVisit(res, val, location, PointSumval);
          // return;
          // 门店校验 地址不通过
          if (response.code != 200) {
            // updateAddress : ，1：同城AB+金牌,去修改地址;2:非金牌店铺，非同城店铺偏差过大不允许拜访，可以重置定位;0非金牌店铺，非同城店铺 位置信息不存在 可以继续拜访
            if (response.data.updateAddress == 0) {
              // 非金牌店铺，非同城店铺 位置信息不存在 可以继续拜访
              this.$dialog
                .confirm({
                  confirmButtonText: '确定拜访',
                  cancelButtonText: '取消拜访',
                  title: '系统提示',
                  message:
                    '该客户没有经纬度，此次拜访会保存定位点作为客户经纬度，下次拜访时判断是否偏差过大。',
                  closeOnClickOverlay: true,
                })
                .then(() => {
                  this.toSuishenbangOutstoreVisit(res, val, location, 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: val.chainId,
                        type: 'address',
                        storeAddressId: val.storeAddressId,
                      },
                    });
                  });
              } else {
                this.$dialog.confirm({
                  title: '系统提示',
                  message: '已经达到最大修改次数',
                  messageAlign: 'left',
                  confirmButtonText: '确定',
                });
              }
            } else if (response.data.updateAddress == 2) {
              // 1.非金牌店铺，非同城店铺 位置偏差过大 重置经纬度
              this.resetCoord(res, val, location, PointSumval);
              return;
            }
          } else {
            // 门店编码校验门店地址通过 进入拜访
            this.toSuishenbangOutstoreVisit(res, val, location, PointSumval);
          }
        })
        .catch(() => {
          this.toastLoading().clear();
        });
    },
    // 重置经纬度
    resetCoord(res, val, location, PointSumval) {
      this.$dialog
        .confirm({
          confirmButtonText: '初始化定位',
          cancelButtonText: '取消拜访',
          title: '系统提示',
          message: '偏差过大，不允许拜访。可修改本店定位.',
          closeOnClickOverlay: true,
        })
        .then(() => {
          mobileReposition({
            chainId: val.chainId,
            lat: location.lat,
            lon: location.lon,
          }).then((response) => {
            if (response.code == 200) {
              this.$dialog
                .alert({
                  title: '系统提示',
                  message: '本信息定位已更新成功!',
                })
                .then(() => {
                  this.toSuishenbangOutstoreVisit(res, val, location, PointSumval);
                });
              localStorage.setItem('startTime', new Date());
              localStorage.setItem('ORGName', val.deptName);
              localStorage.setItem('chainNameR', val.chainName);
            } else {
              this.$toast(response.msg);
            }
          });
        });
    },
    // 进入拜访 router.push
    toSuishenbangOutstoreVisit(res, val, location, PointSumval) {
      addVisitsPosition({
        chainId: val.chainId,
        visitsId: '',
        lon: res.longitude,
        lat: res.latitude,
        sourceLon: location.lon,
        sourceLat: location.lat,
        positionDesc: '',
        accuracy: res.accuracy,
      }).then((response) => {
        // 进入拜访之前先刷新页面
        store.dispatch('setDeviceOutsidePage', true);
        localStorage.removeItem('visitId'); //删除上次拜访id
        this.$router.push({
          path: '/visitPage',
          query: {
            typeName2: val.typeName2,
            chainId: val.chainId,
            rdId: val.rdId,
            customerManager: val.customerManager,
            openDate: val.openDate,
            close: val.close,
            freeze: val.freeze,
            lat: location.lat,
            lon: location.lon,
            visitId: val.visitId,
            pageType: 'out',
            addressLine: val.addressLine,
            storeCategory: val.storeCategory,
            chainName: val.chainName,
            hisTime: val.hisTime,
            contactName: val.contactName,
            chainCode: val.chainCode,
            tabVal: this.tabVal,
            visitModel: '1',
            latNew: location.lat,
            lonNew: location.lon,
            PointSum: PointSumval,
            marklat: res.latitude,
            marklon: res.longitude,
            from: 'outPlan',
          },
        });
      });
    },
    // 异常拜访
    abnormalVisit(val) {
      localStorage.removeItem('visitId');
      localStorage.setItem('tabVal', this.tabVal);
      this.buryingPoint({
        systemModel: '计划外',
        buryingPointType: 1,
        buryingPointValue: val.chainName + '(' + val.chainCode + ')',
        buryingPointName: '异常拜访',
        buryingPointPosition: this.tabVal == 1 ? '我的' : '销售部',
      });
      getPosition()
        .then((res) => {
          let { TXisBD, resData } = res;
          this.lat = TXisBD.lat;
          this.lon = TXisBD.lon;
          localStorage.setItem('lat', this.lat);
          localStorage.setItem('lon', this.lon);
          let PointSum = this.twoPointSum(TXisBD.lat, TXisBD.lon, TXisBD.lat, TXisBD.lon).toFixed(
            2
          );
          addVisitsPosition({
            chainId: val.chainId,
            visitsId: '',
            lon: resData.longitude,
            lat: resData.latitude,
            sourceLon: location.lon,
            sourceLat: location.lat,
            positionDesc: '',
            accuracy: resData.accuracy,
          }).then((response) => {
            // 进入拜访之前先刷新页面
            store.dispatch('setDeviceOutsidePage', true);
            this.$router.push({
              path: '/visitAbnormal',
              query: {
                chainId: val.chainId,
                rdId: val.rdId,
                lat: this.lat,
                lon: this.lon,
                visitId: val.visitId,
                pageType: 'out',
                visitModel: localStorage.getItem('postType') != 'GZ' ? '5' : '3',
                chainCode: val.chainCode,
                tabVal: this.tabVal,
                latNew: TXisBD.lat,
                lonNew: TXisBD.lon,
                PointSum: PointSum,
                marklat: resData.latitude,
                marklon: resData.longitude,
              },
            });
            localStorage.setItem('startTime', new Date());
            localStorage.setItem('ORGName', val.deptName);
            localStorage.setItem('chainNameR', val.chainName);
          });
        })
        .catch((error) => {
          this.$dialog.alert({
            message: error,
          });
        });
    },
    // 客户门店
    visitFn(val) {
      this.buryingPoint({
        systemModel: '计划外',
        buryingPointType: 1,
        buryingPointValue: val.chainName + '(' + val.chainCode + ')',
        buryingPointName: '客户信息',
        buryingPointPosition: this.tabVal == 1 ? '我的' : '销售部',
      });
      window.location.href =
        process.env.VUE_APP_SSB_LINK +
        '/order/storeDetail/list?customerCode=' +
        val.chainCode +
        '&status=jxs';
    },
    // 拜访信息
    Visit(val) {
      this.$router.push({
        path: '/historicalDetails',
        query: {
          visitId: val.visitId,
          chainId: val.chainId,
          chainCode: val.chainCode,
        },
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    onSearch() {
      this.pageNum = 1;
      this.list = [];
      this.finished = true;
      this.onLoad();
    },
    onSearchm() {
      localStorage.setItem('outvstoreName', this.chainName);
      localStorage.setItem('outvchainName', this.chainName);
      localStorage.setItem('outvstoreLabelTypes', this.storeLabelTypes);
      localStorage.setItem('outvstoreCategoryList', this.result);
      localStorage.setItem('outvchainCode', this.chainCode);
      this.onSearch();
    },
    tabChange(name) {
      this.finished = true;
      this.pageNum = 1;
      this.list = [];
      this.tabVal = name;
      localStorage.setItem('tabVal', name);
      this.onLoad();
    },
    // 滚动条与底部距离小于 offset 时触发 初始化会触发
    onLoad() {
      this.toastLoading(0, '加载中...', true);
      // 授权
      getTicketFun()
        .then(() => {
          getPosition(true)
            .then((res) => {
              let { TXisBD } = res;
              this.lat = TXisBD.lat;
              this.lon = TXisBD.lon;
              if (this.tabVal == '1') {
                this.getUserOutPlaListFun();
              } else {
                this.getUserOrgStoreList();
              }
            })
            .catch((error) => {
              this.$dialog.alert({
                message: error,
              });
            });
        })
        .catch(() => {
          this.finished = true;
        });
    },
    // 跳转好帮手门店详情
    goOtherSystem(item) {
      if (item.chainCode) {
        window.location.href =
          process.env.VUE_APP_SSB_LINK +
          '/order/customerDetail/index?customerCode=' +
          item.mainCustomerCode;
      } else {
        this.$dialog.alert({
          message: '缺少门店code',
        });
      }
    },
    login() {
      if (this.num > 5) {
        this.$router.push('/login');
      } else {
        this.num = this.num + 1;
      }
    },
    linkList(val) {
      getItemList({ storeCode: val.chainId }).then((res) => {
        if (res.code == 200) {
          this.SKUDateShow = true;
          this.SKUList = res.data;
        } else {
          this.$toast.fail(res.msg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.bgcolor {
  background-color: #f5f5f5;
}
.card {
  padding: 10px 16px;
  box-sizing: border-box;
}
.card .title {
  font-size: 15px;
  font-weight: bold;
  color: #333;
  line-height: 22px;
  padding-right: 52px;
}
.card .info {
  font-size: 14px;
  color: #909090;
  line-height: 26px;
}
.btnbox {
  padding-top: 14px;
  border-top: 1px solid #eee;
  margin: 0 10px;
}
.statstext {
  background-color: #0057ba;
  position: absolute;
  right: 0;
  top: 6px;
  padding: 2px 6px 2px 12px;
  border-bottom-left-radius: 60px;
  border-top-left-radius: 60px;
  color: #fff;
}
.cellcontent .van-cell {
  padding-bottom: 10px;
}
.statstext .van-icon__image {
  height: 0.7em;
}
.home {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .content {
    flex: 1;
    overflow: hidden;
    padding: 10px 0;
    .van-pull-refresh {
      height: 100%;
      overflow-y: auto;
      .van-pull-refresh__track {
      }
    }
  }
}
.monthVisited {
  margin: 0px 14px;
  .van-radio {
    width: 50%;
    margin: 0;
  }
}
</style>
<style lang="scss">
.van-tabs__nav--card .van-tab.van-tab--active {
  background-color: #0057ba !important;
}
.zDialog .van-dialog__header {
  padding: 10px;
  border-bottom: 1px solid #f5f5f5;
}
.zDialog .infoText {
  margin: 10px;
  font-size: 14px;
  color: #909090;
  width: 98%;
}
.visitStoreIco {
  float: left;
  float: left;
  width: 26px;
  text-align: center;
  background-color: #ffba13;
  color: #fff;
  border-radius: 100%;
  margin-left: 14px;
  line-height: 26px;
  height: 26px;
}
.searchcheck {
  padding: 0 10px 10px;
}
.searchcheck .van-checkbox {
  /*width: 44%;*/
  padding-bottom: 10px;
}
.searchcheck .checkbox {
  font-size: 14px;
  display: inline-block;
  width: 50%;
  line-height: 28px;
}
.searchcheck .checkbox .van-checkbox {
  margin-bottom: 2px;
}
.searchcheck .checkbox1 {
  font-size: 14px;
  float: left;
  line-height: 28px;
  width: 50%;
}
.searchcheck .checkbox1 .child {
  width: 100%;
}
.searchcheck {
  /* height: 93vh;
  overflow-y: auto; */
}
.searchchecktitle {
  width: 100%;
  margin: 20px 0;
  font-size: 16px;
  border-left: 3px solid #0057ba;
  line-height: 18px;
}
.searchchecktitle1 {
  width: 100%;
  margin: 20px 0;
  font-size: 16px;
  line-height: 18px;
}
.textsize {
  font-size: 14px;
  /* overflow: hidden; */
  display: flex;
  flex-direction: column;
  .searchcheck {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 50px;
  }
}
.home {
  .TCFXListItem {
    display: inline-block;
    border: 1px solid #ccc;
    padding: 3px 5px;
    margin: 0 5px;
    border-radius: 6px;
  }
}
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #0057ba;
}
.searchDiv {
  .van-search {
    background: #fff;
  }
  .van-search__action {
    font-size: 14px;
    color: #0057ba;
    font-weight: bold;
    background: #f1f1f1;
    border-bottom-right-radius: 60px;
    border-top-right-radius: 60px;
    border: 1px solid #ccc;
    padding: 0 20px;
  }
  .van-search--show-action {
    padding-right: 12px;
  }
  .van-search__content {
    border: 1px solid #ccc;
    border-bottom-left-radius: 60px;
    border-top-left-radius: 60px;
    background: #f1f1f1;
    border-right: 0;
  }
}
.myTab {
  .van-tabs__nav--card {
    margin: 0 !important;
    border-left: 0;
    border-right: 0;
  }
  .van-tabs__wrap,
  .van-tabs__nav--card {
    height: 39px;
  }
  .van-tab {
    line-height: 40px;
  }
}
.myList {
  padding-bottom: 50px;
  .van-cell {
    padding: 0;
    &:after {
      border-bottom: none;
    }
  }
}
</style>
