<!--
 * @Descripttion: 分销记录
 * @version: 1.0
 * @Author: zzx
 * @Date: 2024-11-09 16:08:16
 * @LastEditors: zzx
 * @LastEditTime: 2024-11-19 16:08:16
-->
<template>
    <div class="app-container">
        <el-card class="filter-container" shadow="hover">
            <div>
                <i class="el-icon-search"></i>
                <span>筛选搜索</span>
                <el-button style="float: right" type="primary" @click="handleSearchList()" size="small">
                    查询搜索
                </el-button>
                <el-button style="float: right; margin-right: 15px" @click="handleResetSearch()" size="small">
                    重置
                </el-button>
            </div>
            <div style="margin-top: 15px">
                <el-form :inline="true" :model="listQuery" size="mini" label-width="140px">
                    <el-form-item label="姓名：">
                        <el-input v-model="listQuery.userName" class="input-width" placeholder="请输入用户名称"
                            clearable></el-input>
                    </el-form-item>
                    <el-form-item label="手机号：">
                        <el-input v-model="listQuery.phone" class="input-width" placeholder="请输入手机号码"
                            clearable></el-input>
                    </el-form-item>
                    <el-form-item label="结算状态：">
                        <el-select v-model="listQuery.status" clearable placeholder="请选择">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="充电订单编号：">
                        <el-input v-model="listQuery.chargeOrderNo" class="input-width" placeholder="请输入订单编号"
                            clearable></el-input>
                    </el-form-item>
                    <el-form-item label="完成时间：">
                        <el-date-picker v-model="completeDate" size="mini" value-format="yyyy-MM-dd HH:mm:ss"
                            class="item-width-350 ml10" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="提现时间：">
                        <el-date-picker v-model="withdrawDate" size="mini" value-format="yyyy-MM-dd HH:mm:ss"
                            class="item-width-350 ml10" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结算时间：">
                        <el-date-picker v-model="colseDate" size="mini" value-format="yyyy-MM-dd HH:mm:ss"
                            class="item-width-350 ml10" type="datetimerange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <el-card class="operate-container" shadow="hover">
            <div class="title">
                <div class="titleContent">
                    <i class="el-icon-tickets"></i>
                    <span>数据列表</span>
                </div>
                <div>
                    <el-button class="ml10" type="info" size="small" :disabled="exportDisabled" :loading="downloadLoading" icon="el-icon-printer"
                        @click="exportAllExcel">导出</el-button>
                    <el-button class="ml10" v-if="isAdmin==0" type="warning" :disabled="disabled" size="small" :loading="updateLoading" icon="el-icon-success"
                        @click="financeStatus">财务已结算</el-button>
                </div>
            </div>
        </el-card>
        <div class="table-container">
            <el-table ref="adminTable" :data="list" style="width: 100%" v-loading="listLoading" border>
                <el-table-column label="充电订单编号" width="100" align="center" prop="chargeOrderNo"></el-table-column>
                <el-table-column label="订单金额/元" align="center" prop="realCost"></el-table-column>
                <!-- <el-table-column label="服务费金额/元" align="center" prop="realServiceCost"></el-table-column> -->
                <el-table-column label="订单完成时间" align="center" prop="endTime"></el-table-column>
                <el-table-column label="一级分销员" align="center" prop="firstLevelUserName"></el-table-column>
                <el-table-column label="一级分销员手机号" align="center" prop="firstLevelPhone"></el-table-column>
                <el-table-column label="一级分销员佣金" align="center" prop="firstLevelCommission"></el-table-column>
                <el-table-column label="二级分销员" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.secondLevelUserName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="二级分销员手机号" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.secondLevelPhone || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="二级分销员佣金" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.secondLevelCommission || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="结算状态" align="center" prop="updateBy">
                    <template slot-scope="scope">
                        <el-tag type="info" v-if="scope.row.status == 0">未提现</el-tag>
                        <el-tag type="wanning" v-if="scope.row.status == 1">待结算</el-tag>
                        <el-tag type="success" v-if="scope.row.status == 2">已结算</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="提现时间" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.withdrawTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="结算时间" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.settleTime || '--' }}
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper" :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize" :page-sizes="[10, 15, 20]" :total="total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import { recordsList, updateStatus } from "@/api/distribution";
import { formatDate } from "@/utils/date";
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    phone: null,
    // 完成区间
    orderStartTime: "",
    orderEndTime: "",
    // 结算区间
    settleStartTime: "",
    settleEndTime: "",
    // 提现区间
    withdrawStartTime: "",
    withdrawEndTime: "",
    status: "",
    chargeOrderNo: "",
    adminUserId: null,
    recordId: null
};
export default {
    name: "records",
    data() {
        return {
            disabled: false,
            exportDisabled: false,
            isAdmin: null,
            completeDate: "",
            withdrawDate: "",
            colseDate: "",
            downloadLoading: false,
            updateLoading: false,
            listQuery: Object.assign({}, defaultListQuery),
            list:[],
            financeList: [],
            total: null,
            listLoading: false,
            forbiddenDialogVisible: false,
            options: [{
                value: 0,
                label: "未提现",
            },{
                value: 1,
                label: "待结算",
            },
            {
                value: 2,
                label: "已结算",
            },
            ],
        };
    },
    watch: {
        completeDate(val) {
            if (val) {
                this.listQuery.orderStartTime = Date.parse(val[0]);
                this.listQuery.orderEndTime = Date.parse(val[1]);
            } else {
                this.listQuery.orderStartTime = "";
                this.listQuery.orderEndTime = "";
            }
        },
        withdrawDate(val) {
            if (val) {
                this.listQuery.withdrawStartTime = Date.parse(val[0]);
                this.listQuery.withdrawEndTime = Date.parse(val[1]);
            } else {
                this.listQuery.withdrawStartTime = "";
                this.listQuery.withdrawEndTime = "";
            }
        },
        colseDate(val) {
            if (val) {
                this.listQuery.settleStartTime = Date.parse(val[0]);
                this.listQuery.settleEndTime = Date.parse(val[1]);
            } else {
                this.listQuery.settleStartTime = "";
                this.listQuery.settleEndTime = "";
            }
        },
    },
    created() {
        this.isAdmin = localStorage.getItem("isAdmin");
        this.getList();
        if (this.$route) {
            this.listQuery.adminUserId = this.$route.query.adminUserId
            this.listQuery.recordId = this.$route.query.recordId
        }
    },
    filters: {
        formatDateTime(time) {
            if (time == null || time === "") {
                return "N/A";
            }
            let date = new Date(time);
            return formatDate(date, "yyyy-MM-dd hh:mm:ss");
        },
    },
    methods: {
        // 更新结算状态
        financeStatus() {
            let query = JSON.parse(JSON.stringify(this.listQuery))
            query.pageSize = this.total
            query.page = 0
            query.status = 1
            recordsList(query).then((response) => {
                this.financeList.push(...response.data.list);
                // settleRecordId去重
                let updateList = Object.values(this.financeList.reduce((acc, r) => {
                    acc[r.settleRecordId] = r
                    return acc
                }, {}))
                this.financeList = updateList.map(item => item.settleRecordId)
                if(this.financeList.length <= 0) return this.$message.error('暂无待结算数据')
                this.updateLoading = true
                updateStatus(this.financeList).then((res) => {
                    this.updateLoading = false
                    if (res.code === 200) {
                        this.$message({
                            message: "更新成功",
                            type: "success",
                        });
                        this.getList();
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error",
                        })
                    }
                })
            });
        },

        // 导出
        exportAllExcel() {
            this.downloadLoading = true
            const allData = [];
            let query = JSON.parse(JSON.stringify(this.listQuery))
            query.pageSize = this.total
            recordsList(query).then(res => {
                this.downloadLoading = false
                if (res.code == 200) {
                    allData.push(...res.data.list);
                    this.exportExcel(allData);
                }
            });
        },

        // 导出数据处理
        exportExcel(r) {
            const data = r.map((item) => {
                let status = "";
                if(item.status==0){
                    status='未提现'
                }else if(item.status==1){
                    status='待结算'
                }else if(item.status==2){
                    status='已结算'
                }
                return {
                    "充电订单编号": item.chargeOrderNo,
                    "订单金额/元": item.realCost,
                    // "服务费金额/元": item.realServiceCost,
                    "订单完成时间": item.endTime,
                    "一级分销员": item.firstLevelUserName,
                    "一级分销员手机号": item.firstLevelPhone,
                    "一级分销员佣金": item.firstLevelCommission,
                    "二级分销员": item.secondLevelUserName || '--',
                    "二级分销员手机号": item.secondLevelPhone || '--',
                    "二级分销员佣金": item.secondLevelCommission || '--',
                    "结算状态":status,
                    "提现时间": item.withdrawTime || '--',
                    "结算时间": item.settleTime || '--',
                }
            })
            const worksheet = XLSX.utils.json_to_sheet(data);
            const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
            const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
            const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
            FileSaver.saveAs(blob, '分销记录表.xlsx');
        },

        handleResetSearch() {
            this.completeDate=''
            this.withdrawDate=''
            this.colseDate=''
            this.listQuery = Object.assign({}, defaultListQuery);
        },
        handleSearchList() {
            this.listQuery.pageNum = 1;
            this.getList();
        },
        handleSizeChange(val) {
            this.listQuery.pageNum = 1;
            this.listQuery.pageSize = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.listQuery.pageNum = val;
            this.getList();
        },
        getList() {
            this.listLoading = true;
            recordsList(this.listQuery).then((response) => {
                this.listLoading = false;
                this.list = response.data.list;
                this.total = response.data.total;
                if (this.list.length <= 0) {
                    this.disabled=true
                    this.exportDisabled = true;
                }else{
                    this.disabled=false
                    this.exportDisabled = false;
                }
            });
        },
    },
};
</script>
<style scoped lang="scss">
.title {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>
