<template>
  <div class="create-afsorder">
    <div class="title">请选择退款商品</div>
    <div class="skuList">
      <div class="sku-item" v-for="(sku, index) in skuList" :key="index">
        <SkuCell
          :sku="sku"
          :index="index"
          @plus="handlePlus"
          @minus="handleMinus"
        ></SkuCell>
      </div>
    </div>
    <div class="title">请选择退款理由</div>
    <div class="reasons">
      <div class="reason-item" :class="{'active': currentIndex === index}" v-for="(item, index) in afsOrderReasons" :key="index" @click="handlePick(index)">{{item}}</div>
    </div>
    <!-- <div class="cell">
      <div class="left">已选数量:</div>
      <div class="right">{{totalCount}}</div>
    </div> -->
    <div class="bottom-bar">
      <div class="left">已选数量: {{totalCount}}</div>
      <div class="right">
        <div class="btn" @click="handleCreateAfs">发起售后</div>
      </div>
    </div>
    <ZyLoading></ZyLoading>
  </div>
</template>

<script>
import {errToast, alert, toast, modal} from '@/utils/uniapi.js'
import ZyLoading from '@/components/Loading/loading'
import {afsOrderReasons} from '@/config'
import SkuCell from '../afsOrderCmp/pick-sku-cell.vue'
import {debounce} from '@/utils'
import { mapGetters } from "vuex";
import orderPage from '@/apis/orderPage'

export default {
  components: {
    ZyLoading, SkuCell
  },
  data () {
    return {
      vendorOrderID: '',
      vendorID: null,
      skuList: [],
      currentIndex: 0
    }
  },
  computed: {
    ...mapGetters({
      isLogin: "login/isLogin",
    }),
    afsOrderReasons: () => afsOrderReasons,
    totalCount () {
      return this.skuList.map(item => +item.currentCount).reduce((prev, next) => prev + next, 0)
    },
    refundSkuList () {
      return this.skuList.filter(item => item.currentCount).map(item => ({
        skuID: item.skuID,
        count: item.currentCount,
        storeSubID: item.storeSubID
      }))
    }
  },
  async onLoad (query) {
    const {vendorOrderID, vendorID} = query
    // console.log(vendorOrderID, vendorID)
    this.vendorOrderID = vendorOrderID
    this.vendorID = vendorID
    await this.pageInit()
  },
  destroyed() {
    uni.removeStorageSync('createAfsOrder')
  },
  methods: {
    getTimeFormDate(time) {
      let str = ''
      let y = time.getFullYear()                // 年
      let m = time.getMonth() +1                // 月
      let d = time.getDate()                    // 日
      let h = time.getHours()                   // 时
      let min = time.getMinutes()               // 分
      let ss = time.getSeconds()                // 秒
      let millisecond = time.getMilliseconds()  // 毫秒

      m = ('' + m).length >= 2 ? '' + m : '0' + m
      d = ('' + d).length >= 2 ? '' + d : '0' + d
      h = ('' + h).length >= 2 ? '' + h : '0' + h
      min = ('' + min).length >= 2 ? '' + min : '0' + min
      ss = ('' + ss).length >= 2 ? '' + ss : '0' + ss
      str = y + '-' + m + '-' + d + 'T' + h + ':' + min + ':' + ss + '.' + millisecond + '0000' + '+08:00'
      return str
    },
    async pageInit () {
      try {
        this.showLoad()
        const reqArr = [
          orderPage.getOrderSkuInfo(this.vendorOrderID, this.vendorID),
          orderPage.getAfsOrderSkuInfo({vendorOrderID:this.vendorOrderID, vendorID:this.vendorID, isNotFaild:true})
        ]
        const [orderSkus, afsOrderSkus] = await Promise.all(reqArr)
        if (afsOrderSkus) {
          // 剪掉已售后商品
          afsOrderSkus.forEach(afsSku => {
            // skuID count
            const findItem = orderSkus.find(item => item.skuID === afsSku.skuID && item.storeSubID === afsSku.storeSubID)
            if (findItem) {
              findItem.count -= afsSku.count
            }
          })
        }
        this.skuList = orderSkus.map(item => ({
          skuID: item.skuID,
          name: item.skuName,
          currentCount: 0,
          count: item.count,
          storeSubID: item.storeSubID,
          salePrice: item.salePrice,
          image: item.image,
          orderSkus: orderSkus,
          afsOrderSkus: afsOrderSkus

        }))
      } catch (e) {
        this.$alertBack(e)
      } finally {
        this.hideLoad()
      }
    },
    handlePlus (index) {
      console.log(index)
      this.skuList[index].currentCount += 1
      this.$set(this.skuList, index, this.skuList[index])
    },
    handleMinus (index) {
      console.log(index)
      this.skuList[index].currentCount -= 1
      this.$set(this.skuList, index, this.skuList[index])
    },
    handlePick (index) {
      this.currentIndex = index
    },
    handleCreateAfs: debounce(async function () {
      const { totalCount, afsOrderReasons, currentIndex} = this
      if (!totalCount) {
        toast('请选择退款商品')
        return false
      }
      try {
        this.showLoad()

        let afsOrder = uni.getStorageSync('createAfsOrder')
        let afsCreatedAt = await this.getTimeFormDate(new Date())

        let obj = {
          appKey: '4A86853D-E4B6-454E-940A-B68ECDA2B73E',
          msgType: 'afsOrder',
          subMsgType: 155,
          thingID: Number(afsOrder.vendorOrderID),
          thingID2:Number(afsOrder.vendorOrderID),
          timestamp: 1680835152
        }
        let data = {
          vendorOrderID: afsOrder.vendorOrderID,
          afsOrderID: "",
          afsCreatedAt,
          vendorStoreID: '' + afsOrder.storeID,
          vendorStatus: "neworder",
          vendorReasonType: "2002",
          reasonDesc: afsOrderReasons[currentIndex],
          reasonImgList: "",
          vendorAppealType: "1",
          skus:[]
        }


        this.skuList.map(item => {
          if (item.currentCount !== 0) {
            data.skus.push({
              vendorSkuID:'' + item.skuID,
              promotionType: 1,
              name: item.name,
              salePrice: item.salePrice,
              count:item.currentCount
            })
          }
        })

        obj.data = JSON.stringify(data)

        await orderPage.applyAfterSale(obj)
        toast('申请成功，待商家审核')
      } catch (e) {
        errToast(e)
      } finally {
        this.hideLoad()
      }
    }, 1000, true)
  }
}
</script>

<style lang="scss">
@import "create-afsorder";
</style>