import {
  addOrder,
  cancelOrder,
  orderDelit,
  driverLocation,
  driverLocationLog,
} from "@/api/trip.js";
export const mixin = {
  data() {
    return {
      seconds: 0,
      minutes: 0,
      timer: null,
      loading: false,
      hangupObj: {
        orderId: "",
        orderNo: "",
        queryId: "",
        reason: "",
      },
      hangupShow: false,
      optionList: [
        {
          name: "地址选错了",
        },
        {
          name: "不需要用车了",
        },
        {
          name: "司机太远了",
        },
        {
          name: "计划有变",
        },
        {
          name: "其他原因",
        },
      ],
      driver: {
        driverId: "",
        driverName: "",
        driverPhone: "",
        driverAvatar: "",
        driverStatus: "",
        driverReceivedTime: "",
        payPrice: "", // 预估价格
      },
      location: {
        driverId: "", // 司机ID
        longitude: 0, // 司机当前位置  gcj-02坐标系
        latitude: 0, // 司机当前位置  gcj-02坐标系
        createTime: "", // 司机定位时间
        gpsAccuracyStatus: 1, // 司机定位信号强度， 1：GPS定位信号好；其他：定位信号不好
        accuracy: 0, // 定位进度，单位米
      },
      path: [],
      priceItems: [],
    };
  },
  methods: {
    // 呼叫司机
    call() {
      // this.markers = [];
      // console.log(this.markers)
      // console.log(this.map)
      // this.map.removeMarkers()
      this.loading = true;
      if (this.step !== 2) {
        uni.showToast({
          title: "请先选择目的地",
          icon: "none",
        });
        setTimeout(() => {
          this.chooseAddress("end");
          this.loading = false;
        }, 1000);
        return;
      }
      uni.showLoading({
        title: "加载中",
      });
      // adcode	string(11)	Y	下单地区的行政区划代码，六位数字，精确到省市区（县）
      // originName	string(40)	Y	起点名称，如 XXX大厦，XXX小区XX栋，XXX工业园
      // originLocation	string(200)	Y	地点详细全称，XXX省XX市XX区XX街道XXXX小区XXX栋X单元
      // originLongitude	double	Y	起点经度，gcj-02坐标系
      // originLatitude	double	Y	起点纬度，gcj-02坐标系
      // destinationName	string(40)	N	终点地名，选填，关于终点的四个参数，要么都不传入，要么都要传入。
      // destinationLocation	string(200)	N	终点全名
      // destinationLongitude	double	N	终点终点经度，gcj-02坐标系
      // destinationLatitude	double	N	终点纬度，gcj-02坐标系
      addOrder({
        channel: "ZhongShu",
        adcode: this.form.adcode,
        originName: this.form.start,
        originLocation: this.form.start,
        originLongitude: Math.floor(this.form.startLocation.lng * 100) / 100,
        originLatitude: Math.floor(this.form.startLocation.lat * 100) / 100,
        destinationName: this.form.end,
        destinationLocation: this.form.end,
        destinationLongitude: Math.floor(this.form.endLocation.lng * 100) / 100,
        destinationLatitude: Math.floor(this.form.endLocation.lat * 100) / 100,
      }).then((res) => {
        this.loading = false;
        if (res.state === "Success") {
          this.hangupObj.orderNo = res.content.orderNo;
          this.hangupObj.queryId = res.content.goodsList[0].id;
          uni.setStorageSync("tripId", this.hangupObj.queryId);
          this.step = 3;
          this.startTimer();
        } else {
          uni.showToast({
            title: res.message,
            icon: "none",
          });
        }
        uni.hideLoading({
          noConflict: true,
        });
      });
    },
    // 取消
    hangup() {
      this.hangupShow = true;
    },
    // 取消订单
    cancelOrder() {
      uni.showLoading({
        title: "取消中...",
      });
      cancelOrder({
        orderId: this.hangupObj.queryId,
        reason: this.hangupObj.reason,
      }).then((res) => {
        console.log(res);
        uni.hideLoading();
        if (res.state === "Success") {
          uni.showToast({
            title: "取消成功",
            icon: "success",
          });
          this.state = 2;
          this.loading = false;
          clearInterval(this.timer);
          this.timer = null;
          this.seconds = 0;
          this.minutes = 0;
        } else {
          uni.showToast({
            title: res.message,
            icon: "none",
          });
        }
      });
    },
    startTimer() {
      // 保证只存在一个实例
      if (this.timer) {
        return;
      } else {
        this.timer = setInterval(() => {
          this.seconds++;
          // 每隔5秒请求一次
          if (this.seconds % 5 == 0) {
            // 获取订单状态
            orderDelit(this.hangupObj.queryId).then((res) => {
              if (res.state === "Success") {
                // 可能取消了可能接单了
                const id = res.content.orderStatus;
                const driverStatus = res.content.driverStatus;
                // 更新司机数据
                this.driver.driverId = res.content.driverId;
                this.driver.driverName = res.content.driverName;
                this.driver.driverPhone = res.content.driverPhone;
                this.driver.driverAvatar = res.content.driverAvatar;
                this.driver.driverStatus = res.content.driverStatus;
                this.driver.payPrice = res.content.payPrice;
                this.priceItems = res.content.priceItems;
                if (id == 1) {
                  // 获取司机位置
                  driverLocation({
                    orderId: this.hangupObj.queryId,
                  }).then((res) => {
                    if (res.state == "Success") {
                      const { content } = res.content;
                      this.location.driverId = content.driverId;
                      this.location.longitude = content.longitude;
                      this.location.latitude = content.latitude;
                      this.location.createTime = content.createTime;
                      this.location.gpsAccuracyStatus =
                        content.gpsAccuracyStatus;
                      this.location.accuracy = content.accuracy;

                      // 订单进行中
                      if (driverStatus == 1) {
                        // 有人接单了
                        this.step = 4;
                        // 绘制司机的行驶轨迹
                        this.goToUser();
                      } else if (driverStatus == 2) {
                        // 到达了目的地开始了等待
                        this.step = 5;
                      } else if (driverStatus == 3) {
                        // 乘客已经上车
                        this.step = 6;
                        this.goToEnd();
                      } else if (driverStatus == 4) {
                        // 订单完成
                        this.step = 7;
                      }
                    }
                  });
                } else if (id == 2) {
                  // 订单已经完成
                  this.step = 7;
                  this.loading = false;
                  clearInterval(this.timer);
                  this.timer = null;
                  uni.removeStorageSync("tripId");
                  this.seconds = 0;
                  this.minutes = 0;
                  this.go(true);
                } else if (id == -1) {
                  this.step = 2;
                  this.loading = false;
                  clearInterval(this.timer);
                  this.timer = null;
                  this.seconds = 0;
                  this.minutes = 0;
                  uni.removeStorageSync("tripId");
                  // 重置地图
                  uni.showToast({
                    title: "订单已经取消！",
                    icon: "none",
                    duration: 2000,
                  });
                  this.go();
                }
              }
            });
          }
          if (this.seconds == 60) {
            this.minutes++;
            this.seconds = 0;
          }
        }, 1000);
      }
    },
    selectClick(e) {
      console.log(e);
      this.hangupObj.reason = e.name;
      this.hangupShow = false;
      this.cancelOrder();
    },
  },
};
