import Toast from 'tdesign-miniprogram/toast/index';
import Dialog from 'tdesign-miniprogram/dialog/index';
import {
  OrderButtonTypes
} from '../../config';
import {
  wechatPayOrder
} from '~/services/pay';
import {
  wxRepay
} from '~/services/order/wxRepay';
import {
  waitPayCancelOrder
} from '~/services/order/waitPayCancelOrder';
import {
  payCancelOrder
} from '~/services/order/payCancelOrder';
import {
  delOrder
} from '~/services/order/delOrder';
import {
  confirmReceipt
} from '~/services/order/confirmReceipt';

Component({
  options: {
    addGlobalClass: true,
  },
  properties: {
    order: {
      type: Object,
      observer(order) {
        // 判定有传goodsIndex ，则认为是商品button bar, 仅显示申请售后按钮
        // if (this.properties?.goodsIndex !== null) {
        //   const goods = order.goodsList[Number(this.properties.goodsIndex)];
        //   this.setData({
        //     buttons: {
        //       left: [],
        //       right: (goods.buttons || []).filter((b) => b.type == OrderButtonTypes.APPLY_REFUND),
        //     },
        //   });
        //   return;
        // }
        // 订单的button bar 不显示申请售后按钮
        const buttonsRight = (order.buttons || [])
          // .filter((b) => b.type !== OrderButtonTypes.APPLY_REFUND)
          .map((button) => {
            //邀请好友拼团按钮
            if (button.type === OrderButtonTypes.INVITE_GROUPON && order.groupInfoVo) {
              const {
                groupInfoVo: {
                  groupId,
                  promotionId,
                  remainMember,
                  groupPrice
                },
                goodsList,
              } = order;
              const goodsImg = goodsList[0] && goodsList[0].imgUrl;
              const goodsName = goodsList[0] && goodsList[0].name;
              return {
                ...button,
                openType: 'share',
                dataShare: {
                  goodsImg,
                  goodsName,
                  groupId,
                  promotionId,
                  remainMember,
                  groupPrice,
                  storeId: order.storeId,
                },
              };
            }
            return button;
          });
        // 删除订单按钮单独挪到左侧
        const deleteBtnIndex = buttonsRight.findIndex((b) => b.type === OrderButtonTypes.DELETE);
        let buttonsLeft = [];
        if (deleteBtnIndex > -1) {
          buttonsLeft = buttonsRight.splice(deleteBtnIndex, 1);
        }
        this.setData({
          buttons: {
            left: buttonsLeft,
            right: buttonsRight,
          },
        });
      },
    },
    goodsIndex: {
      type: Number,
      value: null,
    },
    isBtnMax: {
      type: Boolean,
      value: false,
    },
  },

  data: {
    order: {},
    buttons: {
      left: [],
      right: [],
    },
  },

  methods: {
    // 点击【订单操作】按钮，根据按钮类型分发
    onOrderBtnTap(e) {
      const {
        type
      } = e.currentTarget.dataset;
      switch (type) {
        case OrderButtonTypes.DELETE:
          this.onDelete(this.data.order);
          break;
        case OrderButtonTypes.CANCEL:
          this.onCancel(this.data.order);
          break;
        case OrderButtonTypes.CONFIRM:
          this.onConfirm(this.data.order);
          break;
        case OrderButtonTypes.PAY:
          this.onPay(this.data.order);
          break;
        case OrderButtonTypes.APPLY_REFUND:
          this.onApplyRefund(this.data.order);
          break;
        case OrderButtonTypes.VIEW_REFUND:
          this.onViewRefund(this.data.order);
          break;
        case OrderButtonTypes.COMMENT:
          this.onAddComment(this.data.order);
          break;
        case OrderButtonTypes.INVITE_GROUPON:
          //分享邀请好友拼团
          break;
        case OrderButtonTypes.REBUY:
          this.onBuyAgain(this.data.order);
      }
    },

    //删除订单
    onDelete(order) {
      delOrder(order.id).then((res) => {
        if (res.code === 200) {
          this.triggerEvent('refresh')
          Toast({
            context: this,
            selector: '#t-toast',
            message: '删除成功',
            icon: '',
          });
        }
      })
    },

    //取消订单
    onCancel(order) {

      console.log(order, '看看order先');
      // 待支付取消
      if (order.status === 1) {
        let data = {
          orderGuid: order.Guid
        }
        waitPayCancelOrder(data).then((res) => {
          if (res.code === 200) {
            this.triggerEvent('refresh')
            Toast({
              context: this,
              selector: '#t-toast',
              message: '取消成功',
              icon: '',
            });
          }
        })
      }
      // 已支付取消
      if (order.status !== 1) {
        let data = {
          orderGuid: order.Guid
        }
        payCancelOrder(data).then((res) => {
          if (res.code === 200) {
            this.triggerEvent('refresh')
            Toast({
              context: this,
              selector: '#t-toast',
              message: '申请取消成功',
              icon: '',
            });
          }
        })
      }
    },

    //确认收货
    onConfirm(order) {
      Dialog.confirm({
          title: '确认是否已经收到货？',
          content: '',
          confirmBtn: '确认收货',
          cancelBtn: '取消',
        })
        .then(() => {
          let data = {
            orderGuid: order.Guid
          }
          confirmReceipt(data).then((res) => {
            if (res.code === 200) {
              this.triggerEvent('refresh')
              Toast({
                context: this,
                selector: '#t-toast',
                message: '收货成功',
                icon: 'check-circle',
              });
            }
          })
        })
        .catch(() => {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '你取消了确认收货',
            icon: 'check-circle',
          });
        });
    },

    // 重新调起支付
    onPay(order) {
      let data = {
        orderNo: order.orderNo,
        openId: wx.getStorageSync('openId')
      }

      wxRepay(data).then((res) => {
        this.handlePay(res.data,order).then((res) => {
          console.log(res);
        })
      })
    },

    onBuyAgain() {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '你点击了再次购买',
        icon: 'check-circle',
      });
    },

    // 申请售后
    onApplyRefund(order) {
      console.log(order, '这里的参数');
      const goods = order.goodsList[this.properties.goodsIndex];
      const params = {
        orderGuid: order.Guid,
        orderNo: order.orderNo,
        goodsList: JSON.stringify(order.goodsList),
        skuId: goods?.skuId,
        spuId: goods?.id,
        thumb: goods?.thumb,
        title: goods?.title,
        spec: goods?.spec,
        orderStatus: order.status,
        logisticsNo: order.logisticsNo,
        price: goods?.price,
        num: goods?.num,
        createTime: order.createTime,
        orderAmt: order.totalAmount,
        freightFee: order.freightFee,
        payAmt: order.amount,
        canApplyReturn: true,
      };
      const paramsStr = Object.keys(params)
        .map((k) => `${k}=${params[k]}`)
        .join('&');
      wx.navigateTo({
        url: `/pages/order/apply-service/index?${paramsStr}`
      });
    },

    onViewRefund() {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '你点击了查看退款',
        icon: '',
      });
    },

    /** 添加订单评论 */
    onAddComment(order) {
      const imgUrl = order?.goodsList?.[0]?.thumb;
      const title = order?.goodsList?.[0]?.title;
      const specs = order?.goodsList?.[0]?.specs;
      const orderGuid = order?.Guid;
      const goodsGuid = order?.goodsList?.[0]?.id;
      wx.navigateTo({
        url: `/pages/goods/comments/create/index?specs=${specs}&title=${title}&orderNo=${order?.orderNo}&imgUrl=${imgUrl}&orderGuid=${orderGuid}&goodsGuid=${goodsGuid}`,
      });
    },

    // 处理支付
    handlePay(data,order) {
      const {
        jsApiUiPackage,
        outTradeNo,
        interactId,
        transactionId
      } = data;
      const payOrderInfo = {
        payInfo: jsApiUiPackage,
        orderId: outTradeNo,
        orderAmt: order.totalAmount,
        payAmt: order.totalAmount,
        interactId: interactId,
        tradeNo: outTradeNo,
        transactionId: transactionId,
      };
      console.log(payOrderInfo, '支付信息');

      // if (channel === 'wechat') {
      wechatPayOrder(payOrderInfo);
      // }
    },

  },
});