<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" />
  </div>
</template>
<script>
import groupBuyApi from '@/api/groupBuy';
import List from './components/List';
import { isApp, isWxMp } from '@/service/validation.service';
import sharePic from '@/components/sharePic';
import qs from 'qs';
import MpBridge from '@/service/mp';
import config from '@/config';
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: {}
    };
  },
  computed: {
    goodsShareInfo() {
      return this.$store.state.pay.goodsShareInfo;
    }
  },
  watch: {
    goodsShareInfo: {
      immediate: false,
      handler(val) {
        this.onShareEventChange(val);
      }
    }
  },
  mounted() {
    this.getstatusQuery();
    this.getList();
  },
  created() {
    this.nativeBridge = new MpBridge();
  },
  methods: {
    async outputPicUrl(posterUrl) {
      if (isApp) {
        // 如果是app环境直接调用app方法
        const shareInfo = await this.getShareData({ ...this.sharePicData, posterUrl });
        this.$store.dispatch('goods_share_open', shareInfo);
      }
      if (isWxMp) {
        // 如果是小程序则默认跳转小程序的海报保存页面
        this.nativeBridge.openNewUrl({
          newUrl: `/pages/goodshare/index?url=${encodeURIComponent(JSON.stringify(posterUrl))}`
        });
      }
    },
    async getShareData(shareInfo) {
      // 处理详情页面分享数据
      const linkPath = qs.stringify({
        skuNo: shareInfo.skuNo,
        groupBuyGroupId: shareInfo.groupBuyGroupId,
        goodsSpecialId: shareInfo.goodsSpecialId,
        activityId: shareInfo.activityId,
        templateId: shareInfo.templateId,
        templateDetailId: shareInfo.templateDetailId
      });
      let detailUrl = `${config.localHost}/groupBuy/skuInfoSmallPic?h=0&${linkPath}`;
      if (isWxMp) {
        detailUrl = `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(detailUrl))}`;
      }
      return Promise.resolve({
        title: shareInfo.skuName,
        desc: '',
        link: detailUrl, // 页面地址
        imgUrl: shareInfo.skuImg, // 图片地
        posterUrl: shareInfo.posterUrl
      });
    },
    async onShareEventChange({ ev, nativeBridge }) {
      const shareDic = await this.getShareData(this.sharePicData);
      if (ev === 'pic') {
        // 分享海报跳转小程序海报分享页面
        this.$refs.sharePic.createAndUploadPic();
      }
      if (ev === 'weixin') {
        // 分享朋友派发微信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(info) {
      try {
        const [res] = await groupBuyApi.getGroupShareInfo(info.orderNo);
        this.sharePicData = res;
        if (isWxMp) {
          // 如果是微信弹出底部框
          this.$store.dispatch('goods_share_open');
        }
        if (isApp) {
          // 如果是app则先调用创建海报组件
          this.$refs.sharePic.createAndUploadPic();
        }
      } catch (err) {
        console.log(err);
      }
    },
    handleOptionClick(info) {
      this.currentOrder = info;
      switch (info.eventType) {
        case 'share':
          this.openShareEvent(info);
          break;
        default:
          this.currentOrder = {};
          break;
      }
    },
    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>
