// pages/DetailsOfRefund/DetailsOfRefund.js
var http = require('../../utils/http.js');
var util = require('../../utils/util.js');
var plugin = requirePlugin("logisticsPlugin")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: 15 * 60 * 1000,
    timeData: {},
    statusObject: {
      0: '待支付',
      1: '待发货',
      20: '订单已接单',
      30: '订单待配送',
      40: '待收货',
      50: '订单取消待审核',
      60: '订单已取消',
      70: '订单已送达',
      80: '订单已完成'
    },
    shopInfo:null,
    totalUsableScore:0,
    dvyType:'',//配送方式显示文字
    type:'',//配送方式 1快递 3配送
    dvyName:'',
    dvyFlowId:'',
    orderItemDtos: [],
    remarks: "",
    actualTotal: 0,
    canRefund:false,
    shopId:0,
    userAddrDto: null,
    orderNumber: "",
    createTime: "",
    status: 0,
    productTotalAmount: '',
    transfee: '',
    totalNum:0,
    reduceAmount: '',
    prodid: '',
    orderType: 0,
    shopName: '', //店铺名称
    canRefund: false, // 能否退款
    canAllRefund: false, // 能否整单退款
    isLastProd: false,  //最后一款商品
    irrevocable: false,  //不可撤销
    sum: [],  //本单已申请单个退款的商品数组
    orderScore: 0, // 整单使用积分
    orderNumSend:'',
    estimatedTime: '',
    estimatedTimeStr: '',
    sendInfo:null,//骑手信息
    cancelReason:null,
    markers:[
    ],
    polyline:[],
    includePoints:[],//存放点位 显示完整图标
    timer:null,//定时器
    commSts:1,//评论状态： 0 未评价  1 已评价
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      orderNumSend:options.orderNum
    })
    this.loadOrderDetail(options.orderNum);
  },
  /**
   * 加载订单数据
   */
  loadOrderDetail: function(orderNum) {
    var ths = this;
    wx.showLoading();
    //加载订单详情
    var params = {
      url: "/p/myOrder/orderDetail",
      method: "GET",
      data: {
        orderNumber: orderNum
      },
      callBack: function(res) {
        let img=''
        res.orderItemDtos.forEach(e=>{
          img=e.pic.split(',')
          e.pic=img[0]
        })

        var dvyType
        let markers = []
        let includePoints = []
        let polyline = []
        if(res.dvyType == 1){
          ths.getShopInfo(res.shopId).then(r=>{
            markers = [{
              // 商家标记
              id: 1,
              longitude:ths.data.shopInfo.lon,
              latitude: ths.data.shopInfo.lat,
              iconPath: '../../images/icon/shopPosition.png',  // 商家图标
              width: "140rpx",
              height: '176rpx',
              rotate: 0,  // 旋转角度（可根据方向动态调整）
              zIndex: 99,   // 层级（骑手图标在最上层）
              customCallout: {
                anchorY: 0,
                anchorX: 0,
                display: 'ALWAYS',
              },
            },
            {
              // 收货地址
              id: 2,
              longitude:res.userAddrDto.longitude,
              latitude: res.userAddrDto.latitude,
              iconPath: '../../images/icon/head04.png',  // 图标
              width: "80rpx",
              height: '80rpx',
              rotate: 0,  // 旋转角度（可根据方向动态调整）
              zIndex: 3,   // 层级（骑手图标在最上层）
            }]
            let orderMap = wx.createMapContext('orderMap')
            includePoints = [
              {
                longitude:ths.data.shopInfo.lon,
                latitude: ths.data.shopInfo.lat,
              },
              {
                longitude:res.userAddrDto.longitude,
                latitude: res.userAddrDto.latitude,
              }
            ]
            orderMap.includePoints({points:includePoints,padding:[50,50,50,50]})
            polyline= [{
                points:[ {
                    longitude:ths.data.shopInfo.lon,
                    latitude: ths.data.shopInfo.lat,
                  },
                  {
                    longitude:res.userAddrDto.longitude,
                    latitude: res.userAddrDto.latitude,
                  }
                ],
                color: "#006CE8",  // 折线颜色（支持十六进制、rgb）
                width: 4,          // 折线宽度（单位：px）
                arrowLine: true   // 是否带箭头（默认 false，支持微信基础库 2.13.0+）
              }
            ]
            ths.setData({
              polyline,
              includePoints,
              markers,
            })
          })
          dvyType = '运费（快递）'
          
        }else if(res.dvyType == 3){
          dvyType = '配送费（即时配送）'
        }else{
          dvyType = '自提'
        }
        // 15分钟倒计时
        let time = (new Date(res.createTime).getTime() + 1000*60*15)- new Date().getTime()
        ths.setData({
          time,
          totalUsableScore:res.totalUsableScore,
          dvyType:dvyType,
          dvyName: res.dvyName,
          dvyFlowId: res.dvyFlowId,
          type:res.dvyType,
          orderNumber: orderNum,
          actualTotal: res.actualTotal, //实际支付总额（商品总额+运费)
          canRefund:res.canRefund,
          userAddrDto: res.userAddrDto,
          remarks: res.remarks,
          orderItemDtos: res.orderItemDtos,
          createTime: res.createTime,
          status: res.status,
          shopId: res.shopId,
          // status: res.status,//海博订单状态
          productTotalAmount: res.total, //所有商品总额
          transfee: res.transfee, //运费
          totalNum:res.totalNum,
          reduceAmount: res.reduceAmount,
          orderType: res.orderType,
          shopName: res.shopName,
          canRefund: res.canRefund,
          canAllRefund: res.canAllRefund,
          orderScore: res.orderScore, // 整单使用积分
          estimatedTime: res.estimatedTime,
          estimatedTimeStr: res.estimatedTimeStr,
          cancelReason: res.cancelReason,
          commSts: res.commSts,
        });
        
        wx.hideLoading();
      
        if(res.dvyType == 3&&res.status==40){//配送中再获取骑手位置
          ths.startGetposition()
        }
      }
    };
    http.request(params);

  },
  // 获取店铺详情
  getShopInfo: function(shopId) {
    return new Promise((resolve,reject)=>{
      var ths = this;
      //热门搜索
      var params = {
        url: "/shop/headInfo",
        method: "GET",
        data: {
          shopId: shopId
        },
        callBack: function(res) {
          console.log(1111,res)
          ths.setData({
            shopInfo:res
          })
          resolve()
        },
      };
      http.request(params);
    })
  },
  /**
   * 
   * 开始定时查询骑手位置
   */
  startGetposition(){
   let timer =  setInterval(() => {//1分钟查询一次
      this.getSenderPosition()
    }, 60000);
    this.setData({
      timer
    })
  },
  /**
   * 获取骑手位置
   */
  getSenderPosition: function (e) {
    // wx.showLoading();
    var ths = this;
    var params = {
      url: "/p/location/info",
      method: "get",
      data: {
        orderNumber:this.data.orderNumber //'1978351838923198464'
      },
      callBack: res => {
        // wx.hideLoading();
        console.log(res);
        if(res.code == 200&&res.data){
          let markers = [
            {
              // 骑手标记
              id: 1,
              longitude:res.data.longitude,
              latitude: res.data.latitude,
              iconPath: '../../images/icon/sender.png',  // 骑手图标
              width: "140rpx",
              height: '176rpx',
              rotate: 0,  // 旋转角度（可根据方向动态调整）
              zIndex: 3,   // 层级（骑手图标在最上层）
              customCallout: {
                anchorY: 0,
                anchorX: 0,
                display: 'ALWAYS',
              },
            },
            {
              // 收货地址
              id: 2,
              longitude:ths.data.userAddrDto.longitude,
              latitude: ths.data.userAddrDto.latitude,
              iconPath: '../../images/icon/head04.png',  // 图标
              width: "80rpx",
              height: '80rpx',
              rotate: 0,  // 旋转角度（可根据方向动态调整）
              zIndex: 3,   // 层级（骑手图标在最上层）
            },
          ]

          let includePoints = [
            {
              longitude:res.data.longitude,
              latitude: res.data.latitude,
            },
            {
              longitude:ths.data.userAddrDto.longitude,
              latitude: ths.data.userAddrDto.latitude,
            }
          ]

          
          ths.setData({
            includePoints,
            markers,
            sendInfo:res.data
          })
        }
      }
    };
    http.request(params);
  },
  clickMarker(e){
    console.log(e.detail.markerId);
    if(e.detail.markerId == 1 && this.data.type == 1&&this.data.status>1&&this.data.actualTotal>0){
      this.getWaybillToken()
    }
  },
  getWaybillToken(){
    wx.showLoading()
    var ths = this;
    var params = {
      url: "/p/myOrder/getWaybillToken",
      method: "get",
      data: {
        orderNumber:this.data.orderNumber //'1978351838923198464'
      },
      callBack: res => {
        wx.hideLoading()
        console.log(res);
        if(res.errcode == 0&&res){
          const waybillToken = res.waybill_token;
          // 在此通过调用api来查询微信快递服务详情
          //必须用预览才能测试这个功能，无法在工具端模拟
          plugin.openWaybillTracking({
                waybillToken: waybillToken
          })
        }
      }
    };
    http.request(params);
    

  },
  //跳转商品详情页
  toProdPage: function(e) {
    var prodid = e.currentTarget.dataset.prodid;
    if(this.data.orderType==3){
      console.log('积分商品')
      wx.navigateTo({
        url: '/pages/convertProdDet/convertProdDet?prodid=' + prodid,
      })
    }else{
      wx.navigateTo({
        url: `/pages/prod/prod?prodid=${prodid}&shopid=${this.data.shopId}`,
      })
    }
  },

  /**
   * 付款
   */
  onPayAgain: function (e) {
    wx.showLoading({
      mask: true
    });
    var ths = this;
    var orderType = this.data.orderType;
    var params = {
      url: "/p/order/pay",
      method: "POST",
      data: {
        orderType: orderType ? orderType : 0,
        payType: 1,
        orderNumbers: this.data.orderNumber
      },
      callBack: res => {
        //console.log(res);
        wx.hideLoading();
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.paySign,
          success: function () {
            ths.loadOrderDetail(ths.data.orderNumber)  //请求订单详情数据
            // wx.navigateTo({
            //   url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + e.currentTarget.dataset.ordernum,
            // })
          },
          fail: function (err) {
            //console.log("支付失败");
          }
        })
      }
    };
    http.request(params);
  },

  //删除已完成||已取消的订单
  delOrderList: function (e) {
    var ths = this
    wx.showModal({
      title: '',
      content: '确定要删除此订单吗？',
      confirmColor: "#006CE8",
      success(res) {
        if (res.confirm) {
          var ordernum = e.currentTarget.dataset.ordernum;
          wx.showLoading();
          var params = {
            url: "/p/myOrder/" + ordernum,
            method: "DELETE",
            data: {},
            callBack: function (res) {
              wx.navigateTo({
                url:'/pages/orderList/orderList'
              })
              wx.hideLoading();
            }
          }
          http.request(params);
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 去评价
   */
  goWrite(e){
    wx.navigateTo({
      url: '/pages/prodComm/prodComm?orderNumber='+this.data.orderNumber,
    })
  },

    /**
   * 取消订单
   */
  onCancelOrder: function (e) {
    var ths = this;
    wx.showModal({
      title: '',
      content: '要取消此订单？',
      confirmColor: "#006CE8",
      cancelText: '否',
      confirmText: '是',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            mask: true
          });

          var params = {
            url: "/p/myOrder/cancel/" + ths.data.orderNumber,
            method: "PUT",
            data: {},
            callBack: function (res) {
              //console.log(res);
              ths.loadOrderDetail(ths.data.orderNumber)  //请求订单详情数据
              wx.hideLoading();
            }
          };
          http.request(params);
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 确认收货
   */
  onConfirmReceive: function (e) {
    var ths = this;
    wx.showModal({
      title: '',
      content: '我已收到货？',
      confirmColor: "#006CE8",
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            mask: true
          });
          var params = {
            url: "/p/myOrder/receipt/" + ths.data.orderNumber,
            method: "PUT",
            data: {},
            callBack: function (res) {
              wx.hideLoading();
              ths.loadOrderDetail(ths.data.orderNumber)  //请求订单详情数据

            }
          };
          http.request(params);
        } else if (res.cancel) {
          //console.log('用户点击取消')
        }
      }
    })
  },

  /**
   * 申请退款
   */
  applyRefund: function(e) {
    var item = {}
    item.orderNumber = this.data.orderNumber;
    item.actualTotal = this.data.actualTotal;
    item.transfee = this.data.transfee;
    item.status = this.data.status; //订单状态
    item.orderItemDtos = this.data.orderItemDtos;
    item.totalNum = this.data.totalNum
    item.orderScore = this.data.orderScore,  // 整单积分
    item.userAddrDto = this.data.userAddrDto,  // 用户信息
    //拿到存储在本地的订单项数据
    wx.setStorageSync("refundItem", item);

    wx.redirectTo({ //通过wx.redirectTo实现跳转（关闭当前页面，跳转到应用内某个页面）
      url: '/pages/applyRefund/applyRefund',
    })

},

  callSender(){
    wx.makePhoneCall({
      phoneNumber: this.data.sendInfo.courierPhone//仅为示例，并非真实的电话号码
    })
  },

  // 一键复制事件
  copyBtn: function(e) {
    let data = e.currentTarget.dataset.value
    wx.setClipboardData({
      //准备复制的数据
      data,
      success: function(res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    })
  },
  onChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})