<template>
    <el-dialog v-model="showDialog" title="选择优惠券" top="12vh" width="80%" @closed="resetHandle">
        <el-radio-group v-model="querForm.statusActiveIndex" @change="typeChange">
            <el-radio-button :label="`商品兑换券（${goodsCoupon.length}）`" :value="0"></el-radio-button>
            <el-radio-button :label="`折扣优惠券（${discountCoupon.length}）`" :value="1"></el-radio-button>
        </el-radio-group>
        <div style="height: 50vh;overflow-y: auto;">
            <div class="table" v-if="querForm.statusActiveIndex == 0">
                <div class="title">可用优惠券</div>
                <el-table ref="tableRef1" :data="list.canUseCoupons" border stripe v-loading="tableData.loading"
                    row-key="id">
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="抵扣" prop="discountAmount"></el-table-column>
                    <el-table-column label="限制" prop="fullAmount">
                        <template v-slot="scope">
                            满{{ scope.row.fullAmount }}减{{ scope.row.discountAmount }}
                        </template>
                    </el-table-column>
                    <el-table-column label="描述" prop="useRestrictions">
                        <template v-slot="scope">
                            <div v-html="scope.row.useRestrictions"></div>
                        </template>
                    </el-table-column>
                    <el-table-column label="选择" width="100" align="center">
                        <template #default="scope">
                            <el-checkbox v-model="scope.row.selected" :true-value="1" :false-value="0"
                                :disabled="scope.row.disabled" @change="selectCoupon($event, scope.row)"></el-checkbox>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="title">不可用优惠券</div>
                <el-table ref="tableRef2" :data="list.noCanUseCoupons" border v-loading="tableData.loading">
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="不可用原因">
                        <template v-slot="scope">
                            {{ scope.row.canuseResult.reason }}
                        </template>
                    </el-table-column>
                    <el-table-column label="描述" prop="useRestrictions">
                        <template v-slot="scope">
                            <div v-html="scope.row.useRestrictions"></div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="table" v-if="querForm.statusActiveIndex == 1">
                <div class="title">可用优惠券</div>
                <el-table ref="tableRef1" :data="list.canUseDiscountCoupon" border stripe v-loading="tableData.loading">
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="抵扣" prop="discountAmount"></el-table-column>
                    <el-table-column label="限制" prop="fullAmount">
                        <template v-slot="scope">
                            满{{ scope.row.fullAmount }}减{{ scope.row.discountAmount }}
                        </template>
                    </el-table-column>
                    <el-table-column label="描述" prop="useRestrictions">
                        <template v-slot="scope">
                            <div v-html="scope.row.useRestrictions"></div>
                        </template>
                    </el-table-column>
                    <el-table-column label="选择" width="100" align="center">
                        <template #default="scope">
                            <el-checkbox v-model="scope.row.selected" :true-value="1" :false-value="0"
                                :disabled="scope.row.disabled" @change="selectCoupon($event, scope.row)"></el-checkbox>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="title">不可用优惠券</div>
                <el-table ref="tableRef2" :data="list.noUseDiscountCoupon" border v-loading="tableData.loading">
                    <el-table-column label="名称" prop="name"></el-table-column>
                    <el-table-column label="不可用原因">
                        <template v-slot="scope">
                            {{ scope.row.canuseResult.reason }}
                        </template>
                    </el-table-column>
                    <el-table-column label="描述" prop="useRestrictions">
                        <template v-slot="scope">
                            <div v-html="scope.row.useRestrictions"></div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="dialog_footer">
            <el-button @click="showDialog = false">取消</el-button>
            <el-button type="primary" @click="selectCouponConfirm">确认</el-button>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useGoods } from '@/store/goods.js'
import { findCoupon } from '@/api/account.js'
import { ElMessage } from 'element-plus'
import { useUser } from "@/store/user.js";
import { couponUtils } from "ysk-utils";

const props = defineProps({
    orderList: {
        type: Array,
        default: []
    }
})

const emits = defineEmits(['success'])

const store = useUser()
const goodsStore = useGoods()
const tableRef1 = ref(null)
const tableRef2 = ref(null)
const showDialog = ref(false)
const query = ref({
    type: 1,
    userId: ''
})
const tableData = reactive({
    loading: false,
    list: []
})

// 关闭初始化
function resetHandle() {
    query.value.type = 1
    tableData.loading = false
    tableData.list = []
}

function typeChange() {
    tableData.loading = false
    // tableData.list = []
    list.canUseCoupons = []
    list.noCanUseCoupons = []
    list.canUseDiscountCoupon = []
    list.noUseDiscountCoupon = []
    findCouponAjax()
    // if (query.type == 2) {
    //     tableRef2.value.clearSelection()
    // }
}

function groupByPropertyAndCount(arr, property) {
    // 创建一个空对象来存储每个属性值对应的数量
    const propertyMap = {};

    // 遍历原始数组
    arr.forEach(item => {
        const key = item[property];
        const num = item.number || 1;
        if (!propertyMap[key]) {
            // 如果该属性值还没有在 propertyMap 中，初始化一个对象
            propertyMap[key] = {
                value: item[property],
                count: num
            };
        } else {
            // 如果该属性值已经存在，增加数量
            propertyMap[key].count += num;
        }
    });

    // 将 propertyMap 中的结果转换为数组
    return Object.values(propertyMap);
}

// 选择优惠券
const goodsCoupon = ref([]) // 商品券
const discountCoupon = ref([]) // 其他优惠券
function selectCoupon($event, e) {
    console.log($event);
    console.log(e);
    if (querForm.value.statusActiveIndex == 0) {
        goodsCoupon.value = []
        if ($event) {
            goodsCoupon.value.push(e)
            list.canUseCoupons.map(item => {
                if (item.id != e.id) {
                    item.disabled = true
                }
            })
        } else {
            list.canUseCoupons.map(item => {
                if (item.id != e.id) {
                    item.disabled = false
                }
            })
        }
    } else {
        discountCoupon.value = []
        if ($event) {
            discountCoupon.value.push(e)
            list.canUseDiscountCoupon.map(item => {
                if (item.id != e.id) {
                    item.disabled = true
                }
            })
        } else {
            list.canUseDiscountCoupon.map(item => {
                if (item.id != e.id) {
                    item.disabled = false
                }
            })
        }
    }
    updateSelCoupon()
    console.log('goodsStore.cartInfo===', goodsStore.cartInfo);
}

let orderPrice = ref(goodsStore.cartInfo.costSummary.goodsRealAmount);
function updateSelCoupon() {
    const newval = [...goodsCoupon.value, ...discountCoupon.value];

    const user = goodsStore.vipUserInfo;
    let shopInfo = store.shopInfo;

    if (!shopInfo.isMemberPrice) {
        shopInfo = {};
    }

    console.log('updateSelCoupon.user', user);
    console.log('updateSelCoupon.shopInfo', shopInfo);

    const canDikouGoodsArr = couponUtils.returnCanDikouGoods(goodsStore.cartInfo.allGoods, [], user);

    if (newval.length >= 2) {
        let goodsCoupon = newval.filter((v) => v.type == 2);
        let otherCoupon = newval.filter((v) => v.type != 2);
        goodsCoupon = goodsCoupon.map((v) => {
            const discount = couponUtils.returnCouponDiscount(
                canDikouGoodsArr,
                v,
                user,
                orderPrice.value,
                [],
                shopInfo,
                goodsStore.limitDiscountRes
            );
            return {
                ...v,
                discount,
                discountAmount: discount ? discount.discountPrice : v.discountAmount,
            };
        });
        otherCoupon = otherCoupon.map((v) => {
            const canuseResult = couponUtils.returnCouponCanUse({
                canDikouGoodsArr,
                coupon: v,
                orderPrice: orderPrice.value,
                user: user,
                selCoupon: goodsCoupon,
                shopInfo: shopInfo,
                limitTimeDiscount: goodsStore.limitDiscountRes
            });

            const discount = couponUtils.returnCouponDiscount(
                canDikouGoodsArr,
                v,
                user,
                orderPrice.value,
                goodsCoupon,
                shopInfo,
                goodsStore.limitDiscountRes
            );
            return {
                ...v,
                canuseResult,
                discount,
                discountAmount: discount ? discount.discountPrice : v.discountAmount,
            };
        });
        if (!otherCoupon[0].canuseResult.canUse) {
            ElMessage.warning('已为您自动剔除叠加不可用的优惠券')
            discountCoupon.value = [];
            goodsCoupon.value = goodsCoupon;
            return;
        }
        goodsCoupon.value = goodsCoupon;
        discountCoupon.value = otherCoupon;
    }
}

// 确认选择优惠券，然后关闭弹窗
function selectCouponConfirm() {
    updateSelCoupon();

    let ngoodsCoupon = goodsCoupon.value.filter(item => item.discountAmount > 0)
    let ndiscountCoupon = discountCoupon.value.filter(item => item.discountAmount > 0)

    if (ngoodsCoupon.length != goodsCoupon.value.length || ndiscountCoupon.length != discountCoupon.value.length) {
        ElMessage.warning('已为您自动剔除叠加不可用的优惠券')
    }

    console.log('ngoodsCoupon', ngoodsCoupon);
    console.log('ndiscountCoupon', ndiscountCoupon);

    const data = [...ngoodsCoupon, ...ndiscountCoupon]

    console.log(data);

    // return
    emits('success', data)
    goodsCoupon.value = []
    discountCoupon.value = []

    showDialog.value = false
}

const querForm = ref({
    searchValue: '',
    shopId: '',
    shopName: '',
    statusActiveIndex: 0
});

const list = reactive({
    page: 1,
    size: 10,
    status: 'nomore',
    data: [],
    noCanUseCoupons: [],
    canUseCoupons: [],
    noUseDiscountCoupon: [],
    canUseDiscountCoupon: []
});

const couponSel = ref({
    id: ''
});
const goodsCouponSel = ref({
    id: ''
});
const quansSelArr = computed(() => {
    return [couponSel.value, goodsCouponSel.value].filter((v) => v.id);
});

// 格式化优惠券
function formatCoupon() {
    let canUseGoodsCoupon = [];
    let canUseDiscountCoupon = [];

    let noUseGoodsCoupon = [];
    let noUseDiscountCoupon = [];
    const user = goodsStore.vipUserInfo;
    let shopInfo = store.shopInfo;
    if (!shopInfo.isMemberPrice) {
        shopInfo = {};
    }
    const goodsOrderPrice = goodsStore.cartInfo.costSummary.goodsRealAmount;

    console.log('goodsOrderPrice==========', goodsOrderPrice);


    const canDikouGoodsArr = couponUtils.returnCanDikouGoods(goodsStore.cartInfo.allGoods, user, shopInfo);
    for (let i = 0; i < couponList.value.length; i++) {
        const coupon = couponList.value[i];
        const canuseResult = couponUtils.returnCouponCanUse({
            canDikouGoodsArr,
            coupon,
            goodsOrderPrice,
            user,
            selCoupon: quansSelArr.value,
            shopInfo,
            limitTimeDiscount: goodsStore.limitDiscountRes
        });
        const { canUse, reason } = canuseResult;
        if (coupon.type == 2) {
            if (canUse || goodsCouponSel.value.id == coupon.id) {
                canUseGoodsCoupon.push(coupon);
            } else {
                noUseGoodsCoupon.push({
                    ...coupon,
                    canuseResult
                });
            }
        } else {
            if (canUse || couponSel.value.id == coupon.id) {
                canUseDiscountCoupon.push(coupon);
            } else {
                noUseDiscountCoupon.push({
                    ...coupon,
                    canuseResult
                });
            }
        }
    }
    //商品券
    canUseGoodsCoupon = canUseGoodsCoupon.map((v) => {
        const discount = couponUtils.returnCouponDiscount(canDikouGoodsArr, v, user, goodsOrderPrice, quansSelArr.value, shopInfo, goodsStore.limitDiscountRes);
        return {
            ...v,
            discount,
            discountAmount: discount ? discount.discountPrice : v.discountAmount
        };
    });
    //非商品券
    canUseDiscountCoupon = canUseDiscountCoupon.map((v) => {
        const discount = couponUtils.returnCouponDiscount(canDikouGoodsArr, v, user, goodsOrderPrice, quansSelArr.value, shopInfo, goodsStore.limitDiscountRes);
        return {
            ...v,
            discount,
            discountAmount: discount ? discount.discountPrice : v.discountAmount
        };
    });

    if (querForm.value.statusActiveIndex == 0) {
        list.noCanUseCoupons = noUseGoodsCoupon;

        canUseGoodsCoupon.map(item => {
            item.selected = false
            item.disabled = false
        })

        list.canUseCoupons = canUseGoodsCoupon;
    } else {
        list.noUseDiscountCoupon = noUseDiscountCoupon;

        canUseDiscountCoupon.map(item => {
            item.selected = false
            item.disabled = false
        })

        list.canUseDiscountCoupon = canUseDiscountCoupon;
    }

    console.log('canUseGoodsCoupon', canUseGoodsCoupon);
    console.log('noUseGoodsCoupon', noUseGoodsCoupon);
    console.log('canUseDiscountCoupon', canUseDiscountCoupon);
    console.log('noUseDiscountCoupon', noUseDiscountCoupon);

    console.log('list===', list);
}

// 获取用户可用的优惠券
const couponList = ref([])
async function findCouponAjax() {
    try {
        tableData.loading = true
        const res = await findCoupon({
            shopUserId: query.value.userId
        })
        couponList.value = res
        formatCoupon()
        // if (query.value.type == 1) {
        //     tableData.list = res
        // } else {
        //     let arr = []
        //     let ids = props.orderList.map(item => item.product_id)
        //     res && res.map((item, index) => {

        //         let found = ids.find(val => val == item.proId)
        //         let result = found !== undefined

        //         if (result) {
        //             let pro = props.orderList.find(val => val.product_id == item.proId)

        //             console.log('pro===', pro);

        //             let discount = pro.lowPrice

        //             if (goodsStore.showVipPrice) {
        //                 discount = pro.memberPrice
        //             }

        //             if (+pro.discount_sale_amount) {
        //                 discount = pro.discount_sale_amount
        //             }

        //             arr.push({
        //                 ...item,
        //                 productName: pro.productName,
        //                 lowPrice: pro.lowPrice,
        //                 discount: discount
        //             })
        //         }
        //     })
        //     tableData.list = arr

        //     console.log('tableData.list===', tableData.list);
        // }
    } catch (error) {
        console.log(error);
    }
    tableData.loading = false
}

async function show(userId) {
    showDialog.value = true
    query.value.userId = userId
    await findCouponAjax()
    console.log('couponModal.orderList===', props.orderList);
    // updateSelCoupon()
    // formatCoupon()
}

defineExpose({
    show
})
</script>

<style scoped lang="scss">
.dialog_footer {
    display: flex;
    justify-content: flex-end;
    padding-top: var(--el-font-size-base);
}

.title {
    padding: 20px 0 10px 0;
    font-size: 16px;
    color: #333;
}
</style>