<template>
  <div class="my-all-order">
    <!-- 顶部tab -->
    <div class="status-tab">
      <div class="zy-top-tab">
        <div class="tab-item" v-for="(item, i) in tabData" :key="item.key" @click="tabClick(i)">
          <badge :count="item.count || 0">
            <div class="tab-text" :class="{'active': currentIndex === i}">{{item.name}}</div>
          </badge>
          <div :class="{
              'bottom-border': true
          }" v-show="currentIndex === i" ></div>
        </div>
        <!-- <div :class="{
          'bottom-border': true,
          'four-1': tabData.length === 4 && currentIndex === 0,
          'four-2': tabData.length === 4 && currentIndex === 1,
          'four-3': tabData.length === 4 && currentIndex === 2,
          'four-4': tabData.length === 4 && currentIndex === 3,
          'three-1': tabData.length === 3 && currentIndex === 0,
          'three-2': tabData.length === 3 && currentIndex === 1,
          'three-3': tabData.length === 3 && currentIndex === 2,
          'two-1': tabData.length === 2 && currentIndex === 0,
          'two-2': tabData.length === 2 && currentIndex === 1
        }"></div> -->
      </div>
    </div>
    <!-- 中间内容 -->
    <div class="content">
      <!-- 商品 -->
      <div class="order-item"
        v-for="(order,index) in orderList"
        :key="index"
        @click="toDetail(order)"
      >
        <order-cell
          :order="order"
          @on-click="handleOp"
          @refreshPage="refreshPage"
        ></order-cell>
      </div>
      <!-- 没有查到商品 -->
      <div class="no-order" v-if="noOrderShow">
        <no-list msg="这里没有订单" img="img-noOrders"></no-list>
      </div>
    </div>
    <!-- loading -->
    <zy-loading></zy-loading>
  </div>
</template>

<script>
import {errToast, toast,modal, openWeixinMiniprogram, jumpPage} from '@/utils/uniapi.js'
import orderCell from '../orderCmp/order-cell/order-cell.vue'
import NoList from '@/components/commonCmp/list-none.vue'
import ZyLoading from '@/components/Loading/loading'
import {mapGetters,mapActions} from 'vuex'
import {store} from '@/store'

import goodPage from '@/apis/goodPage';
import orderPage from '@/apis/orderPage'
import { handleCreatePay } from '@/utils/uniapi.js'
export default {
  components: {
    orderCell, NoList, ZyLoading
  },
  data () {
    return {
      tabData: [
        {
          key: 'all',
          name: '全部',
          statuss: []
        },
        {
          key: 'waitPay',
          name: '待支付',
          count: 0,
          statuss: [2]
        },
        {
          key: 'waitReceive',
          name: '待收货',
          statuss: [5, 10, 15, 17, 18, 20]
        },
        {
          key: 'waitComment',
          name: '待评价',
          statuss: [110]
        }
      ],
      currentIndex: 0,
      orderList: [],
      totalCount: 0,
      pageSize: 10,
      page: 1,
      noOrderShow: false,
      isOnLoad: false
    }
  },
  async onShow () {
    if (!this.isOnLoad) {
      this.isOnLoad = true
    } else if (this.currentIndex !== 0) {
      try {
        this.showLoad()
        // 请求订单数量
        await this.handleGetOrderCount()
        // 请求订单
        await this.getOrders()
      } catch (e) {
        console.error(e)
        errToast(e)
      } finally {
        this.hideLoad()
      }
    }
  },
  async onLoad (query) {
    // console.log(query)
    try {
      if (query.name) {
        // 找到当前的tab index
        this.currentIndex = this.tabData.findIndex(item => item.key === query.name)
      }
      this.showLoad()
      // 查询订单数量
      await this.handleGetOrderCount()
      // 查询订单
      await this.getOrders()
    } catch (e) {
      console.log(e)
      errToast(e)
    } finally {
      this.hideLoad()
    }
  },
  async onPullDownRefresh () {
    console.log('下拉刷新')
    // uni.stopPullDownRefresh()
    try {
      this.showLoad()
      // 请求订单数量
      await this.handleGetOrderCount()
      // 请求订单
      await this.getOrders()
      // await new Promise(resolve => {
      //   setTimeout(() => {
      //     resolve()
      //   }, 2000)
      // })
    } catch (e) {
      console.error(e)
      errToast(e)
    } finally {
      uni.stopPullDownRefresh()
      this.hideLoad()
    }
  },
  async onReachBottom () {
    console.log('到底加载更多')
    try {
      this.showLoad()
      if (this.page * this.pageSize < this.totalCount) {
        this.page += 1
        await this.getOrders((this.page - 1) * this.pageSize)
      } else {
        toast('没有更多')
      }
    } catch (e) {
      errToast(e)
    } finally {
      this.hideLoad()
    }
  },
  computed: {
    ...mapGetters({
      storeMap:"indexPage/storeMap",
      isMaterial: "indexPage/isMaterial",
      storeID: "indexPage/storeID",
      materialInfo: "indexPage/materialInfo"
    })
  },
  methods: {
    ...mapActions({
      clearAllShopCar: 'cartPage/clearAllShopCar',
      changeCar: "cartPage/changeCar"
    }),
    // 刷新页面
    async refreshPage() {
      try {
        this.showLoad()
        // 请求订单数量
        await this.handleGetOrderCount()
        // 请求订单
        await this.getOrders()
        // await new Promise(resolve => {
        //   setTimeout(() => {
        //     resolve()
        //   }, 2000)
        // })
      } catch (e) {
        console.error(e)
        errToast(e)
      } finally {
        // uni.stopPullDownRefresh()
        this.hideLoad()
      }
    },
    // 请求订单数量
    async handleGetOrderCount () {
      try {
        let {waitCount, deliverCount} = await orderPage.getOrderCount()
        this.tabData[1].count = waitCount
        this.tabData[2].count = deliverCount
      } catch (e) {
        console.log(e)
      }
    },
    // 请求订单
    async getOrders (offset = 0) {
      try {
        this.noOrderShow = false
        // 请求前处理
        if (!offset) {
          this.orderList = []
        }
        let {totalCount, data} = await orderPage.getMyOrders({
          statuss: JSON.stringify(this.tabData[this.currentIndex].statuss),
          offset
        })

        // #ifdef MP-WEIXIN
        if (this.isMaterial) {
          data = data.filter(item => item.storeID === 666666)
          totalCount = data.length || 0
        }
        // #endif

        this.totalCount = totalCount
        if (offset) {
          this.orderList = [...this.orderList, ...data]
        } else {
          this.orderList = data
          this.page = 1
        }
        if(this.orderList.length === 0) this.noOrderShow = true
      } catch (e) {
        throw e
      }
    },
    // 点击切换Tab
    async tabClick (index) {
      // console.log(index)
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
      if (this.currentIndex !== index) {
        this.currentIndex = index
        try {
          this.showLoad()
          // 查询订单数量
          await this.handleGetOrderCount()
          // 查询订单
          await this.getOrders()
        } catch (e) {
          console.error(e)
          errToast(e)
        } finally {
          this.hideLoad()
        }
      }
    },
    // 到订单详情页面
    toDetail (order) {
      // console.log('到订单详情页面', order)
      jumpPage('navigateTo',`/pagesOrders/order-detail/index?vendorOrderID=${order.vendorOrderID}`)
    },
    // 操作
    async handleOp ({key, order}) {
      if (key === 'repay') {
        // 重新支付
        try {
          this.showLoad()
          // 获取支付信息

          let payInfo = null

          // #ifdef MP-WEIXIN
          payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 2,
            vendorPayType: 'W06',
            subAppID: "wx4b5930c13f8b1170",
          });
          await handleCreatePay(payInfo.vendorOrderID, payInfo.prepayID, JSON.parse(payInfo.codeURL))
          // #endif

          // #ifdef MP-TOUTIAO
          payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 3,
            vendorPayType: 'tt',
            // subAppID: "tta6a1d01c399f264201",
            subAppID: "ttaceeda5333d7a7ab01",
          });
          await handleCreatePay(payInfo.vendorOrderID, payInfo.prepayID, payInfo.codeURL,payInfo)
          // #endif

           // #ifdef MP-KUAISHOU
           payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 4,
            vendorPayType: 'ks',
            subAppID: "ks680887971696897880",
           })
          //  console.log('打印快手支付信息',payInfo)
           await handleCreatePay(payInfo.vendorOrderID, payInfo.prepayID, payInfo.codeURL,payInfo)
          // #endif

          // #ifdef APP-PLUS || APP
          let res = await modal("温馨提示", '为了保证您的账户安全，即将跳转到微信进行支付');

          if (res) {
            let jxParams = {
            "origin": "weixinappcs",
            "vendorOrderID": order.vendorOrderID,
            "storeID": order.storeID,
            "name":order.storeName,
            "totalPrice":order.actualPayPrice
          }
            openWeixinMiniprogram(`JX-pay/JX-pay?jxParams=${JSON.stringify(jxParams)}`)
          }
        
          // #endif

          // #ifdef MP-ALIPAY
          payInfo = await orderPage.pay4Order({
            vendorOrderID: order.vendorOrderID,
            payType: 2,
            vendorPayType: 'A02',
          });
          await handleCreatePay(
            payInfo.vendorOrderID,
            payInfo.prepayID,
            payInfo.codeURL
          );
          // #endif

          // console.log('打印payInfo信息', payInfo)

          this.tabClick(2)
        } catch (e) {
          console.error(e)
          if ('errKey' in e) {
            errToast('订单支付失败，请稍后重试')
          } else {
            errToast(e)
          }
        } finally {
          this.hideLoad()
          // 查询订单数量
          await this.handleGetOrderCount()
          // 查询订单
          await this.getOrders()
        }
      } else if (key === 'rebuy') {
        // 再来一单
        // 请求商品
        try {
          this.showLoad()
          let {skuNames} = await goodPage.getStoresSkus({
            skuIDs: Array.from(new Set(order.skuList.map(item => item.skuID))),
            storeID: order.storeID
          })
          // console.log(skuNames)

          // #ifdef MP-WEIXIN
          if (this.isMaterial && this.materialInfo && this.materialInfo.fromStoreInfo.packageSwitch === 1) return toast(`非常抱歉,无法购买物料，请联系运营${this.materialInfo.fromStoreInfo.marketManPhone}`)
          // #endif

          if (skuNames.length > 0) {
            // 把数量加上
            skuNames.forEach((skuName, i) => {
              let findItem = order.skuList.filter(item => item.skuID === skuName.id)
              console.log(findItem, skuNames[i])
              if (findItem) {
                skuNames[i].count = findItem.reduce((prev, next) => prev + next.skuCount2, 0)
              }
            })
            console.log(skuNames)
            store.commit('indexPage/changeStoreID', [order.storeID])

            // 获取单门店的数据信息，保存到storeMap中
            if (!(this.storeMap && this.storeMap[this.storeID[0]])) await store.dispatch('indexPage/getStoreInfo',{storeID:this.storeID[0]})

            await this.clearAllShopCar()  // 清空购物车
            await this.changeCar({  // 放入购物车
              skuName: skuNames,
            });

            
            // 跳转到购物车页面
            // #ifndef MP-TOUTIAO || APP-PLUS
            jumpPage('switchTab','/pages/cart/index')
            // #endif
                  
            // #ifdef MP-TOUTIAO || APP-PLUS
            jumpPage('navigateTo','/pages/cart/index')
            // #endif
          } else {
            throw new Error('订单商品已下架')
          }
        } catch (e) {
          console.error(e)
          errToast(e)
        } finally {
          this.hideLoad()
        }
      } else if (key === 'received') {
        toast('暂无功能')
      }
    }
  }
}
</script>

<style lang="scss">
@import './my-order.scss';
page {
  background-color: #f4f4f4;
}
</style>