<template>
    <div class="app-container" id="lostReportList">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
            <el-form-item prop="unitIds">
                <treeselect
                    v-model="queryParams.unitId"
                    :options="unitList" :normalizer="normalizer"
                    :show-count="true" style="width: 240px" :disable-branch-nodes="true"
                    noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果"
                    placeholder="请选择结算单位" @select="unitChange"
                />
            </el-form-item>
            <el-form-item prop="projectIds">
                <treeselect
                    v-model="queryParams.projectId"
                    :options="proList" :normalizer="normalizer"
                    :show-count="true" style="width: 240px" :disable-branch-nodes="true"
                    noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果"
                    placeholder="请选择结算工程" @select="proChange"
                />
            </el-form-item>
            <el-form-item prop="agreementCode">
                <el-input v-model="queryParams.agreementCode" placeholder="请输入协议号" clearable/>
            </el-form-item>
            <el-form-item prop="dateRange">
                <el-date-picker
                    v-model="queryParams.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 240px"
                    @change="handleDateRangeChange">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <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-button type="success" icon="el-icon-download" size="mini" @click="exportExcel" :disabled="tableList.length === 0">导出Excel</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="tableList" border stripe>
            <el-table-column label="序号" align="center" type="index" width="60">
                <template slot-scope="scope">
                    <span>{{
                        (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column label="协议号" align="center" prop="agreementCode" :show-overflow-tooltip="true"/>
            <el-table-column label="结算单位" align="center" prop="unitName" />
            <el-table-column label="结算工程" align="center" prop="projectName" />
            <el-table-column label="机具名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
            <el-table-column label="规格型号" align="center" prop="modelName" :show-overflow-tooltip="true" />
            <el-table-column label="单位" align="center" prop="mtUnitName" width="80" />
            <el-table-column label="丢失数量" align="center" prop="num" width="100" />
            <el-table-column label="单价（元）" align="center" prop="buyPrice" width="120">
                <template slot-scope="scope">
                    {{ scope.row.buyPrice ? scope.row.buyPrice.toFixed(2) : '0.00' }}
                </template>
            </el-table-column>
            <el-table-column label="丢失费用（元）" align="center" prop="cost" width="120">
                <template slot-scope="scope">
                    {{ (scope.row.buyPrice * scope.row.num).toFixed(3) }}
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
    </div>
</template>

<script>
import {
  getProjectList,
  getUnitList,
  getAgreementInfoById,
  getUnitListFilterTeam,
} from '@/api/back/index.js'
import { getLostReportList } from '@/api/cost/cost'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as XLSX from 'xlsx';

export default {
    name: 'LostReportHome',
    components: { Treeselect },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 单位数据
            unitList: [],
            // 工程数据
            proList: [],
            // 表格数据
            tableList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                unitId: null,
                projectId: null,
                agreementCode: null,
                dateRange: null,
                startTime: null,
                endTime: null,
            },
        }
    },
    created() {
        this.initDefaultDateRange()
        this.GetUnitData()
        this.GetProData()
        this.getList()
    },
    methods: {
        // 初始化默认日期范围（当月第一天到最后一天）
        initDefaultDateRange() {
            const now = new Date()
            const year = now.getFullYear()
            const month = now.getMonth()

            // 当月第一天
            const firstDay = new Date(year, month, 1)
            const firstDayStr = this.formatDate(firstDay)

            // 当月最后一天
            const lastDay = new Date(year, month + 1, 0)
            const lastDayStr = this.formatDate(lastDay)

            this.queryParams.dateRange = [firstDayStr, lastDayStr]
            this.queryParams.startTime = firstDayStr
            this.queryParams.endTime = lastDayStr
        },

        // 格式化日期为 yyyy-MM-dd 格式
        formatDate(date) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}-${month}-${day}`
        },

        // 处理日期范围变化
        handleDateRangeChange(dateRange) {
            if (dateRange && dateRange.length === 2) {
                this.queryParams.startTime = dateRange[0]
                this.queryParams.endTime = dateRange[1]
            } else {
                this.queryParams.startTime = null
                this.queryParams.endTime = null
            }
        },

        /** 转换菜单数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children,
            };
        },

        // 获取 来往单位 列表数据
        async GetUnitData() {
            const params = {}
            const res = await getUnitListFilterTeam(params)
            this.unitList = res.data;
            this.getAgreementInfo()
        },

        unitChange(val){
            setTimeout(()=>{
                this.queryParams.projectId=null
                this.queryParams.agreementCode = null
                this.GetProData()
            },500)
        },

        // 获取 工程名称 列表数据
        async GetProData() {
            const params = {
                unitId: this.queryParams.unitId,
            }
            const res = await getProjectList(params)
            this.proList = res.data;
            this.getAgreementInfo()
        },

        proChange(val){
            setTimeout(()=>{
                this.GetUnitData()
            },500)
        },

        // 获取 协议id
        async getAgreementInfo() {
            if (this.queryParams.unitId && this.queryParams.projectId) {
                const params = {
                    unitId: this.queryParams.unitId,
                    projectId: this.queryParams.projectId,
                }
                const res = await getAgreementInfoById(params)
                if (!(res.data && res.data.agreementId)) {
                    this.$message.error('当前单位和工程无协议！')
                    this.queryParams.unitId = null
                    this.queryParams.projectId = null
                    this.GetUnitData()
                    this.GetProData()
                } else {
                    this.queryParams.agreementCode = res.data.agreementCode
                }
            }
        },

        /** 查询列表 */
        getList() {
            this.loading = true
            getLostReportList(this.queryParams).then((response) => {
                this.tableList = response.rows || []
                this.total = response.total
                this.loading = false
            }).catch((error) => {
                console.error('获取丢失费用报表失败:', error)
                this.tableList = []
                this.total = 0
                this.loading = false
            })
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                unitId: null,
                projectId: null,
                agreementCode: null,
                dateRange: null,
                startTime: null,
                endTime: null,
            }
            // 重新初始化默认日期范围
            this.initDefaultDateRange()
            this.resetForm('queryForm')
            this.handleQuery()
        },

        // 导出Excel
        exportExcel() {
            if (!this.tableList || this.tableList.length === 0) {
                this.$modal.msgWarning('没有可导出的数据');
                return;
            }

            try {
                // 定义Excel列配置
                const columns = [
                    { key: 'index', title: '序号' },
                    { key: 'agreementCode', title: '协议号' },
                    { key: 'unitName', title: '结算单位' },
                    { key: 'projectName', title: '结算工程' },
                    { key: 'typeName', title: '机具名称' },
                    { key: 'modelName', title: '规格型号' },
                    { key: 'mtUnitName', title: '单位' },
                    { key: 'num', title: '丢失数量' },
                    { key: 'buyPrice', title: '单价（元）' },
                    { key: 'cost', title: '丢失费用（元）' }
                ];

                // 准备Excel数据
                const excelData = [];

                // 添加表头
                const headerRow = columns.map(col => col.title);
                excelData.push(headerRow);

                // 添加数据行
                this.tableList.forEach((row, index) => {
                    const dataRow = columns.map(col => {
                        if (col.key === 'index') {
                            return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
                        } else if (col.key === 'buyPrice') {
                            // 处理单价字段格式
                            return row.buyPrice ? parseFloat(row.buyPrice.toFixed(2)) : 0.00;
                        } else if (col.key === 'cost') {
                            // 处理丢失费用字段格式，计算buyPrice * num
                            const cost = (row.buyPrice || 0) * (row.num || 0);
                            return parseFloat(cost.toFixed(3));
                        } else {
                            return row[col.key] || '';
                        }
                    });
                    excelData.push(dataRow);
                });

                // 创建工作簿和工作表
                const workbook = XLSX.utils.book_new();
                const worksheet = XLSX.utils.aoa_to_sheet(excelData);

                // 设置列宽
                const columnWidths = [
                    { wch: 8 },   // 序号
                    { wch: 20 },  // 协议号
                    { wch: 15 },  // 结算单位
                    { wch: 20 },  // 结算工程
                    { wch: 20 },  // 机具名称
                    { wch: 15 },  // 规格型号
                    { wch: 8 },   // 单位
                    { wch: 10 },  // 丢失数量
                    { wch: 12 },  // 单价
                    { wch: 15 }   // 丢失费用
                ];
                worksheet['!cols'] = columnWidths;

                // 添加工作表到工作簿
                XLSX.utils.book_append_sheet(workbook, worksheet, '丢失费用报表');

                // 生成文件名（包含日期范围）
                let fileName = '丢失费用报表';
                if (this.queryParams.startTime && this.queryParams.endTime) {
                    fileName += `_${this.queryParams.startTime}_至_${this.queryParams.endTime}`;
                }
                fileName += `_${new Date().toISOString().slice(0, 10)}.xlsx`;

                // 生成Excel文件并下载
                const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
                const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

                // 创建下载链接
                const link = document.createElement('a');
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', fileName);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // 清理URL对象
                URL.revokeObjectURL(url);

                this.$modal.msgSuccess('Excel导出成功');
            } catch (error) {
                console.error('导出Excel失败:', error);
                this.$modal.msgError('导出Excel失败，请稍后重试');
            }
        },
    },
}
</script>

<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
    width: 80px !important;
    margin-bottom: 10px;
}
</style>
