<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>
    <share-pic ref="sharePic" :share-pic-data="sharePicData" @outputPicUrl="outputPicUrl" />
    <!-- <cr-action-sheet
      v-model="showExpressPopup"
      title="请选择物流单号"
      cancel-txt="关闭"
      round
      :actions="expressActions"
      @click="toExpress"
    /> -->
  </div>
</template>
<script>
import groupBuyApi from '@/api/groupBuy';
import List from './components/List';
import { isApp } from '@/service/validation.service';
import localStorage from '@/service/localStorage.service';
import { EventBus } from '@/service/utils.service';
import sharePic from '@/components/sharePic';
import qs from 'qs';
import MpBridge from '@/service/mp';
const commonParams = {
  loading: false,
  finished: false,
  page: 1,
  pageSize: 5,
  list: []
};
export default {
  name: 'OrderList',
  components: {
    List,
    sharePic
  },
  data() {
    return {
      isApp,
      nativeBridge: null,
      sharePicData: {},
      showCancelPopup: false,
      showExpressPopup: false,
      currentTab: 0,
      // -1-全部  1-拼团中,未支付  2-拼团成功
      navList: [
        {
          status: -1,
          title: '全部',
          ...JSON.parse(JSON.stringify(commonParams))
        },
        {
          status: 1,
          title: '拼团中',
          ...JSON.parse(JSON.stringify(commonParams))
        },
        {
          status: 2,
          title: '已成团',
          ...JSON.parse(JSON.stringify(commonParams))
        }
      ],
      currentOrder: {},
      expressActions: [],
      orderStatusInfo: {}
    };
  },
  mounted() {
    this.getstatusQuery();
    this.getList();
    this.onShareEventChange();
  },
  beforeDestroy() {
    EventBus.$off('shareClickItem');
  },
  created() {
    this.nativeBridge = new MpBridge();
  },
  methods: {
    outputPicUrl(posterUrl) {
      this.nativeBridge.openNewUrl({
        newUrl: `/pages/goodshare/index?url=${encodeURIComponent(JSON.stringify(posterUrl))}`
      });
    },
    async getShareData(shareInfo) {
      const linkPath = qs.stringify({
        h: 0,
        skuNo: shareInfo.skuNo,
        groupBuyGroupId: shareInfo.activityHundredGroupId,
        goodsSpecialId: shareInfo.specialId,
        activityId: shareInfo.activityInfoId,
        templateId: shareInfo.templateId,
        templateDetailId: shareInfo.templateId
      });
      const detailUrl = `${window.location.origin}/groupBuy/skuInfoSmallPic?${linkPath}`;
      return Promise.resolve({
        title: shareInfo.skuName,
        link: `pages/webview/webview?url=${encodeURIComponent(JSON.stringify(detailUrl))}`, // 页面地址
        imgUrl: shareInfo.skuImg // 图片地
      });
    },
    onShareEventChange() {
      const vm = this;
      EventBus.$on('shareClickItem', async function({ ev, nativeBridge }) {
        const shareDic = await vm.getShareData(vm.sharePicData);
        console.log(shareDic);
        if (ev === 'pic') {
          vm.$refs.sharePic.createAndUploadPic();
          // 分享海报跳转小程序海报分享页面
        }
        if (ev === 'weixin') {
          // const res = await groupBuyApi.getGroupShareInfo(this.shareInfo.order);
          // 分享朋友派发微信postMessage事件
          nativeBridge.run({
            event: 'showShareView',
            data: {
              shareDic
            }
          });
        }
      });
    },
    getstatusQuery() {
      const { status } = this.$route.params || {};
      status && (this.currentTab = Number(status));
      console.log(this.currentTab);
    },
    handleTabChange(name) {
      this.currentTab = name;
      this.getList();
    },
    handleLoad() {
      this.getList();
    },
    async openShareEvent() {
      try {
        const [res] = await groupBuyApi.getGroupShareInfo('1440884214932389888');
        console.log(res);
        this.sharePicData = res;
        this.$store.dispatch('goods_share_open');
      } catch (err) {
        console.log(err);
      }
    },
    handleOptionClick(info) {
      console.log(info);
      this.currentOrder = info;
      switch (info.eventType) {
        case 'share':
          this.openShareEvent();
          break;
        default:
          this.currentOrder = {};
          break;
      }
    },
    orderRefundPopup(cashCouponCancelNote, showCashCouponCancelNote) {
      let tips = {
        message: this.currentOrder.cancelNote || '宝贝马上就要发货了，您真的要取消吗？',
        confirmButtonText: '仍要取消',
        cancelButtonText: '留下商品',
        onConfirm: () => {
          this.showCancelPopup = true;
        }
      };
      if (
        this.currentOrder.skuList[0].skuSource === 5 ||
        this.currentOrder.skuList[0].skuSource === 6
      ) {
        tips = {
          message: '该商品暂不支持取消，您可以在收货时直接拒收，钱款原路退回付款账户中',
          confirmButtonText: '知道了',
          showCancelButton: false
        };
      }
      if (showCashCouponCancelNote) {
        tips = {
          message: cashCouponCancelNote,
          confirmButtonText: '确认退货',
          cancelButtonText: '不退了',
          onConfirm: () => {
            this.showCancelPopup = true;
          }
        };
      }
      this.$dialog(tips);
    },
    orderCancelPopup() {
      this.showCancelPopup = true;
    },
    // 售后中
    toRefund() {
      if (this.currentOrder.currentSku.havingService) {
        localStorage.set('orderInfo', this.currentOrder);
        this.$router.push({
          name: 'refundDetail'
        });
        return;
      }
      if ([2, 5, 6].indexOf(this.currentOrder.currentSku.skuSource) > -1) {
        this.$dialog({
          message: '您购买的商品确认收货后才可以申请售后哦！',
          confirmButtonText: '知道了',
          showCancelButton: false
        });
        return;
      }
    },
    toPay() {
      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('操作成功');
      //         }
      //       });
      //   }
      // });
    },
    handleCancelstatus() {
      this.updateCurrentOrder(51, '交易关闭');
    },
    updateCurrentOrder(status, txt) {
      this.$set(this.navList[this.currentTab].list[this.currentOrder.index], `orderStatus`, status);
      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) {
      this.$router.push({
        path: '/expressDetail',
        query: { ...item, deliveryOrderId: 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, status } = this.navList[this.currentTab];
      if (finished) return;
      this.setNavListData('loading', true);
      const [res] = await groupBuyApi.getGroupOrderList({
        pageNo: page,
        pageSize,
        status
      });
      // console.log(res.records);
      if (res?.records?.length) {
        this.setNavListData('loading', false);
        list = [...list, ...res.records];
        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>
