/* eslint-disable arrow-parens */
import { cancelOrder, orderBuyAgain, orderPayCreate, queryOrderStatus, queryForOrderDetail, confirmTakeDelivery, confirmReceiveDelivery } from './service';
import { connect } from 'herculex';
import { tradePay } from '../../utils/tradePay';
import history from '../../utils/history';
Component(connect({
  mapStateToProps: {}
})({
  props: {
    componentData: {}
  },
  data: {
    loadMore: false,
    list: [],
    orderId: '',
    detailData: null,
    startPoll: false,
    btnText: '去支付',
    addressData: null
  },

  async didMount() {
    // eslint-disable-next-line prefer-const
    let {
      orderId = '',
      alipayTradeNo = '',
      poll = ''
    } = this.$page.data.query || my.getLaunchOptionsSync().query || {};

    if (!orderId) {
      orderId = getCurrentPages()[0].options.orderId || '';
    }

    this.orderId = orderId;
    this.alipayTradeNo = alipayTradeNo; // res :  {goods, ...rest }

    try {
      await this.queryDetail(orderId); // // poll 有值  默认开启轮询

      if (poll) {
        my.showLoading({
          content: '支付中...'
        });
        this.setData({
          startPoll: true,
          btnText: '支付中'
        }); // 支付

        await tradePay(alipayTradeNo, orderId);
      }
    } catch (error) {
      my.hideLoading();
      const {
        type = '',
        msg = ''
      } = error;

      if (type === 'cancel') {
        this.setData({
          startPoll: false,
          btnText: '去支付'
        });
      }

      my.showToast({
        type: 'fail',
        content: msg || '查询订单失败'
      });
    }
  },

  didUpdate() {},

  methods: {
    // 查询订单详情
    async queryDetail(orderId) {
      const res = await queryForOrderDetail({
        orderId
      }); // 订单详情

      const list = res.goods;
      const {
        addressInfo = {}
      } = res;
      this.setData({
        orderId,
        list,
        detailData: res,
        addressData: {
          name: addressInfo.userName || '',
          mobile: addressInfo.userPhone || '',
          latitude: addressInfo.latitude || '',
          longitude: addressInfo.longitude || '',
          address: addressInfo.detail || '',
          addressNumber: addressInfo.addressNumber || '',
          isDefault: addressInfo.status || '',
          provinceName: addressInfo.provinceName || '',
          cityName: addressInfo.cityName || '',
          districtName: addressInfo.districtName || ''
        }
      });
    },

    // 确认收货
    async onConfirmReceiveClick() {
      const {
        list = []
      } = this.data;
      my.confirm({
        title: '确认收货',
        content: `当前订单共${list.length}件商品,请收到实物无误后再确认收货`,
        success: async res => {
          if (res.confirm) {
            const {
              orderId
            } = this.data;

            try {
              const flag = await confirmReceiveDelivery({
                orderId
              });
              my.showToast({
                content: flag ? '收货成功' : '收货失败',
                type: 'none',
                success: () => {
                  this.queryDetail(orderId);
                }
              });
            } catch (err) {
              my.showToast({
                content: '收货失败',
                type: 'none'
              });
            }
          }
        }
      });
    },

    // 主动提货
    async onConfirmClick(e) {
      const {
        redeemQrValue
      } = e;
      const {
        list = []
      } = this.data;
      my.confirm({
        title: '确认提货',
        content: `当前订单共${list.length}件商品,请收到实物无误后再确认提货`,
        success: async res => {
          if (res.confirm) {
            const {
              orderId
            } = this.data;

            try {
              const flag = await confirmTakeDelivery({
                orderId,
                redeemCode: redeemQrValue
              });
              my.showToast({
                content: flag ? '提货成功' : '提货失败',
                type: 'none',
                success: () => {
                  this.queryDetail(orderId);
                }
              });
            } catch (err) {
              my.showToast({
                content: '提货失败',
                type: 'none'
              });
            }
          }
        }
      });
    },

    loadMoreItem() {
      this.setData({
        loadMore: true
      });
    },

    // 点击取消订单按钮
    handelCancel() {
      my.confirm({
        title: '',
        content: '确认取消订单吗？',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        success: result => {
          if (result.confirm) {
            // 发起请求
            this.publicOrderFun(async orderId => {
              await cancelOrder({
                orderId
              });
              this.navToDetail();
            });
          }
        }
      });
    },

    // 轮询结束进行的操作
    handelFunCallBack() {
      my.hideLoading();
      my.showToast({
        type: 'fail',
        content: '支付失败'
      });
      this.navToDetail();
    },

    // 执行的判断操作
    async handelStartFun() {
      const {
        payStatus = ''
      } = await queryOrderStatus({
        orderId: this.orderId
      });

      if (payStatus === 'PAYED') {
        this.setData({
          startPoll: false,
          btnText: '支付成功'
        });
        my.hideLoading();
        my.showToast({
          type: 'success',
          content: '支付成功'
        });
        this.navToDetail();
      }
    },

    // 去支付
    handelPay() {
      my.showLoading({
        content: '支付中...'
      });
      this.publicOrderFun(async orderId => {
        const {
          alipayTradeNo = '',
          status = ''
        } = await orderPayCreate({
          orderId
        });
        my.hideLoading(); // 无单号 云支付有错

        if (!alipayTradeNo) {
          return my.showToast({
            type: 'fail',
            content: '云支付失败'
          });
        } // 有支付单号 直接支付


        if (alipayTradeNo && status !== 'PAYED') {
          my.showLoading({
            content: '支付中...'
          });
          this.setData({
            startPoll: true,
            btnText: '支付中'
          });
          await tradePay(alipayTradeNo, orderId);
        }
      });
    },

    // 再来一单
    handelMoreOrder() {
      this.publicOrderFun(async orderId => {
        await orderBuyAgain({
          orderId
        });
        my.showToast({
          type: 'success',
          content: '已添加至购物车'
        });
        my.reLaunch({
          url: '/antbuilder/core/pages/home/index?pageCode=mall'
        });
      });
    },

    copyNum() {
      my.setClipboard({
        text: this.data.orderId
      });
      my.alert({
        title: '复制成功'
      });
    },

    // 跳转详情方法
    navToDetail() {
      history.replace({
        title: '订单详情',
        pageType: 'mallOrderDetail',
        query: {
          orderId: this.orderId
        },
        header: ''
      });
    },

    // 公共失败时展示toast
    async publicOrderFun(fn) {
      try {
        await fn(this.orderId);
      } catch (err) {
        my.hideLoading();
        const {
          type = '',
          msg = ''
        } = err; // 如果调取支付存在失败

        if (type === 'cancel') {
          this.setData({
            startPoll: false,
            btnText: '去支付'
          });
        }

        my.showToast({
          type: 'fail',
          content: msg || '请求失败'
        });
        this.navToDetail();
      }
    }

  }
}));