import { connect } from 'herculex';
import { scenicOrderDetail, scenicOrderRefundApply, scenicOrderRefundDo } from '../../../services';
import { cancellationOfOrder, payImmediately } from '../utils';
import { createSubscribe } from 'applet-page-component'; // 我的订单详情
// 各种状态

const status = [{
  title: '待付款',
  desc: '超时未付款，订单将自动关闭',
  value: '0'
}, {
  title: '预订成功，出票中',
  desc: '系统出票中，请耐心等候～',
  value: '1'
}, {
  title: '预订成功，待消费',
  desc: '请合理安排行程，避免门票过期导致无法使用，造成不必要的损失～',
  value: '2'
}, {
  title: '已使用',
  desc: '祝您旅途愉快～',
  value: '3'
}, {
  title: '已取消',
  desc: '订单已关闭',
  value: '4'
}, {
  title: '退票审核中',
  desc: '退票申请以提交，等待审核门票是否已使用,将在3个工作日内完成审核',
  value: '5'
}, {
  title: '已退票',
  desc: '退票成功，购票金额将返回您原来的账户中～',
  value: '6'
}, {
  title: '已过期',
  desc: '订单已过期',
  value: '7'
}];

function convertLength(length) {
  return Math.round(my.getSystemInfoSync().windowWidth * length / 750);
}

Component(connect({
  mapStateToProps: {
    titleBarHeight: state => state.$global.titleBarHeight,
    // axml文件用
    bannerColor: state => state.$global.bannerColor // axml文件用

  }
})(createSubscribe({
  onPullDownRefresh() {
    // 下拉刷新页面
    this.scenicOrderDetail(true);
  }

})({
  props: {
    componentData: {}
  },
  data: {
    status,
    record: {},
    loading: true,
    noData: false,
    visibleRefund: false,
    // 退款可见
    refund: {} // 退款相关

  },

  didMount() {
    my.setNavigationBar({
      title: '订单详情'
    });
    this.scenicOrderDetail();
  },

  didUnmount() {
    clearTimeout(this.timer);
  },

  methods: {
    // 查询详情
    async scenicOrderDetail(pullDown = false) {
      this.setData({
        noData: false
      });

      if (pullDown === false) {
        this.setData({
          loading: true
        });
      }

      const {
        orderId
      } = this.$page.$routeConfig.query;
      const [, result] = await scenicOrderDetail({
        orderId
      });

      if (result && result.touristList) {
        result.qrcodeList = await this.createQrcode(result);
      }

      if (result.orderStatus === '2') {
        this.timerQrcode();
      } // result.orderStatus = '2';


      await this.setData({
        loading: false,
        noData: !result,
        record: result
      });
      pullDown && my.stopPullDownRefresh();
    },

    // 轮询
    timerQrcode() {
      const {
        refreshTime
      } = this.props.componentData.componentExtInfo;

      if (!refreshTime) {
        return;
      }

      const {
        orderId
      } = this.$page.$routeConfig.query;
      this.timer = setTimeout(async () => {
        const [err, result] = await scenicOrderDetail({
          orderId
        });

        if (err) {
          return;
        }

        if (result.touristList.length !== this.data.record.touristList.length) {
          result.qrcodeList = await this.createQrcode(result);
          this.setData({
            record: result
          });
        }

        this.timerQrcode();
      }, Number(refreshTime) * 1000);
    },

    // 创建二维码
    async createQrcode(record) {
      const qrcodeList = record.touristList.filter(item => item.ticketCode);
      const width = convertLength(320);
      const promises = qrcodeList.map(item => {
        return new Promise(resolve => {
          my.call('generateImageFromCode', {
            code: item.ticketCode,
            format: 'QRCODE',
            width,
            correctLevel: 'H'
          }, result => {
            resolve(result.image);
          });
        });
      });
      const images = await Promise.all(promises);
      return qrcodeList.map((item, index) => ({ ...item,
        qrcodeSrc: images[index]
      }));
    },

    // 取消订单
    async onCancel({
      target: {
        dataset: {
          record
        }
      }
    }) {
      await cancellationOfOrder({
        orderId: record.orderId
      });
      this.scenicOrderDetail();
    },

    // 立即支付
    async onPayment({
      target: {
        dataset: {
          record
        }
      }
    }) {
      await payImmediately({
        orderId: record.orderId
      });
      this.scenicOrderDetail();
    },

    // 显示申请退款
    async showRefund() {
      const {
        record
      } = this.data;
      my.showLoading();
      const [err, result] = await scenicOrderRefundApply({
        orderId: record.orderId
      });
      my.hideLoading();

      if (err) {
        return;
      }

      this.setData({
        visibleRefund: true,
        refund: result
      });
    },

    // 关闭申请退款
    hideRefund() {
      this.setData({
        visibleRefund: false
      });
    },

    // 申请退款
    async refund() {
      my.showLoading();
      const {
        orderId,
        quantity,
        touristList
      } = this.data.record;
      const [err] = await scenicOrderRefundDo({
        orderId,
        refundNum: quantity,
        touristsId: JSON.stringify(touristList.map(item => item.id))
      });
      my.hideLoading();

      if (err) {
        return;
      }

      my.pageScrollTo({
        scrollTop: 0
      });
      this.hideRefund();
      this.scenicOrderDetail();
    }

  }
})));