<template>
  <div class="page page__nopad">
    <cr-tabs
      v-model="currentTab"
      title-inactive-color="#333"
      sticky-inactive-color="#333"
      sticky
      z-index="4"
      @change="handleTabChange"
    >
      <cr-tab v-for="(item, index) in navList" :key="index" :title="item.title" :name="index">
        <list
          :list="item.list"
          :loading="item.loading"
          :finished="item.finished"
          @load="handleLoad"
          @option-click="handleOptionClick"
        />
      </cr-tab>
    </cr-tabs>
    <cancel-popup
      ref="cancelPopupRef"
      v-model="showCancelPopup"
      :order-info="currentOrder"
      @complete="handleCancelState"
      @refresh="refresh"
    />
    <cancel-popup-now
      v-model="showCancelPopupNow"
      :order-info="currentOrder"
      @complete="handleCancelState"
      @refresh="refresh"
    />
    <cr-action-sheet
      v-model="showExpressPopup"
      title="请选择物流单号"
      cancel-txt="关闭"
      round
      :actions="expressActions"
      @click="toExpress"
    />
    <RefundDialog
      v-model="refundImmediately"
      :refund-contract-info-list="refundContractInfoList"
      :cash-coupon-cancel-note="currentOrder.cashCouponCancelNote"
    />
  </div>
</template>
<script>
import orderApi from '@/api/order.api';
import List from './components/List';
import { isApp } from '@/service/validation.service';
import CancelPopup from './components/CancelPopup';
import CancelPopupNow from '../orderList/components/CancelPopupNow.vue';
import RefundDialog from '../orderList/components/RefundDialog.vue';
import localStorage from '@/service/localStorage.service';
import { REFUND_TYPE } from '../../constants/refund';
const commonParams = {
  loading: false,
  finished: false,
  page: 1,
  pageSize: 10,
  list: []
};
export default {
  name: 'OrderList',
  components: {
    List,
    CancelPopup,
    CancelPopupNow,
    RefundDialog
  },
  data() {
    return {
      REFUND_TYPE,
      isApp,
      showCancelPopup: false,
      showExpressPopup: false,
      showCancelPopupNow: false,
      refundImmediately: false,
      refundContractInfoList: [],
      currentTab: 0,
      navList: [
        {
          state: 0,
          title: '全部',
          ...JSON.parse(JSON.stringify(commonParams))
        },
        {
          state: 11,
          title: '待付款',
          ...JSON.parse(JSON.stringify(commonParams))
        },
        {
          state: 21,
          title: '待发货',
          ...JSON.parse(JSON.stringify(commonParams))
        },
        {
          state: 31,
          title: '待收货',
          ...JSON.parse(JSON.stringify(commonParams))
        },
        {
          state: 41,
          title: '已完成',
          ...JSON.parse(JSON.stringify(commonParams))
        }
      ],
      currentOrder: {},
      expressActions: [],
      orderStatusInfo: {},
      radio: 0
    };
  },
  mounted() {
    this.getStateQuery();
    this.getList();
    this.$track.registeredEvents('H5_2B_MyOrderPageExposure');
  },
  methods: {
    getStateQuery() {
      const { state } = this.$route.params || {};
      state && (this.currentTab = Number(state));
    },
    handleTabChange(name) {
      this.currentTab = name;
      this.getList();
    },
    handleLoad() {
      this.getList();
    },
    handleOptionClick(info) {
      const { orderInfo } = info || {};
      this.currentOrder = orderInfo;
      switch (info.eventType) {
        case 'cancel':
          this.orderCancelPopup();
          break;
        case 'pay':
          this.toPay();
          break;
        case 'notify':
          this.orderNotify();
          break;
        case 'again':
          this.toGoods();
          break;
        case 'logistics':
          this.expressActionsCheck();
          break;
        case 'confirm':
          this.orderConfirmPopup();
          break;
        case 'toRefund':
          this.orderRefundPopup(orderInfo);
          break;
        case 'refund':
          this.toRefund();
          break;
        default:
          this.currentOrder = {};
          break;
      }
    },
    async cancelOrder() {
      // this.$refs.cancelPopupRef.open();
      const [res, error] = await orderApi.orderCancelReasonV2({
        orderNo: this.currentOrder.orderNo
      });
      if (!error) {
        this.$refs.cancelPopupRef.reasonList = res.cancelReasonList;
        this.$refs.cancelPopupRef.iconAndTips = res.iconAndTips;
        this.showCancelPopup = true;
      }
      // let tip = {
      //   message: this.currentOrder.cancelNote,
      //   confirmButtonText: '仍要取消',
      //   cancelButtonText: '留下商品',
      //   onConfirm: () => {
      //     this.showCancelPopup = true;
      //   }
      // };
      // this.$dialog(tip);
    },
    async orderRefundPopup(obj) {
      if (obj.showCashCouponCancelNote) {
        // 调接口 判断是否 需要签合同
        const [data] = await orderApi.queryNote({
          orderNo: this.currentOrder.orderNo
        });
        if (data.noteNeedContract) {
          // 需要签合同 弹窗 点了解一下 验证是否勾选合同 合同可以点击跳转
          this.refundImmediately = true;
          this.refundContractInfoList = data.contractInfoList || [];
        } else {
          // 不需要签合同
          let tips = {
            title: '退款、退货须知',
            message: this.currentOrder.cashCouponCancelNote || this.currentOrder.cancelNote || '',
            confirmButtonText: '已了解',
            cancelButtonText: '取消',
            onConfirm: () => {
              this.cancelOrder();
            }
          };
          this.$dialog(tips);
        }
      } else {
        // 调取弹窗接口
        this.cancelOrder();
      }
    },
    orderCancelPopup() {
      if (this.currentOrder.paymentInProgress) {
        this.$dialog({
          message: '订单支付处理中，请稍后再试',
          confirmButtonText: '知道了',
          showCancelButton: false
        });
        return;
      }
      this.showCancelPopupNow = true;
    },
    // 售后中
    toRefund() {
      const currentSku = this.currentOrder.currentSku;
      let { afterServiceType, serviceStatus } = currentSku;
      let refundUrlName = '';
      // if (currentSku.havingService) {
      // if ([REFUND_TYPE.AUDITING, REFUND_TYPE.REFUNDING].includes(+serviceStatus)) {
      //   refundUrlName = 'refundOnlyDetail';
      // } else if ([REFUND_TYPE.AUDIT_PASS, REFUND_TYPE.POSTING].includes(+serviceStatus)) {
      //   refundUrlName = 'refundDetail';
      // } else {
      //   refundUrlName = 'refundType';
      // }
      //afterServiceType售后类型 1-仅退款 2-退货退款
      // 已经取消售后或者商家拒绝售后   重新走售后流程
      let isRefund = [REFUND_TYPE.CANCEL, REFUND_TYPE.UN_ACCEPT, REFUND_TYPE.AUDIT_REFUSE].includes(
        +serviceStatus
      );
      if (+afterServiceType === 1 && !isRefund) {
        refundUrlName = 'refundOnlyDetail';
      } else if (+afterServiceType === 2 && !isRefund) {
        refundUrlName = 'refundDetail';
      } else {
        refundUrlName = 'refundType';
      }
      const urlDetail = refundUrlName;
      localStorage.set('orderInfo', this.currentOrder);
      this.$router.push({
        name: urlDetail,
        query: {
          orderSkuId: currentSku.orderSkuId,
          orderNo: this.currentOrder.orderNo
        }
      });
      // }
      // if ([2, 5, 6].indexOf(currentSku.skuSource) > -1) {
      //   this.$dialog({
      //     message: '您购买的商品确认收货后才可以申请售后哦！',
      //     confirmButtonText: '知道了',
      //     showCancelButton: false
      //   });
      //   return;
      // }
    },
    toPay() {
      if (this.currentOrder.paymentInProgress) {
        this.$dialog({
          message: '支付中，请勿重复支付',
          confirmButtonText: '知道了',
          showCancelButton: false
        });
        return;
      }
      this.$router.push({ name: 'pay', query: { orderNo: this.currentOrder.orderNo } });
    },
    toGoods() {
      this.$router.push({
        path: '/goodDetail',
        query: { skuNo: this.currentOrder.skuList[0].skuNo }
      });
    },
    orderConfirmPopup() {
      if (!this.currentOrder.orderNo) return;
      this.$dialog({
        title: '确定该订单已收货吗？',
        onConfirm: () => {
          orderApi
            .orderConfirm({
              orderNo: this.currentOrder.orderNo,
              status: 41
            })
            .then(res => {
              if (res[0]) {
                this.updateCurrentOrder(41, '交易完成');
                this.$toast('操作成功');
              }
            });
        }
      });
    },
    refresh() {
      setTimeout(() => {
        window.history.go(0);
      }, 500);
    },
    handleCancelState() {
      this.updateCurrentOrder(51, '交易关闭');
    },
    updateCurrentOrder(state, txt) {
      this.$set(this.navList[this.currentTab].list[this.currentOrder.index], `orderStatus`, state);
      this.$set(
        this.navList[this.currentTab].list[this.currentOrder.index],
        `orderStatusText`,
        txt
      );
    },
    expressActionsCheck() {
      const { expressInfoList } = this.currentOrder;
      if (expressInfoList.length > 1) {
        this.expressActions = expressInfoList.map(item => {
          return {
            name: item.deliveryNo,
            deliveryNo: item.deliveryNo,
            expressCompanyCode: item.expressCompanyCode
          };
        });
        this.showExpressPopup = true;
      } else {
        this.toExpress(expressInfoList[0]);
      }
    },
    toExpress(item) {
      // 物流信息传参，订单号对应于orderNo，根据expressCompanyCode（公司编码）和deliveryNo（物流单号）是否存在判断传参
      const { expressCompanyCode, deliveryNo } = item;
      this.$router.push({
        path: '/expressDetail',
        query: deliveryNo
          ? { expressCompanyCode, deliveryNo, orderNo: this.currentOrder.orderNo }
          : { deliveryOrderId: this.currentOrder.orderNo, orderNo: this.currentOrder.orderNo }
      });
    },
    orderNotify() {
      this.$toast.success('已通知卖家');
    },
    setNavListData(key, val) {
      this.$set(this.navList[this.currentTab], key, val);
    },
    async getList() {
      let { finished, page, pageSize, list, state: orderStatus } = this.navList[this.currentTab];
      if (finished) return;
      this.setNavListData('loading', true);
      const [res] = await orderApi.orderList({
        pageNo: page,
        pageSize,
        orderStatus
      });
      if (res) {
        this.setNavListData('loading', false);
        list = [...list, ...res.orderList];
        this.setNavListData('list', list);
        if (!res.hasNext) {
          this.setNavListData('finished', true);
        } else {
          page++;
          this.setNavListData('page', page);
        }
      }
    }
  }
};
</script>
<style lang="less" src="./index.less" scoped></style>
