<template>
    <view class="coupon__order">
        <view class="coupon__order__header">
            <view class="popup__header__tabs">
                <tabs
                    :current="setTabIndex"
                    :swipeable="false"
                    v-bind="tabStyle"
                    @change="handleChangeTab"
                >
                    <tab
                        v-for="(item, i) in couponTabs"
                        :key="i"
                        :name="`${item.name}(${item.count})`"
                    ></tab>
                </tabs>
            </view>
        </view>
        <view class="coupon__order__content">
            <z-paging
                auto-show-back-to-top
                ref="paging"
                v-model="couponList"
                @query="transformQueryList"
                :fixed="false"
                height="100%"
                :to-bottom-loading-more-enabled="false"
                :loading-more-enabled="false"
            >
                <block v-for="(item, index) in couponList" :key="`${index}-${item.id}`">
                    <coupon-card :item="item" :activeTabName="activeTabName">
                        <template v-slot:selection>
                            <u-checkbox-group
                                v-if="tabStatus === CouponStatusEnum.AVALIABLE"
                                class="selection"
                            >
                                <u-checkbox
                                    v-model="item.defaultSelect"
                                    :name="item.id"
                                    @change="detail => handleSelect(detail, item)"
                                    shape="circle"
                                    active-color="#2979FF"
                                ></u-checkbox>
                            </u-checkbox-group>
                        </template>
                        <template #count>
                            <text class="count" v-if="item.alreadyGetCouponCount >= 2">
                                {{ parseText }}使用{{ item.alreadyGetCouponCount }}张
                            </text>
                        </template>
                        <template #expiringSoon>
                            <div class="expiring-soon" v-if="showExpiringSoon(item!)">快失效</div>
                        </template>
                    </coupon-card>
                </block>
            </z-paging>
        </view>
        <view class="coupon__order__btn" v-if="isVisibleConfirmBtn">
            <u-button type="primary" shape="circle" @click="handleSelectCoupon">确定</u-button>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, unref, watch, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useTabs, useZPaging } from '@/hooks/useCoupon'
import { apiCouponByUse, apiCouponCount } from '@/api/coupon'
import { Recordable } from '@/config/interface'
import { CouponCountMap, showExpiringSoonDays } from '@/enums/appEnums'
import { CouponStatusEnum } from '@/enums/appEnums'

const goodsId = ref()
const goodsCategoryId = ref()
const couponList = ref<any[]>([])
const couponTabs = ref<any[]>([])
const availableCount = ref(0) //可用数量

let selectedCouponInfo = reactive<Recordable<string>>({})

const { tabStatus, setTabIndex, handleChangeTab } = useTabs()
const { paging, queryList, refresh } = useZPaging({}, apiCouponByUse)

const isVisibleConfirmBtn = computed(
    () => unref(availableCount) > 0 && unref(tabStatus) === CouponStatusEnum.AVALIABLE
)
const tabStyle = computed(() => {
    return {
        height: 100,
        barWidth: 90,
        fontSize: 32,
        barStyle: { bottom: 0 },
        activeColor: '#1296DB'
    }
})
const parseText = computed(() => (unref(tabStatus) === CouponStatusEnum.AVALIABLE ? '可' : '不可'))
const activeTabName = computed(() => couponTabs.value[setTabIndex.value]?.name)
const showExpiringSoon = computed(() => {
    return (row: any) => {
        const { useTimeEnd, useStatus } = row
        const currentTime = new Date().getTime()
        const endTime = Date.parse(useTimeEnd)
        const daysDifference = Math.abs(endTime - currentTime) / (60 * 60 * 24 * 1000)
        return daysDifference <= showExpiringSoonDays && activeTabName.value == '可用优惠券'
    }
})

watch(
    () => unref(tabStatus),
    () => {
        const params = { usableStatus: unref(tabStatus) }
        refresh(params)
    }
)

/**选择优惠券 */
const handleSelect = (detail, item) => {
    const { name: id, value } = detail
    const selectedItem = unref(couponList).find(coupon => coupon.id === id)
    if (!selectedItem) return
    unref(couponList).forEach(coupon => {
        coupon.defaultSelect = false
    })
    selectedItem.defaultSelect = !selectedCouponInfo.defaultSelect
    value ? saveSelectItem(item) : (selectedCouponInfo = {})
}
/**确定 */
const handleSelectCoupon = async () => {
    if (Object.keys(selectedCouponInfo).length > 0) {
        paging.value.reload()
    } else {
        selectedCouponInfo = unref(couponList).find(i => i.defaultSelect) ?? []
    }
    uni.navigateBack()
    uni.$emit('selectCoupon', {
        selectedCouponInfo,
        availableCount: unref(availableCount)
    })
}

/**获取优惠券数量 */
const getCouponCount = async () => {
    const params = {
        goodsId: unref(goodsId),
        goodsCategoryId: unref(goodsCategoryId)
    }
    try {
        const res = await apiCouponCount(params)
        availableCount.value = res.availableCount
        couponTabs.value = Object.keys(res).map(key => {
            return {
                name: CouponCountMap[key],
                count: res[key]
            }
        })
    } catch (error) {}
}
onLoad(async options => {
    await setPayload(options)
    getCouponCount()
})

/**保存传递过来的参数 */
function setPayload(options: any) {
    const { goodsId: goodId, goodsCategoryId: categoryId, selectCoupon } = options
    const couponInfo = JSON.parse(selectCoupon)
    goodsId.value = goodId
    goodsCategoryId.value = categoryId
    if (!Object.keys(couponInfo).length) return
    saveSelectItem(couponInfo)
}

/**保存选中项内容 */
function saveSelectItem(item: any) {
    for (const key in item) {
        selectedCouponInfo[key] = item[key]
    }
}
function transformQueryList(page_no: number, page_size: number) {
    const config = {
        initParams: {
            goodsId: unref(goodsId),
            goodsCategoryId: unref(goodsCategoryId),
            usableStatus: unref(tabStatus),
            selectCouponId: selectedCouponInfo.id ?? ''
        }
    }
    return queryList(page_no, page_size, config.initParams)
}
</script>

<style lang="scss" scoped>
.coupon__order {
    display: flex;
    flex-direction: column;
    height: 100vh;

    &__header {
    }

    &__content {
        height: calc(100% - 100rpx);
        overflow: auto;

        .selection {
            position: absolute;
            right: -20rpx;
            top: 30rpx;

            :deep(.u-checkbox__icon-wrap) {
                background-color: $white;
            }
        }
    }

    &__btn {
        height: 120rpx;
        background-color: $white;
        padding: 20rpx 30rpx;
    }
}
.expiring-soon {
    position: absolute;
    background: #d83d3b;
    width: 162rpx;
    height: 32rpx;
    rotate: 26deg;
    top: -4px;
    right: -11px;
    font-size: 19rpx;
    line-height: 32rpx;
    padding-left: 53rpx;
}
</style>
