<template>
  <view>
    <!-- <view v-if='showLoading'>
			<u-loading-page :loading="showLoading"></u-loading-page>
		</view> -->
    <view>
      <view class="content">
        <u-toast ref="uToast"></u-toast>
        <view class="map" style="position: relative;">
          <map :class="mapClass" id="map" @markertap='mapFun' :enable-zoom="true" :polyline="polyline"
            :markers='markers' :scale="scale" style="width:100%;height: 100%;" :latitude="markers[0].latitude"
            :enable-scroll="true" :longitude="markers[0].longitude">
          </map>
          <!-- <cover-view v-show="modelShow" style="background-color: rgba(#000, 0.9);height: 100px;width: 100px;position: absolute;top: 0;left: 0;"></cover-view> -->
        </view>
        <view class="map_address">
          <view class="li">
            <view style="display: flex;justify-content: left;">
              <view style="flex-shrink: 0;margin-right: 14rpx;">
                <text class="cir" style="background-color: #40BC5E;"></text>
                中转站:
              </view>
              <view v-if="address.transfer">{{address.transfer.address}}</view>
            </view>
            <view v-if="status!=5||address.transfer.status==2"
              :class="{lg_status1:address.transfer.status==2,lg_status2:address.transfer.status==1}"
              style="margin-top: 10rpx;">
              <text class="cir" style="background-color: transparent;"></text>
              <text>车辆状态：</text>
              <text v-if="address.transfer.status==2">已完成</text>
              <text v-else style="color: #FF7C32;">进行中</text>
            </view>
            <view v-else class="red" style="margin-top: 10rpx;">
              <text class="cir" style="background-color: transparent;"></text>
              <text>车辆状态：</text>
              <text>未完成</text>
            </view>
          </view>
          <view class="li">
            <view style="display: flex;justify-content: left;">
              <view style="flex-shrink: 0;margin-right: 14rpx;">
                <text class="cir" style="background-color: #40BC5E;"></text>
                终&emsp;点:
              </view>
              <view v-if="address.terminus">{{address.terminus.address}}</view>
            </view>
            <view
              :class="{red: address.terminus.status!=2&&address.transfer.status==1,yellow:address.transfer.status!=1&&address.terminus.status!=2, green: address.terminus.status==2}"
              style="margin-top: 10rpx;">
              <text class="cir" style="background-color: transparent;"></text>
              <text :class="{red: status==5}">车辆状态：</text>
              <text v-if="address.terminus.status==2">已完成</text>
              <text v-else-if="address.transfer.status==1">未开始</text>
              <text v-else-if="status!=5">进行中</text>
              <text v-else :class="{red: status==5}">未完成</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <mybtn v-if="status==1" @click="modelShow=true" text="抵达地点(中转站) 1/2"></mybtn>
    <mybtn v-else-if="status==2" @click="modelShow=true" text="抵达地点(终点) 2/2"></mybtn>
    <mybtn v-else-if="status==3" text="任务已完成" my_btn_disabled></mybtn>
    <mybtn v-else-if="status==5" text="任务已关闭" my_btn_disabled></mybtn>
    <cover-view v-show="modelShow" class="cover">
      <cover-view class="cover_model">
        <cover-view class="model_title">标题</cover-view>
        <cover-view class="model_content">确认抵达目的地了吗</cover-view>
        <cover-view>
          <cover-view style="height: 1px;width: 100%;background-color: #eee;"></cover-view>
          <cover-view class="model_btn">
            <cover-view class="item" @click="modelShow=false">取消</cover-view>
            <cover-view style="height: 100%;width: 1px;background-color: #eee;"></cover-view>
            <cover-view class="model_confirm item" @click="getFn();modelShow=false">确认</cover-view>
          </cover-view>
        </cover-view>
      </cover-view>
    </cover-view>
    <!-- <u-modal :show="modelShow" title="提示" content='确认您已到达目标地点' closeOnClickOverlay showCancelButton
    @close="modelShow=false" @cancel="modelShow=false" @confirm="getFn();modelShow=false"></u-modal> -->
  </view>
</template>

<script>
  import mybtn from "@/components/mybtn/mybtn.vue"
  import {
    taskTricycleDetail,
    taskAddTricycleCoordinate
  } from "@/api/task.js"
  import {
    Toast
  } from "../../libs/uniApi";
  export default {
    components: {
      mybtn
    },
    data() {
      return {
        modelShow: false,
        status: 1,
        mapClass: 'custom-map',
        showLoading: true,
        showPop: false,
        goodsDetil: undefined,
        scale: 17,
        nowAddress: "无",
        markers: [
          // 目的地
          {
            id: 1,
            latitude: 28.8733,
            longitude: 105.445717,
            iconPath: '../../static/img/logistics/WZ.png', //显示的图标        
          },
          // 当前所在位置
          {
            id: 2,
            latitude: undefined,
            longitude: undefined,
            iconPath: '../../static/img/logistics/SL.png', //显示的图标        
          }
        ],
        polyline: [],
        task_id: -1,
        address: {
          transfer: {
            status: 1
          },
          terminus: {
            status: 1
          }
        }
      }
    },
    onLoad(options) {
      this.task_id = options.task_id;
      this.locationFn();
      this.initPosition();
    },
    methods: {
      // 获取位置
      async initPosition() {
        let res = await taskTricycleDetail({
          id: this.task_id
        });
        this.address = res.data.extend;
        if (res.data.extend?.update?.transfer?.lnglat[0]) { //已抵达中转站,更新目标点为终点
          this.markers[0].latitude = +res.data.extend.terminus.lnglat[1];
          this.markers[0].longitude = +res.data.extend.terminus.lnglat[0];
          this.status = 2;
          this.address.transfer['status'] = 2;
        } else { // 未抵达中转站,设置中转站为目标点
          this.markers[0].latitude = +res.data.extend.transfer.lnglat[1];
          this.markers[0].longitude = +res.data.extend.transfer.lnglat[0];
          this.address.transfer['status'] = 1;
        }
        if (res.data.extend?.update?.terminus?.lnglat[0] || res.data.status == 3) {
          this.address.terminus['status'] = 2;
          this.status = 3;
        } else this.address.terminus['status'] = 1;
        if (res.data.status == 5) {
          this.status = 5;
        }
      },
      // 位置
      locationFn() {
        let that = this;
        // uni.showLoading({
        //   title: '获取位置中'
        // })
        uni.getLocation({
          type: 'gcj02',
          geocode: true,
          isHighAccuracy: true,
          success: function async (res) {
            that.markers[1].latitude = res.latitude;
            that.markers[1].longitude = res.longitude;
            that.getDriverLine();
            // uni.hideLoading();
            uni.showModal({
              title: '成功',
              content: JSON.stringify(res)
            })
          },
          fail(e) {
            // uni.hideLoading();
            Toast('获取位置失败');
            console.log(e);
            // uni.showModal({
            //   title: '失败',
            //   content: JSON.stringify(e)
            // })
            try {
              plus.geolocation.getCurrentPosition(function(position) {
                console.log('经度：' + position.coords.longitude);
                console.log('纬度：' + position.coords.latitude);
                that.markers[1].latitude = position.coords.longitude;
                that.markers[1].longitude = position.coords.longitude;
                that.getDriverLine();
                uni.hideLoading();
                uni.showModal({
                  title: 'plus成功',
                  content: JSON.parse(position)
                })
              }, function(error) {
                console.error('获取位置失败：', error.message);
                uni.showModal({
                  title: 'plus失败',
                  content: JSON.parse(error)
                })
                uni.sendHostEvent('getLocation', '获取位置', (ret) => {
                  uni.$on('uniMP_getLocation', (res) => {
                    try {
                      that.markers[1].latitude = res.latitude;
                      that.markers[1].longitude = res.longitude;
                      that.getDriverLine();
                      uni.hideLoading();
                      uni.showModal({
                        title: 'uniMP成功',
                        content: JSON.parse(res)
                      })
                    } catch (e) {
                      Toast('获取位置失败');
                      uni.showModal({
                        title: 'uniMP失败',
                        content: JSON.parse(e)
                      })
                    }
                  })
                });
              });
            } catch (e) {
                uni.showModal({
                  title: '没有plus',
                  content: JSON.parse(e)
                })
            }
          }
        });


      },
      showToast() {
        this.$refs.uToast.show({
          type: 'success',
          title: '成功主题(带图标)',
          message: "操作成功",
          iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
        })
      },
      mapFun() {
        uni.openLocation({
          latitude: Number(this.goodsDetil.logistics.shop_lat),
          longitude: Number(this.goodsDetil.logistics.shop_long),
          address: this.goodsDetil.logistics.shop_address,
          name: this.goodsDetil.logistics.shop_name,
          scale: 15,
        });
      },
      showToast() {
        this.$refs.uToast.show({
          type: 'success',
          title: '成功主题(带图标)',
          message: "操作成功",
          iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
        })
      },
      // 计算距离
      getDistance(point1, point2) {
        const rad = Math.PI / 180.0;
        const lat1 = point1.latitude;
        const lng1 = point1.longitude;
        const lat2 = point2.latitude;
        const lng2 = point2.longitude;
        const dlat = lat2 - lat1;
        const dlng = lng2 - lng1;
        const a =
          Math.sin(dlat / 2 * rad) * Math.sin(dlat / 2 * rad) +
          Math.cos(lat1 * rad) * Math.cos(lat2 * rad) *
          Math.sin(dlng / 2 * rad) * Math.sin(dlng / 2 * rad);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        const distance = 6378137 * c;
        return distance;
      },
      // 上报位置
      getFn() {
        uni.showLoading({
          title: '上传中',
          mask: true
        })
        this.locationFn()
        // console.log(this.getDistance(this.markers[0], this.markers[1]))
        if ((this.getDistance(this.markers[0], this.markers[1]) >> 0) > 10000) {
          return Toast('距离目标位置过远');
        } else {
          let data;
          if (this.status == 1) data = {
            id: this.task_id,
            transfer: {
              lnglat: [
                this.markers[1].longitude,
                this.markers[1].latitude
              ]
            }
          };
          else data = {
            id: this.task_id,
            terminus: {
              lnglat: [
                this.markers[1].longitude,
                this.markers[1].latitude
              ]
            }
          };
          taskAddTricycleCoordinate(data).then(() => {
            uni.hideLoading()
            Toast('上传成功!')
            this.initPosition();
            this.locationFn();
          })
        }
      },
      getDriverLine() {
        const that = this;
        const key = "997c9a3d88154fa78f4d28bebc1dd84f";
        const origin = `${this.markers[1].longitude},${this.markers[1].latitude}`;
        const destination = `${this.markers[0].longitude},${this.markers[0].latitude}`;
        uni.request({
          // url: `https://restapi.amap.com/v3/direction/walking?key=${key}&origin=105.43639400000002,28.908854&destination=105.439304,28.908447`,
          url: `https:restapi.amap.com/v4/direction/bicycling?key=${key}&origin=${origin}&destination=${destination}`,
          success: (res) => {
            const data = res.data.data;
            var points = [];
            if (data.paths && data.paths[0] && data.paths[0].steps) {
              var steps = data.paths[0].steps;
              for (var i = 0; i < steps.length; i++) {
                //将每一步的数据放到points数组中
                var poLen = steps[i].polyline.split(";");
                for (var j = 0; j < poLen.length; j++) {
                  points.push({
                    longitude: parseFloat(poLen[j].split(",")[0]),
                    latitude: parseFloat(poLen[j].split(",")[1]),
                  });
                }
              }
              that.runningRoute = data.paths[0].steps[0].instruction;
            }
            uni.getSystemInfo({
              success: function(e) {
                if (e.platform == 'ios') {
                  that.polyline = [{
                    points: points,
                    color: "#0091ff",
                    dottedLine: true,
                    width: 10,
                  }, ];
                } else {
                  that.polyline = [{
                    points: points,
                    color: "#0091ff",
                    dottedLine: true,
                    width: 15,
                  }, ];
                }
              }
            })

          },
          fail: function(res) {
            console.log("获取路线失败", res);
          },
        });
      },

    },
    onPullDownRefresh() {
      // this.getOrderList();
      // this.getIndexList()
      uni.stopPullDownRefresh();
    },

  }
</script>

<style lang='scss' scoped>
  .cover {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(#000, 0.3);

    .cover_model {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 650rpx;
      /* height: 300rpx; */
      background-color: #fff;
      border-radius: 6px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .model_title {
        height: 92rpx;
        line-height: 92rpx;
        text-align: center;
        font-size: 16px;
        font-weight: bold;
      }

      .model_content {
        margin: 12px 25px 25px 25px;
        font-size: 15px;
      }

      .model_btn {
        display: flex;
        height: 96rpx;
        font-size: 16px;

        .item {
          flex: 1;
          text-align: center;
          line-height: 96rpx;
        }

        .model_confirm {
          color: #0122c7;
        }
      }
    }
  }

  .red {
    color: #ff0000;
  }

  .green {
    color: #40bc5e;
  }

  .yellow {
    color: #ff7c32;
  }

  .custom-map /deep/ .polyline {
    stroke-width: 20px;
  }

  .content {
    padding: 2vh 3vw;
    background-color: #F5F5F5;
    height: 100vh;
    box-sizing: border-box;
  }

  .map {
    height: 60vh;
    border-radius: 2vw;
    overflow: hidden;
  }

  .map_address {
    background-color: white;
    padding: 20rpx 10rpx;
    border-radius: 0 0 14rpx 14rpx;

    .li {
      margin: 20rpx 0;
      line-height: 40rpx;
    }

    .cir {
      display: inline-block;
      width: 2vw;
      height: 2vw;
      border-radius: 2vw;
      margin: 0 20rpx;
    }
  }

  .map_btn {
    width: 50px;
    height: 50px;
    position: absolute;
    bottom: 0px;
    right: 0;
    z-index: 9999999;
  }

  .btn {

    position: fixed;
    bottom: 20rpx;
    width: 90vw;
    left: 50%;
    transform: translateX(-50%);

  }
</style>