<template>
  <div class="storeVisit">
    <div class="navBarTOP">
      <van-nav-bar class="navBar" title="拜访" left-arrow @click-left="onClickLeft"></van-nav-bar>
    </div>
    <div class="container">
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <div class="lineGrey"></div>
      <div class="card mt10">
        <div class="title f-blue">
          <span
            @click="goOtherSystem"
            :class="{
              'to-other-system': isToOtherSystem,
            }">
            {{ storeName }}
            (
            <span style="color: #0057ba">
              {{ urlParameter.storeCode }}
            </span>
            )
          </span>
        </div>
        <div class="info1 storeCategory" v-if="insert">
          <div class="storeType">类型：{{ storeCategory }}</div>
          <van-button
            type="info"
            style="background: #ed5565; border-color: #ed5565; color: #fff; border-radius: 5px"
            size="small"
            plain
            class="centerBtn"
            @click="onstopVisit">
            取消拜访
          </van-button>
        </div>
        <div class="info1" v-if="addressLine != null">地址：{{ addressLine }}</div>
        <div class="info1" v-if="notes != null && insert">上次拜访备注：{{ notes }}</div>
        <div class="info1" v-if="timeShow">拜访时长：{{ showTime }}</div>
        <div class="info1" v-if="insert">上次拜访时间：{{ parseTime(urlParameter.genDate) }}</div>
        <div class="info1 visitsRemarks" v-if="visitsRemarks">
          <span @click="shows = true" class="f-blue" style="font-weight: bold">
            <van-icon name="browsing-history-o" />查看最近三次
          </span>
          <van-button
            type="info"
            style="background: rgb(0, 87, 186); color: #fff; border-radius: 5px"
            size="small"
            plain
            v-if="showOrderButton"
            class="centerBtn"
            @click="overbookingFn(urlParameter)">
            去下单
          </van-button>
        </div>
        <div class="btnBox">
          <!-- <van-button
          type="info"
          style="background: rgb(0, 87, 186); color: #fff; margin: 10px 0; border-radius: 5px"
          size="small"
          plain
          class="centerBtn"
          @click="visitFn(urlParameter.storeCode)"
          >经营情况</van-button
        > -->
          <!-- <van-button
          type="info"
          style="background: rgb(0, 87, 186); color: #fff; margin: 10px; border-radius: 5px"
          size="small"
          plain
          class="centerBtn"
          @click="wuliaoLog(urlParameter)"
          >物料历史</van-button
        > -->
        </div>
      </div>
      <div v-if="addShow1" style="padding: 10px; background-color: #f5f5f5">
        <!-- <van-icon name="info-o" /> -->
        <p style="margin: 5px 0; color: red; font-size: 12px">
          1、已启动SKU图像识别，目前覆盖桶装和战略产品158个
        </p>
        <p style="margin: 5px 0; color: red; font-size: 12px">
          2、请在"生动化陈列”中拍全本店陈列的所有产品+道具
        </p>
        <p style="margin: 5px 0; color: red; font-size: 12px">
          3、提交拜访后约30秒，在拜访门店列表或历史拜访中查看完美门店报告
        </p>
      </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' || item.isMust == '2'">*</span>
          <span class="must" v-show="item.isMust != '0' && item.isMust != '2'">&nbsp;</span>
          <p style="width: 72%; margin: 0; line-height: 24px; display: inline-block">
            {{ item.taskName }}
          </p>
          <span v-show="item.processKey != null" class="processIco">
            <span v-show="item.processKey == 1" style="color: #0057ba; font-size: 12px"
              >审批中</span
            >
            <span v-show="item.processKey == 2" style="color: #07c160; font-size: 12px"
              >审批完成</span
            >
            <span v-show="item.processKey == 3" style="color: red; font-size: 12px">拒绝</span>
            <van-icon :name="sp" size="16" style="float: right; margin-left: 6px" />
          </span>
          <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" v-if="insert">
      <!--      &&!LCshow-->
      <van-button class="submitBtn" block type="info" color="#0057ba" @click="endVisitsFn"
        >提交拜访</van-button
      >
    </div>
    <div class="tc" style="padding: 0 16px" v-if="restartProcessButtion">
      <van-button class="submitBtn" block type="info" color="#0057ba" @click="endVisitsFn('t')"
        >重新提交</van-button
      >
    </div>
    <!--    <div class="tc" style="padding: 0 16px" v-if="LCshow">-->
    <!--      <van-button class="submitBtn"  block type="info" color="#0057ba" @click="endVisitsFn('t')">退回提交</van-button>-->
    <!--    </div>-->
    <br />
    <van-dialog v-model="shows">
      <div class="tipTitleBox" style="padding: 10px">
        <p class="p">近三次拜访备注</p>
        <div
          v-for="item in visitsRemarks"
          style="border-bottom: 1px solid #e8e8e8; font-size: 14px; padding: 10px 0">
          <p>拜访时间：{{ item.stopTime }}</p>
          <p>备注：{{ item.visitRemark }}</p>
        </div>
      </div>
    </van-dialog>
    <div id="allmap"></div>
    <!-- 物料历史列表 -->
    <el-dialog
      :visible.sync="wuliaoTable"
      width="90%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="wuliaoTableClose"
      custom-class="wuliaoTable">
      <el-table :data="wuliaoList" border style="width: 100%">
        <el-table-column label="物料名称" prop="materialDataName" align="center" />
        <el-table-column label="发放时间" prop="issuerTime" align="center" />
        <el-table-column label="数量" prop="inventoryNum" width="60" align="center" />
        <el-table-column label="签收状态" prop="receiptState" width="60" align="center" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStoreGroupTask,
  endVisits,
  editDwellTime,
  suishenbangStoreSale,
  stopVisit,
  restartProcess,
  buryingPoint,
  getMaterialHistory,
  getVisitTasks,
  getCljlaToDBLabel,
} from '@/api/index';
import axios from 'axios';
import sp from './../../assets/sp.png';
import { saveVisitsParams, getOrderUrlByStoreId } from '@/api/inventory';
export default {
  name: 'storeVisitpage',
  data() {
    return {
      notes: '',
      shows: false,
      visitModel: '1',
      sp: sp,
      imgs: [],
      addShow1: false,
      html: '',
      LCshow: false,
      normalshow: true,
      timeShow: false,
      iscuxiao: false,
      text: '',
      radio: '',
      isEdit: false,
      storeId: '',
      rdId: '',
      lat: '',
      lon: '',
      timer: null,
      flag: true,
      list: [],
      storeGroupId: '',
      visitId: '',
      addressLine: '',
      storeCategory: '',
      storeName: '',
      contactName: '',
      insert: true,
      showTime: '00:00:00',
      startTime: null,
      visitsRemarks: [],
      location: {
        lat: '34.6174',
        lon: '112.44039',
      },
      address: '',
      city: '',
      locationAccuracy: '',
      uType: '-1',
      showOrderButton: null,
      restartProcessButtion: false,
      wuliaoTable: false,
      wuliaoList: [],
      urlParameter: {},
      isToOtherSystem: false,
    };
  },
  created() {
    // this.urlParameter = this.$route.query;
    // this.storeId = this.$route.query.storeId + '';
    // this.visitId = this.$route.query.visitId;
    // this.rdId = this.$route.query.rdId + '';
    // 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.visitModel = this.$route.query.visitModel + '';
    // this.lat = this.$route.query.lat + '';
    // this.lon = this.$route.query.lon + '';
    // sessionStorage.setItem('visitModel', '1');
    // this.uType = localStorage.getItem('uType');
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == '/deviceWithin/index' && from.path == '/storeVisitpage') {
      if (this.visitId != null && this.visitId != '') {
        this.editDwellTimes();
      }
    }
    next();
  },
  activated() {
    // 是否请求任务列表接口
    let getRequestFlage = localStorage.getItem('getRequestFlage');
    if (getRequestFlage != 'true') return;
    this.urlParameter = this.$route.query;
    this.storeId = this.$route.query.storeId + '';
    this.visitId = this.$route.query.visitId;
    this.rdId = this.$route.query.rdId + '';
    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.visitModel = this.$route.query.visitModel + '';
    this.lat = this.$route.query.lat + '';
    this.lon = this.$route.query.lon + '';
    // this.list = [];
    this.uType = localStorage.getItem('uType');
    this.list = [];
    this.isToOtherSystem = false;
    if (this.$route.query.type != 'edit') {
      this.timeShow = true;
      if (localStorage.getItem('visitId') != null) {
        this.visitId = localStorage.getItem('visitId');
        setTimeout(() => {
          this.addVisits();
        });
      } else {
        setTimeout(() => {
          this.addVisits();
        });
      }
    } else {
      this.timeShow = false;
      this.addVisits();
    }
  },
  methods: {
    animation() {
      var times = new Date().getTime() - new Date(this.startTime).getTime();
      var house = Math.floor(times / 3600000); //毫秒转化为分钟
      var minutes = Math.floor(times / 60000 - house * 60); //毫秒转化为分钟
      var minutes1 = Math.floor(times / 60000); //毫秒转化为分钟
      var seconds = Math.floor((times - minutes1 * 60000) / 1000); //已知分钟将time减去分钟 除去1000得出 秒
      var ms = Math.floor((times - minutes1 * 60000 - seconds * 1000) / 10); //
      this.showTime =
        (house < 10 ? '0' + house : house) +
        ':' +
        (minutes < 10 ? '0' + minutes : minutes) +
        ':' +
        (seconds < 10 ? '0' + seconds : seconds);
      // +":"
      // +(ms<10 ? "0"+ms : ms);
    },
    overbookingFn(val) {
      buryingPoint({
        systemModel: '拜访页',
        buryingPointType: 1,
        buryingPointValue: val.storeName + '(' + val.storeCode + ')',
        buryingPointName: '去下单',
        buryingPointPosition: '拜访页',
      });
      this.toastLoading(0, '加载中...', true);
      getOrderUrlByStoreId({
        storeId: this.$route.query.storeId,
        from: this.$route.query.from,
      }).then((res) => {
        this.toastLoading().clear();
        if (res.code == 200 && res.data) {
          window.location.href = res.data;
        } else {
          this.Toast({
            message: res.msg,
            duration: 5000,
          });
        }
      });
    },
    // 结束拜访
    onstopVisit() {
      this.$dialog
        .confirm({
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          title: '系统提示',
          message: '取消拜访会清空填写的拜访内容和照片，是否确认？',
        })
        .then(() => {
          buryingPoint({
            systemModel: '拜访页',
            buryingPointType: 1,
            buryingPointValue:
              this.urlParameter.storeName + '(' + this.urlParameter.storeCode + ')',
            buryingPointName: '取消拜访',
            buryingPointPosition: '拜访页',
          });
          stopVisit({ visitsId: this.visitId }).then((res) => {
            if (res.code == 200) {
              this.$dialog
                .alert({
                  title: '系统提示',
                  message: '拜访中任务结束成功！',
                })
                .then(() => {
                  window.location.replace(
                    window.location.origin + this.locationOrigin + '/deviceWithin/index',
                  );
                });
            } else {
              this.$toast(res.msg);
            }
          });
        });
    },
    editDwellTimes() {
      let dwellTime = this.weekend(localStorage.getItem('startTime'), new Date()) + '';
      editDwellTime({ dwellTime: dwellTime, visitsId: this.visitId }).then((res) => {
        if (res.code != 200) {
          this.$toast.fail(res.msg);
        }
        localStorage.removeItem('visitId');
      });
    },
    visitFn(val) {
      var that = this;
      suishenbangStoreSale({ storeCode: val }).then((res) => {
        if (res.code == 200) {
          if (res.data.num != '0') {
            window.location.href =
              process.env.VUE_APP_SSB_LINK + '/order/storeDetail/index?shopCode=' + val;
          } else {
            that.$toast(res.data.msg);
          }
        }
      });
    },
    weekend(time1) {
      var arrtime1 = new Date(time1).getTime();
      var arrtime2 = new Date().getTime();
      return Math.round((arrtime2 - arrtime1) / 1000);
    },
    addVisits() {
      var that = this;
      var insert = '';
      var postType = localStorage.getItem('postType');
      if (postType == 'GZ') {
        this.addShow1 = false;
      } else {
        this.addShow1 = true;
      }
      // this.LCshow=this.$route.query.LCshow
      if (this.$route.query.type == 'edit') {
        insert = false;
      } else {
        insert = true;
      }
      this.insert = insert;
      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);
          let recommend = '';
          if (addresses) {
            recommend = addresses.recommend;
          }
          if (that.$route.query.type == 'edit') {
            var params = {
              storeId: that.storeId,
              storeCode: that.urlParameter.storeCode,
              visitEntry: '0',
              lat: '',
              lon: '',
              visitModel: that.visitModel,
              routeDetailsId: '',
              storeGroupId: that.urlParameter.storeGroupId,
              visitSource: '1',
              insert: insert,
              locationCity: '',
              locationRemark: recommend,
              locationAccuracy: that.urlParameter.PointSum,
              province: address_component.province,
              city: address_component.city,
              district: address_component.district,
            };
            that.locationAccuracy = '';
            that.city = '';
            that.address = '';
            if (that.visitId != null) {
              params.id = that.visitId;
            }
            let loading2 = that.$toast.loading({
              duration: 0,
              message: '加载中...',
              forbidClick: true,
            });
            that.list = [];
            getVisitTasks(params).then((res) => {
              loading2.clear();
              if (res.code == 200) {
                that.notes = res.data.notes;
                that.restartProcessButtion = res.data.restartProcessButtion;
                if (res.data.visitId != undefined) {
                  localStorage.setItem('visitId', res.data.visitId);
                  that.visitId = res.data.visitId;
                }
                that.list = that.filterSfaTaskList(res.data.sfaTaskList);
                that.storeGroupId = res.data.storeGroupId;
                that.showOrderButton = res.data.showOrderButton;
                that.startTime = res.data.startTime;
                that.timeN = setInterval(that.animation, 16);
                that.visitsRemarks = res.data.visitsRemarks;
                let sfaStoreType = res.data.sfaStoreType;
                if (
                  (sfaStoreType && (sfaStoreType.jz || sfaStoreType.gz)) ||
                  res.data.approvalStatus == null ||
                  res.data.approvalStatus == 0
                ) {
                  that.isToOtherSystem = false;
                } else {
                  that.isToOtherSystem = true;
                }
              }
            });
          } else {
            var params = {
              storeId: that.storeId,
              storeCode: that.urlParameter.storeCode,
              visitEntry: '0',
              lat: that.urlParameter.latNew,
              lon: that.urlParameter.lonNew,
              visitModel: that.visitModel,
              routeDetailsId: that.rdId,
              visitSource: '1',
              insert: insert,
              locationCity: '',
              locationRemark: recommend,
              locationAccuracy: that.urlParameter.PointSum,
              province: address_component.province,
              city: address_component.city,
              district: address_component.district,
            };
            that.locationAccuracy = that.urlParameter.PointSum;
            that.city = '';
            that.address = recommend;
            localStorage.setItem('address', '');
            if (that.visitId != null) {
              params.id = that.visitId;
            }
            let loading2 = that.$toast.loading({
              duration: 0,
              message: '加载中...',
              forbidClick: true,
            });
            that.list = [];
            getVisitTasks(params).then((res) => {
              loading2.clear();
              if (res.code == 200) {
                that.notes = res.data.notes;
                that.restartProcessButtion = res.data.restartProcessButtion;
                if (res.data.visitId != undefined) {
                  localStorage.setItem('visitId', res.data.visitId);
                  that.visitId = res.data.visitId;
                }
                that.list = that.filterSfaTaskList(res.data.sfaTaskList);
                that.storeGroupId = res.data.storeGroupId;
                that.showOrderButton = res.data.showOrderButton;
                that.startTime = res.data.startTime;
                that.timeN = setInterval(that.animation, 16);
                that.visitsRemarks = res.data.visitsRemarks;
                let sfaStoreType = res.data.sfaStoreType;
                if (
                  (sfaStoreType && (sfaStoreType.jz || sfaStoreType.gz)) ||
                  res.data.approvalStatus == null ||
                  res.data.approvalStatus == 0
                ) {
                  that.isToOtherSystem = false;
                } else {
                  that.isToOtherSystem = true;
                }
              } else {
                this.$toast(res.msg);
              }
            });
          }
        },
        function (err) {
          if (that.$route.query.type == 'edit') {
            var params = {
              storeId: that.storeId,
              storeCode: that.urlParameter.storeCode,
              visitEntry: '0',
              lat: '',
              lon: '',
              visitModel: that.visitModel,
              routeDetailsId: '',
              storeGroupId: that.urlParameter.storeGroupId,
              visitSource: '1',
              insert: insert,
              locationCity: '',
              locationRemark: '',
              locationAccuracy: that.urlParameter.PointSum,
            };
            that.locationAccuracy = '';
            that.city = '';
            that.address = '';
            if (that.visitId != null) {
              params.id = that.visitId;
            }
            let loading2 = that.$toast.loading({
              duration: 0,
              message: '加载中...',
              forbidClick: true,
            });
            that.list = [];
            getVisitTasks(params).then((res) => {
              loading2.clear();
              if (res.code == 200) {
                that.notes = res.data.notes;
                that.restartProcessButtion = res.data.restartProcessButtion;
                if (res.data.visitId != undefined) {
                  localStorage.setItem('visitId', res.data.visitId);
                  that.visitId = res.data.visitId;
                }
                that.list = that.filterSfaTaskList(res.data.sfaTaskList);
                that.storeGroupId = res.data.storeGroupId;
                that.showOrderButton = res.data.showOrderButton;
                that.startTime = res.data.startTime;
                that.timeN = setInterval(that.animation, 16);
                that.visitsRemarks = res.data.visitsRemarks;
                let sfaStoreType = res.data.sfaStoreType;
                if (
                  (sfaStoreType && (sfaStoreType.jz || sfaStoreType.gz)) ||
                  res.data.approvalStatus == null ||
                  res.data.approvalStatus == 0
                ) {
                  that.isToOtherSystem = false;
                } else {
                  that.isToOtherSystem = true;
                }
              } else {
                that.$toast(res.msg);
              }
            });
          } else {
            var params = {
              storeId: that.storeId,
              storeCode: that.urlParameter.storeCode,
              visitEntry: '0',
              lat: that.urlParameter.latNew,
              lon: that.urlParameter.lonNew,
              visitModel: that.visitModel,
              routeDetailsId: that.rdId,
              visitSource: '1',
              insert: insert,
              locationCity: '',
              locationRemark: '',
              locationAccuracy: that.urlParameter.PointSum,
            };
            that.locationAccuracy = that.urlParameter.PointSum;
            that.city = '';
            that.address = '';
            localStorage.setItem('address', '');
            if (that.visitId != null) {
              params.id = that.visitId;
            }
            let loading2 = that.$toast.loading({
              duration: 0,
              message: '加载中...',
              forbidClick: true,
            });
            that.list = [];
            getVisitTasks(params).then((res) => {
              loading2.clear();
              if (res.code == 200) {
                that.notes = res.data.notes;
                that.restartProcessButtion = res.data.restartProcessButtion;
                if (res.data.visitId != undefined) {
                  localStorage.setItem('visitId', res.data.visitId);
                  that.visitId = res.data.visitId;
                }
                that.list = that.filterSfaTaskList(res.data.sfaTaskList);
                that.storeGroupId = res.data.storeGroupId;
                that.showOrderButton = res.data.showOrderButton;
                that.startTime = res.data.startTime;
                that.timeN = setInterval(that.animation, 16);
                that.visitsRemarks = res.data.visitsRemarks;
                let sfaStoreType = res.data.sfaStoreType;
                if (
                  (sfaStoreType && (sfaStoreType.jz || sfaStoreType.gz)) ||
                  res.data.approvalStatus == null ||
                  res.data.approvalStatus == 0
                ) {
                  that.isToOtherSystem = false;
                } else {
                  that.isToOtherSystem = true;
                }
              } else {
                that.$toast(res.msg);
              }
            });
          }
        },
      );
    },
    getLocation() {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      let url = window.location.href;
      let wx = this.wx;
      this.list = [];
      let that = this;
      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) {
            loading1.clear();
            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) {
                  var location = that.CJ02BD(res.latitude, res.longitude);
                  that.location = location;
                  if (that.urlParameter.lat == '' || that.urlParameter.lat == null) {
                    that.lat = that.location.lat;
                    that.lon = that.location.lon;
                  } else {
                    that.lat = that.urlParameter.lat;
                    that.lon = that.urlParameter.lon;
                  }
                  let PointSum = that
                    .twoPointSum(that.lat, that.lon, location.lat, location.lon)
                    .toFixed(2);
                  that.locationAccuracy = PointSum;
                  if (PointSum > 500) {
                    that.visitModel = '5';
                    localStorage.setItem('visitModel', '5');
                    that.$dialog
                      .confirm({
                        confirmButtonText: '确定',
                        cancelButtonText: '重新定位',
                        title: '系统提示',
                        message: '距离本店距离差距太大',
                      })
                      .then(() => {
                        that.addVisits();
                      })
                      .catch(() => {
                        that.getLocation();
                      });
                  } else {
                    that.addVisits();
                  }
                },
                fail: function () {
                  that.$dialog
                    .alert({
                      message: 'GPS未开启',
                    })
                    .then(() => {
                      that.getLocation();
                    });
                },
              });
            });
          }
        });
    },
    filterSfaTaskList(list) {
      let taskTypeArr = list.filter((val) => val.taskType !== '5');
      let taskType5Index = list.findIndex((val) => val.taskType == '5');
      if (taskType5Index != -1) {
        let taskType5Arr = list.filter((val) => val.taskType == '5');
        let taskIds = [];
        taskType5Arr.forEach((val) => {
          taskIds.push(val.taskId);
        });
        let taskType5 = {
          ...list[taskType5Index],
          taskIds: taskIds,
        };
        taskType5.taskName = '生动化陈列（拍全产品和道具）';
        taskTypeArr.splice(taskType5Index, 0, taskType5);
      }
      console.log(taskTypeArr);
      return taskTypeArr;
    },
    addStoreVisit(val, index) {
      if (this.flag) {
        this.flag = false;
        this.timer = null;
        this.timer = setTimeout(() => {
          this.flag = true;
        }, 2000);
        localStorage.setItem('getRequestFlage', 'false');
        if (val.taskType == '5') {
          // getCljlaToDBLabel({ visitsId: this.visitId }).then((res) => {
          //   if (res.code == 200) {
          this.$router.push({
            path: '/taskPhotoTaking',
            query: {
              storeCode: this.urlParameter.storeCode,
              visitsId: this.visitId,
              taskIds: val.taskIds.join(','),
              storeGroupId: this.storeGroupId,
              photoType: val.photoType,
              insert: this.insert,
              storeId: this.storeId,
            },
          });
          //   } else {
          //     this.$toast(res.msg);
          //   }
          // });
        } else {
          this.$router.push({
            path: '/addStoreVisit',
            query: {
              visitSource: '1',
              storeId: this.storeId,
              storeCode: this.urlParameter.storeCode,
              visitId: this.visitId,
              ids: index,
              taskId: val.taskId,
              type: this.urlParameter.type,
              storeGroupId: this.storeGroupId,
              taskType: val.taskType,
              photoType: val.photoType,
              lat: this.lat,
              lon: this.lon,
              visitModel: this.visitModel,
              locationCity: this.city,
              locationRemark: this.address,
              types: this.$route.query.type,
              locationAccuracy: this.locationAccuracy,
              insert: this.insert,
              photoIdentifyType: val.photoIdentifyType,
              deviceCode: val.deviceCode,
              putInCode: val.putInCode,
              equipmentCode: val.equipmentCode,
              inspectionType: val.inspectionType,
            },
          });
        }
      }
      // this.$router.push({path: "/addStoreVisit", query:
      // 		{storeId:this.storeId,storeCode:that.urlParameter.storeCode,visitId:this.visitId,ids:index,taskId:val.taskId,storeGroupId:this.storeGroupId,taskType:val.taskType,photoType:val.photoType}})
      // localStorage.setItem('collectionItemList', JSON.stringify(val.collectionItemList));
    },
    onClickLeft() {
      localStorage.setItem('getRequestFlage', 'true');
      if (this.$route.query.urltype == 2) {
        window.location.replace(window.location.origin + this.locationOrigin + '/home');
      } else {
        this.$router.go(-1);
      }
    },
    // 物料历史
    wuliaoLog() {
      this.toastLoading(0, '加载中...', true);
      getMaterialHistory({ storeId: this.storeId })
        .then((res) => {
          this.toastLoading().clear();
          if (res.code == 200 && res.data) {
            this.wuliaoList = res.data;
            this.wuliaoTable = true;
          }
        })
        .catch(() => {
          this.toastLoading().clear();
        });
    },
    wuliaoTableClose() {
      this.wuliaoTable = false;
    },
    endVisitsFn(val) {
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      if (val != 't') {
        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 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;
          }, 2000);
          endVisits({
            visitSource: '1',
            visitType: '0',
            dwellTime: dwellTime,
            storeGroupId: this.storeGroupId,
            id: this.visitId,
            visitModel: this.$route.query.visitModel,
            taskId: this.$route.query.taskId,
            pass: true,
            instanceId: this.$route.query.instanceId,
            storeCode: this.urlParameter.storeCode,
          }).then((res) => {
            this.flag = true;
            loading1.clear();
            if (res.code == 200) {
              this.editDwellTimes();
              if (this.$route.query.urltype == 2) {
                window.location.replace(window.location.origin + this.locationOrigin + '/home');
              } else {
                this.$router.go(-1);
                // window.location.replace(window.location.origin + '/mobile/deviceWithin/index');
              }
            } else {
              this.$toast({
                message: res.msg,
                duration: 5000,
              });
            }
          });
        }
      } else {
        if (this.flag) {
          this.flag = false;
          this.timer = null;
          this.timer = setTimeout(() => {
            this.flag = true;
          }, 2000);
          restartProcess({
            visitsId: this.visitId,
          }).then((res) => {
            this.flag = true;
            loading1.clear();
            if (res.code == 200) {
              if (this.$route.query.urltype == 2) {
                window.location.replace(window.location.origin + this.locationOrigin + '/home');
              } else {
                window.location.replace(
                  window.location.origin + this.locationOrigin + '/historAllVisit',
                );
              }
            } else {
              this.$toast({
                message: res.msg,
                duration: 5000,
              });
            }
          });
        }
      }
    },
    // 跳转好帮手门店详情
    goOtherSystem() {
      if (this.isToOtherSystem) {
        if (this.urlParameter.storeCode)
          window.location.href =
            process.env.VUE_APP_SSB_LINK +
            '/order/storeDetail/index?shopCode=' +
            this.urlParameter.storeCode;
      }
    },
  },
};
</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;
  }
  .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: #1989fa;
      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;
    line-height: 22px;
    .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%;
}
.submitBtn {
  margin: 16px 0;
  font-size: 18px;
}
.card .f-blue {
  color: #0057ba;
}
.storeVisit {
  .to-other-system {
    color: #0057ba;
    text-decoration: underline;
  }
  .storeCategory {
    display: flex;
    justify-content: space-between;
    .storeType {
      flex: 1;
      display: flex;
      align-items: center;
    }
  }
  .visitsRemarks {
    display: flex;
    justify-content: space-between;
    .f-blue {
      flex: 1;
      display: flex;
      align-items: center;
    }
  }
}
</style>
<style lang="scss">
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #0057ba;
}
#allmap {
  width: 20px;
  height: 20px;
  left: -1000px;
  position: relative;
}
.el-dialog__wrapper {
  z-index: 9999 !important;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.5) !important;
  .wuliaoTable {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    max-height: 70%;
    margin-top: 0 !important;
    .el-dialog__header {
      height: 40px;
      display: flex;
      justify-content: right;
      .el-dialog__headerbtn {
        position: static !important;
      }
    }
    .el-dialog__body {
      padding: 30px 20px !important;
      overflow-y: auto;
      flex: 1;
    }
    .cell {
      font-size: 12px;
    }
  }
}
</style>
