<template>
  <div>
    <!--        顶部条-->
    <van-nav-bar class="navBar" title="异常拜访" left-arrow @click-left="onClickLeft">
      <template #right>
        <span @click="onstopVisit" class="navRightBtnTop">取消拜访</span>
      </template>
    </van-nav-bar>
    <!--        主体内容-->
    <div class="container">
      <div class="lineGrey"></div>
      <van-form class="bgWhite">
        <div class="formLabel">
          <van-cell>
            <template #title> <span class="van-f-red">*</span>异常信息照 </template>
            <template #right-icon>
              <upload-img
                :uploadid="uploadid2"
                :imgArr="imgs"
                @newimgarr="newimgarr1"
                :visitModel="visitModel"
                :visitsId="visitId"
                :taskId="rdId"></upload-img>
            </template>
          </van-cell>
        </div>
        <div style="padding: 10px 10px 0">
          <delete-upload-img :imgs="imgs" @delimg="newimgarr1"></delete-upload-img>
        </div>
        <div class="formLabel">
          <van-cell>
            <template #title> <span class="van-f-red">*</span>异常事由 </template>
          </van-cell>
          <van-radio-group v-model="abnormalReason" class="z-checkbox">
            <van-radio :name="item.dictValue" v-for="(item, index) in typeList" :key="index">{{
              item.dictLabel
            }}</van-radio>
          </van-radio-group>
        </div>
        <div class="formLabel" style="padding-bottom: 20px">
          <van-cell>
            <van-cell>
              <template #title> <span class="van-f-red">*</span>信息备注 </template>
            </van-cell>
          </van-cell>
          <van-field
            v-model="remark"
            rows="3"
            autosize
            maxlength="260"
            show-word-limit
            label=""
            :formatter="formatter"
            type="textarea"
            placeholder="请填写异常信息" />
        </div>
      </van-form>
      <div class="formLabel" style="margin: 20px 16px">
        <van-button
          block
          type="info"
          size="normal"
          style="background-color: #0057ba"
          @click="endVisitsFn"
          >提交
        </van-button>
      </div>
    </div>
    <div id="allmap"></div>
  </div>
</template>

<script>
// import uploadImg from "@/components/uploadImg";
import uploadImg from '@/components/uploadVvisit';
import deleteUploadImg from '@/components/deleteUploadImg1';
import { addVisits, endVisits, getPhotoTypeList1, stopVisit } from '@/api/index';
import axios from 'axios';

export default {
  name: 'outabnormalVisit',
  components: { uploadImg, deleteUploadImg },
  data() {
    return {
      PhotoTypeList: [],
      typeList: '',
      imgs: [],
      cont: 0,
      abnormalReason: '',
      uploadid2: 'uploadid2',
      remark: '',
      lat: '',
      lon: '',
      storeCode: '',
      dialogms: true,
      visitModel: '',
    };
  },
  created() {
    this.getPhotoTypeList();
    this.urlParameter = this.$route.query;
    this.storeId = this.$route.query.storeId + '';
    this.visitId = this.$route.query.visitId;
    this.storeCode = this.$route.query.storeCode;
    this.rdId = this.$route.query.rdId + '';
    this.lat = this.$route.query.lat + '';
    this.lon = this.$route.query.lon + '';
    this.visitModel = this.$route.query.visitModel + '';
    this.imgs = [];
    this.remark = '';
    this.abnormalReason = '';
  },
  watch: {
    $route(to, from) {
      if (from.path == '/outsidelist/index' && to.path == '/outabnormalVisit') {
        this.imgs = [];
        this.remark = '';
        this.abnormalReason = '';
      }
      if (from.path == '/outabnormalVisit' && to.path == '/outsidelist/index') {
        localStorage.removeItem('visitId');
      }
    },
  },
  activated() {
    this.addVisits();
    this.imgs = [];
    this.remark = '';
    this.abnormalReason = '';
    this.visitModel = this.$route.query.visitModel + '';
    this.urlParameter = this.$route.query;
    this.storeId = this.$route.query.storeId + '';
    this.visitId = this.$route.query.visitId;
    this.storeCode = this.$route.query.storeCode;
    this.rdId = this.$route.query.rdId + '';
    this.lat = this.$route.query.lat + '';
    this.lon = this.$route.query.lon + '';
  },
  methods: {
    // 结束拜访
    onstopVisit() {
      this.$dialog
        .confirm({
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          title: '系统提示',
          message: '取消拜访会清空填写的拜访内容和照片，是否确认？',
        })
        .then(() => {
          stopVisit({ visitsId: this.visitId }).then((res) => {
            if (res.code == 200) {
              this.$dialog
                .alert({
                  title: '系统提示',
                  message: '拜访中任务结束成功！',
                })
                .then(() => {
                  window.location.replace(
                    window.location.origin + this.locationOrigin + '/outsidelist/index',
                  );
                });
            } else {
              this.$toast(res.msg);
            }
          });
        });
    },
    formatter(value) {
      return value.replace(
        /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
        '',
      );
    },
    getPhotoTypeList() {
      getPhotoTypeList1({}).then((res) => {
        this.typeList = res.data;
      });
    },
    newimgarr1(val) {
      this.imgs.push(val);
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    addVisits() {
      var that = this;
      var visitEntry = '';
      if (this.urlParameter.tabVal == '0') {
        visitEntry = '2';
      } else {
        visitEntry = '1';
      }
      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;
          var params = {
            storeId: that.storeId,
            storeCode: that.storeCode,
            visitEntry: visitEntry,
            lat: that.urlParameter.lat,
            lon: that.urlParameter.lon,
            visitModel: that.$route.query.visitModel,
            visitSource: '2',
            routeDetailsId: that.rdId,
            locationCity: '',
            locationRemark: addresses.recommend,
            locationAccuracy: that.urlParameter.PointSum,
          };
          localStorage.setItem('address', '');
          if (that.visitId != null) {
            params.id = that.visitId;
          }
          addVisits(params).then((res) => {
            if (res.code == 200) {
              localStorage.setItem('visitId', res.data);
              that.visitId = res.data;
            } else {
              that.$toast(res.msg);
            }
          });
        },
        function (err) {
          var params = {
            storeId: that.storeId,
            storeCode: that.storeCode,
            visitEntry: visitEntry,
            lat: that.urlParameter.lat,
            lon: that.urlParameter.lon,
            visitModel: that.$route.query.visitModel,
            visitSource: '2',
            routeDetailsId: that.rdId,
            locationCity: '',
            locationRemark: '',
            locationAccuracy: that.urlParameter.PointSum,
          };
          localStorage.setItem('address', '');
          if (that.visitId != null) {
            params.id = that.visitId;
          }
          addVisits(params).then((res) => {
            if (res.code == 200) {
              localStorage.setItem('visitId', res.data);
              that.visitId = res.data;
            } else {
              that.$toast(res.msg);
            }
          });
        },
      );
    },
    endVisitsFn() {
      if (this.imgs.length == 0) {
        this.$toast('请上传图片');
        return;
      }
      if (this.abnormalReason == '') {
        this.$toast('请选择事由');
        return;
      } else if (this.remark.trim() == '') {
        this.$toast('请填写异常内容');
        return;
      } else {
        let dwellTime = this.weekend(localStorage.getItem('startTime'));
        endVisits({
          visitSource: '2',
          dwellTime: dwellTime,
          remark: this.remark,
          visitType: '0',
          abnormalReason: this.abnormalReason,
          id: this.visitId,
          storeCode: this.storeCode,
          visitModel: this.$route.query.visitModel,
        }).then((res) => {
          if (res.code == 200) {
            this.$dialog
              .alert({
                title: '系统提示',
                message: '保存成功',
              })
              .then(() => {
                // if(this.$route.query.linkType==6){
                //   window.location.replace(window.location.origin + "/mobile/topStore?info=y")
                // }else{
                window.location.replace(
                  window.location.origin + this.locationOrigin + '/outsidelist/index?info=y',
                );
                // }
              });
            localStorage.removeItem('visitId');
            localStorage.removeItem('startTime');
          } else {
            this.$toast.fail(res.msg);
          }
        });
      }
    },
    weekend(time1) {
      var arrtime1 = new Date(time1).getTime();
      var arrtime2 = new Date().getTime();
      return Math.round((arrtime2 - arrtime1) / 1000);
    },
  },
};
</script>
<style scoped>
.bgWhite {
  background-color: white;
}
.container {
  padding-bottom: 50px;
}
.van-f-red {
  color: red;
  width: 4px;
  display: inline-block;
}
.formLabel {
  margin: 0 16px;
  border-bottom: 1px solid #f1f1f1;
}
.formLabel .van-cell {
  padding: 10px 0;
}
.z-checkbox .van-radio {
  padding: 6px 0;
}
</style>
<style>
#allmap {
  width: 20px;
  height: 20px;
  left: -1000px;
  position: relative;
}
.formLabel .van-field {
  border: 1px solid #f1f1f1;
  padding: 10px;
  width: 100%;
  background-color: #f1f1f1;
}
.formLabel .van-field__control {
  padding: 0 10px;
}
.lineGrey {
  height: 10px;
  width: 100%;
  background: #f1f1f1;
}
.van-dialog__confirm,
.van-dialog__confirm:active {
  color: #0057ba;
}
.navRightBtnTop {
  color: white;
  background: #74a4d9;
  display: block;
  padding: 6px 10px;
  border-radius: 6px;
}
</style>
