<template>
    <div class="layout-pd">
        <!-- 操作 -->
        <el-row>
            <el-col :xs="24">
                <el-card class="mt8" shadow="hover">
                    <el-form :model="Data.Filter" @submit.stop.prevent>
                        <el-form-item prop="name" style="width: 100%">
                            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                                <el-form-item label="油枪">
                                    <el-input v-model="Data.Filter.nozzleNum" placeholder="请输入油枪" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                                <el-form-item label="油品">
                                    <el-input v-model="Data.Filter.oilName" placeholder="请输入集合编号" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                                <el-form-item label="支付方式">
                                    <el-select v-model="Data.selectedPayment" placeholder="请选择支付方式">
                                 <el-option v-for="payment in Data.paymentOptions" :key="payment.id" :label="payment.paymentName" :value="payment.id + ''" />
                                </el-select>
                                </el-form-item>
                            </el-col> 
                            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                                <el-form-item label="油站">
                                    <el-select v-model="Data.Filter.StationName" placeholder="全部">
                                        <el-option v-for="(value, key) in selectList.station" :key="key" :label="value" :value="value" />
                                    </el-select>
                                </el-form-item>
                            </el-col> 
                            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                                <el-form-item label="加油时间">
                                    <el-date-picker v-model="Data.time1" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" range-separator="To" start-placeholder="开始日期" end-placeholder="结束日期" clearable=false />
                                </el-form-item>
                            </el-col>   
                            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" class="mb20">
                                <el-form-item label="支付用户">
                                    <el-input v-model="Data.Filter.phoneNumberOruserName" placeholder="请输入用户名称和手机号" clearable></el-input>
                                </el-form-item>
                            </el-col> 
                        </el-form-item>
                    </el-form>
                    
                    <hr>

                    <!-- 按钮 -->
                    <el-row justify="space-between" class="submit-button">
                        <el-row>
                            <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
                            <el-button type="primary" icon="ele-RefreshRight" @click="onReset"> 重置 </el-button>
                            <el-button type="primary" icon="ele-Search" @click="downloadExcel"> 导出EXCEL </el-button>
                        </el-row>
                    </el-row>
                </el-card>
            </el-col>
            <!--表格-->
            <el-col :xs="24">
                <el-card style="height: 70vh" class="my-fill mt8" shadow="hover">
                    <el-table ref="multipleTableRef" v-loading="Data.loading" stripe :data="Data.tableModel"
                        row-key="id" style="width: 100%">
                        <el-table-column v-for="column in Data.dynamicColumns" :key="column.prop" :prop="column.prop"
                            :label="column.label" />
                        <!-- 操作
                        <el-table-column label="操作" fixed="right" align="center" header-align="center"
                            class="right-operation" width="140">
                            <template #default="scope">
                                <el-link class="my-el-link mr12 ml12" type="primary" :underline="false" target="_blank"
                                    icon="ele-Tickets" @click.stop="toView(scope.row.id)">查看</el-link>
                            </template>
                        </el-table-column> -->
                    </el-table>
                    
                    <!-- 页码 -->
                    <div class="my-flex my-flex-end" style="margin-top: 20px">
                        <el-pagination 
                            v-model:currentPage="Data.pageInput.page"
                            v-model:page-size="Data.pageInput.pageSize" 
                            :total="Data.total"
                            :default-page-size="10" 
                            :page-sizes="[10,20,50,100]" 
                            small 
                            background 
                            @size-change="onSizeChange" 
                            @current-change="onCurrentChange" 
                            :page-count="pageCount"
                            layout="total, sizes, prev, pager, next, jumper" 
                        />
                        
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts" name="partsManagement/oilGun">
import { onMounted, reactive, watch, computed } from "vue";
import { getOrderInfoPage,getOrderFilter,downloadAfterpayOrder } from "/@/api/api";
import { OrderInfoFilter } from "/@/api/admin/orderDto/QRBookDto";
import { nextTick } from 'vue';
import { formatDate } from '/@/utils/formatTime'

/**页面对象 */
const Data = reactive({
    time1: '',
    /**加载显示 */
    loading: false,
    /**条件查询模块 */
    Filter: {
        /**油枪号 */
        nozzleNum: null,
        /**油品 */
        oilName: null,
        /**支付方式 */
        onlineStatus: null,
        /**加油开始的时间 */
        startCheckTime: null,
        /**加油结束的时间 */
        endCheckTime: null,
        // 支付方式类型
        paymentType:null,
        // 用户手机号码or用户名称
        phoneNumberOruserName:null
    } as OrderInfoFilter,
    /**表格信息 */
    tableModel: [],
    /**动态表头 */
    dynamicColumns: [
        { prop: 'ttc', label: '流水号' },
        { prop: 'stationName', label: '油站' }, 
        { prop: 'machineName', label: '油机号' },
        { prop: 'nozzleAndOil', label: '油枪|油品' },
        { prop: 'priceAndVolume', label: '单价|升数' },
        { prop: 'amount', label: '金额' },
        { prop: 'paymentTime', label: '挂枪时间' },
        { prop: 'endTime', label: '交易时间' },
        { prop: 'paymentName', label: '支付方式' },
        { prop: 'fuelId', label: '支付状态' },
        { prop: 'phoneNumber', label: '支付用户' } 
    ], 
    /**分页总数 */
    total: 0,
    /**分页标识 */
    pageInput: {
        page: 1,
        pageSize: 10,
    },  
  selectedPayment:'', //储存ID
  paymentOptions:[] //储存支付方式
})

/** 选择框列表 */
const selectList = reactive({
    Online: ["在线", "离线"],
    Device: [   
        "启用",
        "备案",
        "维修",
        "出厂注册"],
    Level: [1, 2, 3, 4, 5],
    station:[
        '全部'
    ]
})  

// 计算当前页的数据
const currentPageData = computed(() => {
    console.log('Data.tableModel', Data.tableModel); // 添加调试语句，查看数据是否正确更新
    const start = (Data.pageInput.page - 1) * Data.pageInput.pageSize;
    const end = start + Data.pageInput.pageSize;
    return Data.tableModel.slice(start, end);
});

// 计算显示的页码数量
const pageCount = computed(() => {
    const totalPages = Math.ceil(Data.total / Data.pageInput.pageSize);
    return totalPages < 100? 100 : totalPages;
});

/** 查询订单 */
const onQuery = async () => {
    Data.loading = true;
    try {
        let filterParams = {
            page: Data.pageInput.page,
            pageSize: Data.pageInput.pageSize,
           ...Data.Filter
        };
        // 根据选中的支付方式设置筛选参数
        if (Data.selectedPayment && Data.selectedPayment!== '0') {
            filterParams.paymentType = parseInt(Data.selectedPayment);
        } else {
            // 如果选择“全部”，不传递paymentType参数
            filterParams.paymentType = null; 
        }
        const orders = await getOrderInfoPage(filterParams);
        console.log('后端返回的原始数据:', orders);
        console.log('后端返回的总记录数:', orders.total);
        console.log('后端返回的当前页数据列表长度:', orders.list.length);

        Data.total = orders.total;
        Data.tableModel = orders.list.map(order => {
            return {
               'stationName': order.stationName,
                'ttc': order.ttc,
                'nozzleAndOil': order.nozzleNum + "|" + order.oilName,
                'priceAndVolume': order.price + "|" + order.volume + 'L',
                'amount': order.amount,
                'paymentTime': order.paymentTime,
                'endTime': order.endTime,
                'fuelId': order.paymentStatus === 0? "未支付" : order.paymentStatus === 1? "已支付" : "未知状态",
                'phoneNumber': order.userName,
                'paymentName': order.paymentName,
                "machineName": order.machineName
            };
        });
        console.log('处理后的数据列表长度:', Data.tableModel.length);
    } catch (error) {
        console.error('查询订单数据时出错:', error);
    } finally {
        Data.loading = false;
        await nextTick();
    }
};



/** 重置查询条件 */
const onReset = () => {
    Data.Filter = {
        nozzleNum: null,
        oilName: null,
        onlineStatus: null,
        startCheckTime: null,
        endCheckTime: null,
        StationName: null,
        payUserName: null,
        paymentType: null,
        phoneNumberOruseName: null
    };
    Data.time1 = "";
    // 重置时选择“全部”
    Data.selectedPayment = '0'; 
    initTime()
};

/** 下载excel */
const downloadExcel = async () => {
    // return
    Data.loading = true;
    try {
        let filterParams = {
            page: Data.pageInput.page,
            pageSize: Data.pageInput.pageSize,
           ...Data.Filter
        };
        // 根据选中的支付方式设置筛选参数
        if (Data.selectedPayment && Data.selectedPayment!== '0') {
            filterParams.paymentType = parseInt(Data.selectedPayment);
        } else {
            // 如果选择“全部”，不传递paymentType参数
            filterParams.paymentType = null; 
        }
        const stream = await downloadAfterpayOrder(filterParams);
        const url = window.URL.createObjectURL(new Blob([stream.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
        const link = document.createElement('a');
        link.href = url;
        
        link.setAttribute('download',
        `${formatDate(filterParams.startCheckTime,"YYYY-mm-dd")}-${formatDate(filterParams.startCheckTime,"YYYY-mm-dd")}订单报表.xlsx`)
        
        document.body.appendChild(link);
        link.click();
        // 下载完成后移除链接，并释放内存
        link.remove();
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('查询订单数据时出错:', error);
    } finally {
        Data.loading = false;
        await nextTick();
    }
}

/** 页数修改 */
const onSizeChange = (pageSize) => {
    Data.pageInput.pageSize = pageSize;
    Data.pageInput.page = 1; 
    onQuery();
}

/** 页码修改 */
const onCurrentChange = (page) => {
    Data.pageInput.page = page;
    onQuery();
}

/** 操作 */
const toView = ((data: any) => {
    console.log('查看')
})

const initTime = () => {
    const now = new Date();
    const todayStart = new Date(now.getFullYear(),now.getMonth(),now.getDate());
    var todayEnd = new Date(now.getFullYear(),now.getMonth(),now.getDate());
    todayEnd.setHours(23,59,59,999);
    Data.time1 = [formatDate(todayStart,"YYYY-mm-dd HH:MM:SS"),formatDate(todayEnd,"YYYY-mm-dd HH:MM:SS")]

    Data.Filter.startCheckTime = todayStart;
    Data.Filter.endCheckTime = todayEnd;
}
// 挂载时
onMounted(async () => {
    initTime();
    const response = await getOrderFilter();
    console.log("支付方式请求结果", response);
    // 确保response.payments是一个数组
    if (Array.isArray(response.payments)) {
        const allOption = { id: 0, paymentName: '全部' };
        Data.paymentOptions = [allOption, ...response.payments];
    } else {
        console.error("支付方式数据格式错误,response.payments不是一个数组");
        Data.paymentOptions = [allOption];
    }
    console.log('支付方式筛选:', Data.paymentOptions);
    // 初始化选择“全部”
    Data.selectedPayment = '0'; 
    await onQuery();
});

/** 过滤条件监听——枪号 */
watch(() => Data.Filter.nozzleNum,(val) => {
    if(val) {
        Data.Filter.nozzleNum = val
    } else {
        Data.Filter.nozzleNum = null
    }
})

/** 过滤条件监听——油品 */
watch(() => Data.Filter.oilName,(val) => {
    if(val) {
        Data.Filter.oilName = val
    } else {
        Data.Filter.oilName = null
    }
})

/** 过滤条件监听——时间 */
watch(() => Data.time1,(val) => {
    debugger
    if(val == null || val?.length === 0) {
        initTime()
        return
    }
    Data.Filter.startCheckTime = new Date(val?.[0].toString());
    Data.Filter.endCheckTime = new Date(val?.[1].toString());
})

/** 过滤条件监听——支付方式 */
watch(() => Data.Filter.onlineStatus,(val) => {
    if(val) {
        Data.Filter.onlineStatus = val
    } else {
        Data.Filter.onlineStatus = null
    }
})

/** 过滤条件监听——支付方式类型 */
watch(() => Data.Filter.paymentType,(val) => {
    if(val) {
        Data.Filter.paymentType = val
    } else {
        Data.Filter.paymentType = null
    }
})

/** 过滤条件监听——用户手机号码or用户名称 */
watch(() => Data.Filter.phoneNumberOruseName,(val) => {
    if(val) {
        Data.Filter.phoneNumberOruseName = val
    } else {
        Data.Filter.phoneNumberOruseName = null
    }
})
</script>

<style scoped lang="scss">
.el-input,
.el-select {
    width: 240px;
}

/* 输入框标签固定四个字符宽度 */
::v-deep .el-form-item__label {
    // 字体大小14，4个字符，12px右间距
    width: 14*4px+12px;
    justify-content: start;
}

/* 数据表头 设置灰色样式 */
::v-deep .el-table th.el-table__cell {
    background-color: #F6F6F6;
}

.mb21{
    margin-left: 68px;
}

.mb22{
    width: 2000px;
}
</style>