<route lang="json5" type="page">
    {
      style: {
        navigationStyle: 'custom',
        navigationBarTitleText: '我的订单',
        navigationBarBackgroundColor:'#FFF',
      },
    }
</route>

<template>
    <wd-tabs color="#333" inactiveColor="#888" @click="handleClick">
        <block v-for="item in tabs" :key="item.state">
            <wd-tab :title="item.tabName" :name="item.state">
                <scroll-view scroll-y class="page-wrapper" @scrolltolower="queryNext">
                    <!-- <view class="order-wrapper flex flex-col flex-items-center" v-if="Array.isArray(list[item.state]) && list[item.state].length > 0"> -->
                        <!-- <view v-for="(ele,index) in list[item.state]" :key="`${ele.id}-${item.state}`">
                            <OrderItem :detail="ele" @pay-event="pay" @detail-event="viewDetail" @pwd-event="viewPwd"/>
                        </view> -->
                    <view class="order-wrapper flex flex-col flex-items-center" v-if="Array.isArray(list) && list.length > 0">
                        <view v-for="(ele,index) in list" :key="`${ele.id}-${item.state}`">
                            <OrderItem 
                                :detail="ele" 
                                @pay-event="pay" 
                                @detail-event="viewDetail" 
                                @pwd-event="viewPwd" 
                                @del-event="removeOrder" 
                                @refund-event="refund"
                            />
                        </view>
                        <view class="no-more" v-if="isLastPage">没有更多了~</view>
                    </view>
                    <view class="no-data" v-else>
                        <image
                            src="/static/ycnc/bg-nodata.png"
                            mode="scaleToFill"
                            class="no-img"
                        />
                        <text class="no-text">暂无订单，快去下单吧~</text>
                    </view>
                </scroll-view>
            </wd-tab>
        </block>
    </wd-tabs>
    <wd-message-box />
</template>

<script setup>
    import { useMessage } from 'wot-design-uni'
    import OrderItem  from './components/order-item';
    import usePay from './hooks/usePay';
    import { getOrderList,deleteOrder,refundOrder } from '../../api/ycnc';
    import { onMounted, ref, unref,reactive,computed } from 'vue';
    import { tabs } from './config';
    import {deepClone} from '../../utils/utils'
    const message = useMessage()
    const pageSize = 10;
    const activeName = ref(0);
    const total = ref(0);
    const page = ref(1);
    const list = ref([]);
    const replace = ref(false);
    //页码
    // const enumPage = tabs.reduce((prev,cur) => {
    //     prev[cur.state] = 1
    //     return prev
    // },{})
    // const page = ref(enumPage)
    // //总数
    // const enumObj = tabs.reduce((prev,cur) => {
    //     prev[cur.state] = 0
    //     return prev
    // },{})
    // const total = reactive(enumObj);
    //数据列表
    // const enumOrder = tabs.reduce((prev,cur) => {
    //     prev[cur.state] = []
    //     return prev
    // },{})
    // const list = reactive(enumOrder)

    //获取订单列表
    const queryOrderList = () => {
        const activeTab = unref(activeName);
        const params = {
			page:unref(page),
			pageSize:pageSize,
            ...(activeTab !== 0 && {state:activeTab})
		}
		getOrderList({params}).then(res => {
			const {count,data} = res
            total.value = count
            // Object.assign(list,{[activeTab]:[...list[activeTab],...data]})
            if(replace.value){
                const prevPage = page.value - 1;
                const prevList = list.value.slice(0,  prevPage * pageSize);
                list.value = [...prevList,...data];
            }else{
                list.value = [...list.value,...data]
            }
            replace.value = false
		}).catch(err => {
            total.value = 0;
            // Object.assign(list,{[activeTab]:[]})
            list.value = []
        })
    }

    function handleClick({index, name}){
        page.value = 1;
        total.value = 0;
        // Object.assign(list,{[name]:[]})
        list.value = [];
        activeName.value = name;
        // name代表状态值
        queryOrderList()
     
    }

    function pay(orderData){
        console.log(orderData);
        const {order_no,notify_url,price,brand,sign,plain_text} = orderData;
        const {payFunc} = usePay();
        payFunc({order_no,notify_url,TranAmt:price,MerName:brand,sign,plain_text})
    }

    function viewDetail(orderData){
        const {id,order_no} = orderData;
        uni.navigateTo({
            url:`/pages/ycnc/orderDetail?order_id=${id}&order_no=${order_no}`
        })
    }

    function viewPwd(orderData){
        const {voucher_link} = orderData
        if(voucher_link){
            console.log('跳转外部链接--->',voucher_link);
            window.location.href = voucher_link
        }else{
            console.error(`${voucher_link}无有效值`);
        }
    }

    function removeOrder(orderData){
        message
        .confirm({
            msg: '删除订单后无法恢复，确认继续吗？',
            title: '提示'
        })
        .then(() => {
            const {id} = orderData
            const params = {order_id:id}
            deleteOrder({params}).then(res => {
                replace.value = true;
                queryOrderList()
            }).catch(err => {
                console.log(err);
            })
        })
        .catch(() => {
            console.log('点击了取消按钮')
        })
    }

    function refund(orderData){
        const {id} = orderData
        if(!id){
            uni.showToast({
                icon:'none',
                title: '无有效的订单id',
            });
            return
        }
        const params = {order_id:id}
        refundOrder({params}).then(res => {
            uni.showToast({
                icon:'success',
                title: '退款成功',
            });
            replace.value = true;
            queryOrderList();
        }).catch(err => {
            console.log(err);
        })
    }

    onMounted(()=>{
        queryOrderList()
    })

    const isLastPage = computed(()=>{
        return unref(page) === Math.ceil(unref(total) / pageSize)
    })

    function queryNext(){
    console.log(unref(isLastPage));
        if(unref(isLastPage)){
			console.error('已经是最后一页');
			return false;
		};
        page.value  = page.value + 1
        queryOrderList()
    }
</script>

<style lang='scss' scoped>
.page-wrapper{
    width:100%;
    // height: 100%;
    height: calc(100vh - 42rpx);
    overflow-y: auto;
    background: #FAFBFD;
    box-sizing: border-box;
    padding-bottom:30rpx
}
.order-wrapper{
    display: flex;
    flex-direction: column;
    width:100%;
}
.no-more{
    font-weight: normal;
    font-size: 18rpx;
    color: #999999;
    height:146rpx;
    padding: 28rpx 0;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    box-sizing: border-box;
}
.no-data{
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    .no-img{
        width:446rpx;
        height: 446rpx;
    }
    .no-text{
        font-weight: normal;
        font-size: 24rpx;
        color: #999999;
    }
}
/* 修改标签页下划线颜色*/
// :deep(.wd-button.is-primary){
//     background: #EA0000;
// }
:deep(.wd-tabs__line) {
    background: #EA0000;
}
:deep(.wd-tabs){
    display: flex;
    flex-direction: column;
    height:100%;
}
:deep(.wd-tab__body){
    height:calc(100vh - 42rpx);
}
:deep(.wd-tabs__container){
    flex:1;
}
</style>