<template>
    <div class="wp">
        <el-tabs type="border-card" @tab-click="handleClick">
            <el-tab-pane label="分润订单">
                <div class="querySift">
                    <el-form :model="queryParams" size="small" :inline="true" label-width="110px"
                        @submit.native.prevent>
                        <el-form-item label="日期范围" style="width: 380px;margin-bottom: 0px;">
                            <el-date-picker v-model="queryParams.createTimeRange" style="width: 240px"
                                value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']"
                                type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                                :clearable="true" />
                        </el-form-item>
                        <el-form-item label="选择站点" prop="stationName" label-width="120" style="margin-bottom: 0px;">
                            <el-select v-model="queryParams.stationId" filterable clearable placeholder="请选择站点">
                                <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName"
                                    :value="item.stationId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item style="margin-bottom: 0px;">
                            <el-button type="primary" icon="el-icon-search" size="mini"
                                @click="handleQuery">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="concentrate" style="margin-top: 20px;">
                    <h3 style="margin-top: 0px;">订单分账明细</h3>
                    <el-table :data="orderList" v-loading="loading">
                        <el-table-column property="orderCode" label="订单编号" align="center" />
                        <el-table-column property="orderAmount" label="订单消费金额（元）" align="center" />
                        <el-table-column property="settleAmount" label="订单结算金额（元）" align="center" />
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <el-popover placement="top" trigger="hover" width="1150">
                                    <!-- 嵌套表格 -->
                                    <el-table :data="scope.row.orderSplitList">
                                        <el-table-column property="merchantName" label="运营商名称" align="center"
                                            width="150" />
                                        <el-table-column property="adapayMemberId" label="汇付会员id" align="center"
                                            width="150" />
                                        <el-table-column property="electricitySplitRatio" label="电费分账比例(%)"
                                            align="center" width="130" />
                                        <el-table-column property="electricitySplitAmount" label="电费分账金额(元)"
                                            align="center" width="140" />
                                        <el-table-column property="serviceSplitRatio" label="服务费分账比例(%)" align="center"
                                            width="140" />
                                        <el-table-column property="serviceSplitAmount" label="服务费分账金额(元)" align="center"
                                            width="140" />
                                        <el-table-column property="revenueAmount" label="总收入金额(元)" align="center"
                                            width="140" />
                                        <el-table-column property="feeAmount" label="手续费(元)" align="center"
                                            width="120" />
                                    </el-table>
                                    <span slot="reference" class="link-type"
                                        @mouseover="hoverRow = scope.$index">分润明细</span>
                                </el-popover>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination v-show="orderTotal > 0" :total="orderTotal" :page.sync="getOrderParams.pageNo"
                        :limit.sync="getOrderParams.pageSize" @pagination="getOrderList" />
                </div>
            </el-tab-pane>
            <el-tab-pane label="分润汇总">
                <div class="querySift">
                    <el-form :model="statisticsParams" size="small" :inline="true" label-width="110px"
                        @submit.native.prevent>
                        <el-form-item label="日期范围" style="width: 380px;margin-bottom: 0px;">
                            <el-date-picker v-model="statisticsParams.createTimeRange" style="width: 240px"
                                value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']"
                                type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                                :clearable="true" />
                        </el-form-item>
                        <el-form-item label="选择站点" prop="stationName" label-width="120" style="margin-bottom: 0px;">
                            <el-select v-model="statisticsParams.stationId" filterable clearable placeholder="请选择站点">
                                <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName"
                                    :value="item.stationId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item style="margin-bottom: 0px;">
                            <el-button type="primary" icon="el-icon-search" size="mini"
                                @click="handleStatistics">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetStatistics">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="concentrate">
                    <p class="prompt"
                        v-if="statisticsParams.createTimeRange && statisticsParams.createTimeRange.length >= 2">
                        创建时间 {{ statisticsParams.createTimeRange[0] }} - {{ statisticsParams.createTimeRange[1] }} 期间
                    </p>
                    <p class="prompt" v-else>时间范围：未选择</p>
                    <el-table :data="tableData" border show-summary :summary-method="getSummaries">
                        <el-table-column prop="stationName" label="站点名称" align="center" />
                        <el-table-column prop="orderCount" label="订单数量" align="center" />
                        <el-table-column prop="totalElectricitySplitAmount" label="总电费分账金额（元）" align="center" />
                        <el-table-column prop="totalServiceSplitAmount" label="总服务费分账金额（元）" align="center" />
                        <el-table-column prop="totalFeeAmount" label="总手续费（元）" align="center" />
                        <el-table-column prop="totalRevenueAmount" label="总收入金额（元）" align="center" />
                    </el-table>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import { queryStationList, queryOrderSplitData, queryStationAggregateData } from "@/api/pile/merchant";
export default {
    data() {
        return {
            queryParams: {
                stationId: null,
                createTimeRange: this.getDefaultDateRange(),
            },
            statisticsParams: {
                stationId: null,
                createTimeRange: this.getDefaultDateRange(),
            },
            stationList: [],
            orderList: [],
            orderTotal: 0,
            getOrderParams: {
                pageNo: 1,
                pageSize: 10,
                stationId: null,
                adapayMemberId: this.$route.query.adapayMemberId,
                startTime: this.getDefaultDateRange()[0],
                endTime: this.getDefaultDateRange()[1],
            },
            loading: false,
            tableData: [],
        };
    },
    created() {
        this.getList();
    },
    methods: {
        // 获取当前日期范围
        getDefaultDateRange() {
            // 获取当前日期
            const now = new Date()

            // 当月第一天
            const start = new Date(now.getFullYear(), now.getMonth(), 1)
            start.setHours(0, 0, 0, 0)

            // 今天
            const end = new Date()
            end.setHours(23, 59, 59, 999)

            // 格式化函数
            const format = date => {
                const pad = n => n.toString().padStart(2, '0')
                return [
                    date.getFullYear(),
                    pad(date.getMonth() + 1),
                    pad(date.getDate())
                ].join('-') + ' ' + [
                    pad(date.getHours()),
                    pad(date.getMinutes()),
                    pad(date.getSeconds())
                ].join(':')
            }

            return [format(start), format(end)]
        },
        // 搜索按钮操作
        handleQuery() {
            if (!this.queryParams.createTimeRange) {
                this.$message.error("请选择日期范围");
                return;
            }
            if (!this.queryParams.stationId) {
                this.$message.error("请选择站点");
                return;
            }
            this.getOrderParams.pageNo = 1;
            this.getOrderParams.startTime = this.queryParams.createTimeRange[0];
            this.getOrderParams.endTime = this.queryParams.createTimeRange[1];
            console.log("搜索的值", this.queryParams);
            this.getOrderList();
        },
        // 重置按钮操作
        resetQuery() {
            this.getList();
            this.queryParams.createTimeRange = this.getDefaultDateRange();
            this.getOrderParams = {
                pageNo: 1,
                pageSize: 10,
                stationId: this.queryParams.stationId,
                adapayMemberId: this.$route.query.adapayMemberId,
                startTime: this.getDefaultDateRange()[0],
                endTime: this.getDefaultDateRange()[1],
            };
        },
        // 获取站点列表
        getList() {
            let params = {
                adapayMemberId: this.$route.query.adapayMemberId,
            };
            queryStationList(params).then((response) => {
                this.stationList = response.obj.stationList;
                this.queryParams.stationId = response.obj.stationList[0].stationId;
                this.getOrderList();
            });
        },
        // 获取订单列表
        getOrderList() {
            this.loading = true;
            this.getOrderParams.stationId = this.queryParams.stationId
            queryOrderSplitData(this.getOrderParams).then((response) => {
                this.orderList = response.obj.list;;
                this.orderTotal = response.obj.total;
                this.loading = false;
            });
        },
        getSummaries(param) {
            const { columns, data } = param;
            const integerFields = ['orderCount', 'quantity']; // 需要显示整数的字段

            return columns.map((col, index) => {
                if (index === 0) return '总计';

                const total = data.reduce((sum, row) => {
                    const val = Number(row[col.property]) || 0;
                    return sum + val;
                }, 0);

                return integerFields.includes(col.property)
                    ? total.toLocaleString('zh-CN', { maximumFractionDigits: 0 })
                    : total.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            });
        },
        // 获取统计数据
        getAggregateData() {
            let params = {
                adapayMemberId: this.$route.query.adapayMemberId,
                startTime: this.statisticsParams.createTimeRange[0],
                endTime: this.statisticsParams.createTimeRange[1],
                stationId: this.statisticsParams.stationId,
            };
            queryStationAggregateData(params).then((response) => {
                this.tableData = response.obj;
            });
        },
        // 搜索统计数据
        handleStatistics() {
            if (!this.statisticsParams.createTimeRange) {
                this.$message.error("请选择日期范围");
                return;
            }
            this.statisticsParams.startTime = this.statisticsParams.createTimeRange[0];
            this.statisticsParams.endTime = this.statisticsParams.createTimeRange[1];
            this.statisticsParams.stationId = this.statisticsParams.stationId;
            this.getAggregateData();
        },
        // 重置统计按钮操作
        resetStatistics() {
            this.statisticsParams.createTimeRange = this.getDefaultDateRange();
            this.statisticsParams.stationId = null;
            this.getAggregateData();
        },
        // Tab切换事件
        handleClick(tab, event) {
            if (tab.label === "分润订单") {
                this.resetQuery();
            } else if (tab.label === "分润汇总") {
                this.resetStatistics();
            }
        },
    }
};
</script>
<style lang="scss" scoped>
.wp {
    width: 100%;
    min-height: 100vh;
    background: #f9fafb;
    padding: 20px;
    box-sizing: border-box;
}

p {
    margin: 0;
}

.querySift {
    width: 98%;
    height: 100px;
    display: flex;
    align-items: center;
    border-radius: 8px;
    background: #FFFFFF;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
    margin: 20px auto;
}

.concentrate {
    width: 98%;
    border-radius: 8px;
    background: #FFFFFF;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
    margin: auto;
    padding: 24px;
    box-sizing: border-box;
}

.prompt {
    margin-bottom: 20px;
}
</style>