<template>
  <!-- 拜访详情 -->
  <div class="visitPage">
    <div class="headers">
      <van-nav-bar class="navBar" :title="$route.meta.title" left-arrow @click-left="onClickLeft" />
    </div>
    <div class="container">
      <div class="card">
        <div class="title">
          {{ urlParameter.chainName }}(<span style="color: #0057ba">{{
            urlParameter.chainCode
          }}</span
          >)
        </div>
        <div class="info1">身份类型：{{ urlParameter.typeName2 }}</div>
        <div class="info1">上次拜访备注：{{ notes }}</div>
        <div class="info1">拜访时长：{{ showTime }}</div>
        <div class="info1">
          <span> 上次拜访时间：{{ parseTime(urlParameter.hisTime) }} </span>
        </div>
        <div class="info1">
          <span @click="openVisitHistory" class="f-blue" style="font-weight: bold">
            <van-icon :name="require('@/assets/icon/history.png')" />
            历史拜访记录
          </span>
        </div>
        <van-button
          type="info"
          style="
            float: right;
            background: #ed5565;
            border-color: #ed5565;
            color: #fff;
            margin: 10px 0;
            border-radius: 5px;
            top: -40px;
          "
          size="small"
          plain
          class="centerBtn"
          @click="onstopVisit"
          >取消拜访</van-button
        >
      </div>
      <div
        v-if="addShow1"
        style="color: #999; font-size: 12px; padding: 10px; background-color: #f5f5f5">
        <van-icon name="info-o" />&nbsp;今天拜访拍照内容，将同步传给部主管查阅。
      </div>
      <div class="card">
        <div
          class="info"
          v-for="(item, index) in list"
          :key="index"
          @click="visitTask(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: 74%; margin: 0; line-height: 24px; display: inline-block">
            {{ item.taskName }}
          </p>
          <span v-show="item.processKey != null" class="processIco">
            <van-icon :name="require('@/assets/icon/sp.png')" size="16" />
          </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" tyle="background-color: #0057ba"
            ><van-icon name="success"
          /></span>
        </div>
      </div>
    </div>
    <div class="tc" style="padding: 0 16px">
      <van-button class="submitBtn" block type="info" color="#0057ba" @click="endVisitsFn">
        提交拜访
      </van-button>
    </div>
    <br />
    <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>
  </div>
</template>

<script>
import {
  getChainsGroupTask,
  endVisits,
  stopVisit,
  editDwellTime,
  getVisitTasks,
} from '@/api/agentList';
import store from '@/store';
export default {
  name: 'visitPage',
  data() {
    return {
      notes: '',
      visitModel: '1',
      shows: false,
      flag: true,
      questionsshow: false,
      uploadImgshow: false,
      imgs: [],
      uploadImages: [],
      uploadid1: 'uploadid1',
      uploadid2: 'uploadid2',
      iscuxiao: false,
      text: '',
      radio: '',
      uploadImgEditText: '编辑',
      isEdit: false,
      chainId: '',
      rdId: '',
      lat: '',
      lon: '',
      list: [],
      storeGroupId: '',
      addShow1: false,
      visitId: '',
      addressLine: '',
      storeCategory: '',
      storeName: '',
      contactName: '',
      urlParameter: '',
      uType: '-1',
      showOrderButton: null,

      visitsRemarks: [],
      location: {
        lat: '34.6174',
        lon: '112.44039',
      },
      address: '',
      showTime: '00:00:00',
      city: '',
      locationAccuracy: '',
      id: '89',
      startTime: null,
      timeN: null,
    };
  },
  created() {},
  mounted() {},
  activated() {
    // 是否请求任务列表接口
    let getRequestFlage = localStorage.getItem('getRequestFlage');
    if (getRequestFlage != 'true') return;
    this.urlParameter = this.$route.query;
    this.chainId = this.$route.query.chainId + '';
    this.visitId = this.$route.query.visitId || localStorage.getItem('visitId');
    this.chainCode = this.$route.query.chainCode;
    this.rdId = this.$route.query.rdId || '';
    this.addressLine = this.$route.query.addressLine;
    this.storeCategory = this.$route.query.storeCategory;
    this.chainName = this.$route.query.chainName;
    this.contactName = this.$route.query.contactName;
    this.lat = this.$route.query.lat + '';
    this.lon = this.$route.query.lon + '';
    this.visitModel = this.$route.query.visitModel + '';
    this.uType = localStorage.getItem('uType');
    if (localStorage.getItem('visitId') != null) {
      this.visitId = localStorage.getItem('visitId');
      setTimeout(() => {
        this.addVisits();
      });
    } else {
      setTimeout(() => {
        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);
    },
    // 结束拜访
    onstopVisit() {
      this.$dialog
        .confirm({
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          title: '系统提示',
          message: '取消拜访会清空填写的拜访内容和照片，是否确认？',
        })
        .then(() => {
          stopVisit({ visitsId: this.visitId }).then((res) => {
            if (res.code == 200) {
              localStorage.removeItem('visitId');
              this.$dialog
                .alert({
                  title: '系统提示',
                  message: '拜访中任务结束成功！',
                })
                .then(() => {
                  store.dispatch('setDeviceOutsidePage', true);
                  this.onClickLeft();
                });
            } else {
              this.$dialog.alert({
                title: '系统提示',
                message: res.msg,
              });
            }
          });
        });
    },
    getLocation() {
      this.toastLoading(0, '加载中...', true);
      // 授权
      getTicketFun()
        .then(() => {
          getPosition(true)
            .then((res) => {
              this.toastLoading().clear();
              let { TXisBD } = res;
              this.lat = TXisBD.lat;
              this.lon = TXisBD.lon;
              this.addVisits();
            })
            .catch((error) => {
              this.toastLoading().clear();
              this.$dialog.alert({
                message: error,
              });
            });
        })
        .catch(() => {
          this.toastLoading().clear();
          this.finished = true;
        });
    },
    editDwellTimes() {
      let dwellTime = this.weekend(localStorage.getItem('startTime'), new Date()) + '';
      editDwellTime({ dwellTime: dwellTime, visitsId: this.visitId }).then((res) => {
        if (res.code == 200) {
          localStorage.removeItem('visitId');
        }
      });
    },

    weekend(time1) {
      var arrtime1 = new Date(time1).getTime();
      var arrtime2 = new Date().getTime();
      return Math.round((arrtime2 - arrtime1) / 1000);
    },
    addVisits() {
      var postType = localStorage.getItem('postType');
      if (postType == 'GZ') {
        this.addShow1 = false;
      } else {
        this.addShow1 = true;
      }
      var visitEntry = '';
      if (this.urlParameter.tabVal == '0') {
        visitEntry = '2';
      } else {
        visitEntry = '1';
      }
      if (this.$route.query.shopCode != undefined) {
        this.chainCode = this.$route.query.shopCode;
      }
      var that = this;

      var map = new TMap.Map('allmap', {
        zoom: 14,
        center: new TMap.LatLng(39.986785, 116.301012),
      });
      var geocoder = new TMap.service.Geocoder();
      var markers = new TMap.MultiMarker({
        map: map,
        geometries: [],
      });
      markers.setGeometries([]);
      var input = [that.urlParameter.marklat, that.urlParameter.marklon];
      var location = new TMap.LatLng(Number(input[0]), Number(input[1]));
      geocoder.getAddress({ location: location }).then(
        function (result) {
          var addresses = result.result.formatted_addresses;
          let address_component = result.result.address_component;
          var params = {
            chainId: that.chainId,
            chainCode: that.chainCode,
            visitEntry: visitEntry,
            lat: that.urlParameter.latNew,
            lon: that.urlParameter.lonNew,
            visitModel: that.visitModel,
            routeDetailsId: that.rdId,
            visitSource: '1',
            locationCity: '',
            locationRemark: '',
            locationAccuracy: that.urlParameter.PointSum,
            province: address_component.province,
            city: address_component.city,
            district: address_component.district,
          };
          if (addresses) {
            params.locationRemark = addresses.recommend;
            that.address = addresses.recommend;
          }
          that.locationAccuracy = that.urlParameter.PointSum;
          that.city = '';
          localStorage.setItem('address', '');
          if (that.visitId != null) {
            params.id = that.visitId;
          }
          let loading2 = that.$toast.loading({
            duration: 0,
            message: '加载中...',
            forbidClick: true,
          });
          getVisitTasks(params).then((res) => {
            loading2.clear();
            if (res.code == 200) {
              localStorage.setItem('visitId', res.data.visitId);
              that.notes = res.data.notes;
              that.visitId = res.data.visitId;
              that.list = res.data.sfaTaskList;
              that.storeGroupId = res.data.storeGroupId;
              that.showOrderButton = res.data.showOrderButton;
              that.startTime = res.data.startTime;
              that.timeN = setInterval(that.animation, 16);
              that.visitsRemarks = res.data.visitsRemarks;
            } else {
              that.visitId = res.data;
              that.$toast(res.msg);
            }
          });
        },
        function (err) {
          var params = {
            chainId: that.chainId,
            chainCode: that.chainCode,
            visitEntry: visitEntry,
            lat: that.urlParameter.latNew,
            lon: that.urlParameter.lonNew,
            visitModel: that.visitModel,
            routeDetailsId: that.rdId,
            visitSource: '1',
            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,
          });
          getVisitTasks(params).then((res) => {
            loading2.clear();
            if (res.code == 200) {
              localStorage.setItem('visitId', res.data.visitId);
              that.notes = res.data.notes;
              that.visitId = res.data.visitId;
              that.list = res.data.sfaTaskList;
              that.storeGroupId = res.data.storeGroupId;
              that.showOrderButton = res.data.showOrderButton;
              that.startTime = res.data.startTime;
              that.timeN = setInterval(that.animation, 16);
              that.visitsRemarks = res.data.visitsRemarks;
            } else {
              that.visitId = res.data;
              that.$toast(res.msg);
            }
          });
        },
      );
    },
    visitTask(val, index) {
      localStorage.setItem('getRequestFlage', 'false');
      this.$router.push({
        path: '/visitTask',
        query: {
          chainId: this.chainId,
          chainCode: this.urlParameter.chainCode,
          visitId: this.visitId,
          ids: index,
          taskId: val.taskId,
          storeGroupId: this.storeGroupId,
          taskType: val.taskType,
          photoType: val.photoType,
          lat: this.lat,
          lon: this.lon,
          visitSource: '1',
          visitModel: this.visitModel,
          locationCity: this.city,
          locationRemark: this.address,
          locationAccuracy: this.locationAccuracy,
          photoIdentifyType: val.photoIdentifyType,
          inspectionType: val.inspectionType,
          deviceCode: val.deviceCode,
          putInCode: val.putInCode,
          equipmentCode: val.equipmentCode,
        },
      });
    },
    onClickLeft() {
      localStorage.setItem('getRequestFlage', 'true');
      if (this.$route.query.urltype == 1) {
        window.location.replace(window.location.origin + '/mobile/home');
      } else {
        // 返回上一页不会刷新页面
        this.$router.go(-1);
      }
    },
    onshouow() {
      this.uploadshow = false;
      this.questionsshow = false;
    },
    uploadImgEdit() {
      if (this.uploadImgEditText == '编辑') {
        this.uploadImgEditText = '完成';
      } else {
        this.uploadImgEditText = '编辑';
        this.uploadImgshow = false;
      }
    },
    deleteImg(index) {
      this.imgs.splice(index, 1);
    },
    questionClick(item) {
      console.log(item);
      if (item.isUpload) {
        this.uploadshow = true;
      } else if (item.isQuestion) {
        this.questionsshow = true;
      }
    },
    endVisitsFn() {
      if (this.list.length == 0) {
        this.$toast('暂无任务提交');
        return;
      }
      for (var vl = 0; vl < this.list.length; vl++) {
        if (this.list[vl].isMust == '0') {
          if (!this.list[vl].success) {
            this.$toast(this.list[vl].taskName + '任务未完成');
            return;
          }
        }
      }
      let loading1 = this.$toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true,
      });
      let dwellTime = this.weekend(localStorage.getItem('startTime'), new Date());
      let chainCode = this.chainCode;
      if (this.$route.query.shopCode != undefined) {
        chainCode = this.$route.query.shopCode;
      }
      if (this.flag) {
        this.flag = false;
        this.timer = null;
        this.timer = setTimeout(() => {
          this.flag = true;
        }, 5000);
        endVisits({
          visitSource: '1',
          storeGroupId: this.storeGroupId,
          id: this.visitId,
          chainCode: chainCode,
          dwellTime: dwellTime,
          visitModel: this.$route.query.visitModel,
        }).then((res) => {
          this.flag = true;
          loading1.clear();
          if (res.code == 200) {
            this.editDwellTimes();
            store.dispatch('setDeviceOutsidePage', true);
            if (this.$route.query.linkType == 6) {
              window.location.replace(window.location.origin + '/mobile/topStore?info=y');
            } else {
              if (this.$route.query.urltype == 1) {
                window.location.replace(window.location.origin + '/mobile/home');
              } else {
                this.onClickLeft();
                // window.location.replace(
                //   window.location.origin + '/mobile/outsidelist/index?info=y'
                // );
              }
            }
          } else {
            this.$toast({
              message: res.msg,
              duration: 5000,
            });
          }
        });
      }
    },
    newimgarr1(val) {
      this.imgs = val;
    },
    uploadImgShowFn() {
      this.uploadImgshow = true;
      if (this.uploadImages.length <= 0) {
        this.uploadImgEditText = '';
      }
    },
    previewsImg(index) {
      ImagePreview({
        images: this.uploadImages,
        startPosition: index,
        onClose() {
          // do something
        },
      });
    },
    // 打开历史拜访
    openVisitHistory() {
      this.$router.push({
        name: 'visitHistory',
        query: {
          ...this.urlParameter,
        },
      });
    },
  },
  destroyed() {
    this.timeN = null;
    clearInterval(this.timeN);
  },
};
</script>
<style lang="scss" scoped>
.visitPage {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .container {
    overflow-y: auto;
    flex: 1;
    margin-bottom: 10px;
    background-color: white;
  }
}
.navBarOverlay {
  background: #fff;
}
.card {
  background: #fff;
  box-sizing: border-box;
  padding: 10px 16px;
  .title {
    line-height: 32px;
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
  .subtitle {
    line-height: 24px;
    font-size: 14px;
    color: #7b7b7b;
    .status {
      float: right;
    }
  }
  .info {
    font-size: 14px;
    color: #484848;
    padding: 14px;
    border-bottom: 1px solid #f1f1f1;
    position: relative;
    .arrow {
      float: right;
      display: inline-block;
      height: 20px;
      width: 20px;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      background: #0057ba;
      color: #fff;
      font-weight: bold;
      font-size: 14px;
      position: absolute;
      margin-top: -10px;
      right: 0;
      top: 50%;
    }
  }
  .info1 {
    font-size: 14px;
    color: #666;
    line-height: 18px;
    padding: 4px 0;
    position: relative;
    .arrow {
      float: right;
      display: inline-block;
      height: 20px;
      width: 20px;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      background: #0057ba;
      color: #fff;
      font-weight: bold;
      font-size: 14px;
      margin-top: 9px;
      position: absolute;
      right: 0;
      top: 50%;
      margin-top: -10px;
    }
  }
}
.must {
  font-size: 18px;
  color: #f56c6c;
  margin-right: 2px;
}
.zw {
  display: inline-block;
  width: 7px;
  height: 100%;
}
.lineGrey {
  height: 10px;
  width: 100%;
  background: #f1f1f1;
}
.submitBtn {
  margin: 16px 0;
  font-size: 18px;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  .block {
    width: 100%;
    height: 100%;
    background-color: #fff;
    overflow: auto;
  }
}
.questionName {
  font-size: 16px;
  color: #484848;
  /*line-height: 40px;*/
  background: #f4f4f4;
  padding: 10px 15px;
  box-sizing: border-box;
  position: relative;
  display: flex;
  justify-content: center;
  .text {
    flex: 9;
  }
}
.answerDiv {
  background: #fff;
  padding: 0 15px 10px;
  .answerItem {
    padding: 10px 0;
    border-bottom: 1px solid #dedede;
    .name {
      line-height: 36px;
      font-size: 14px;
      color: #8b8b8b;
    }
  }
}
.border {
  border: 1px solid #dedede;
}
.ht30 {
  height: 30px;
}
.bodrder-b {
  border-bottom: 1px solid #dedede;
}
.img-box {
  width: 50%;
  /*height: 100%;*/
  position: relative;
  padding: 10px;
  display: inline-block;
  i {
    position: absolute;
    right: 2px;
    top: 2px;
  }
  img {
    width: 100%;
    height: 100%;
  }
}
.imgNull {
  text-align: center;
  padding-top: 100px;
  i {
    color: #dedede;
  }
  div {
    padding-top: 30px;
    font-size: 18px;
    font-weight: bold;
  }
}
.card .f-blue {
  color: #0057ba;
}
</style>
<style>
.navBarOverlay .van-nav-bar__left .van-icon {
  color: #8b8b8b;
}
.navBarOverlay .van-nav-bar__right .van-nav-bar__text {
  color: #333;
}
.ht30 .van-radio__label {
  color: #8b8b8b;
}
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #0057ba;
}
#allmap {
  width: 20px;
  height: 20px;
  left: -1000px;
  position: relative;
}
</style>
