<template>
    <div class="app-container" id="repairReportList">
        <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="startTime">
                <el-date-picker
                v-model="queryParams.startTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="开始日期"
                @change="() => queryParams.endTime = ''"
                style="width: 130px"
                />
            </el-form-item>
            <el-form-item>-</el-form-item>
            <el-form-item prop="endTime">
                <el-date-picker
                v-model="queryParams.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="结束日期"
                :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
                style="width: 130px"
                />
            </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 :max-height="650">
            <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="impUnitName" width="150px":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="costs" width="120">
                <template slot-scope="scope">
                    {{ scope.row.costs ? scope.row.costs.toFixed(2) : '0.00' }}
                </template>
            </el-table-column>
            <el-table-column label="维修方式" align="center" prop="repairType" width="120" />
            <el-table-column label="费用类型" align="center" prop="partType" width="120" />
        </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 { getRepairReportList } 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: 'RepairReportHome',
    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
            getRepairReportList(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;
            }
            const formatTime = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}${month}${day}_${hours}${minutes}${seconds}`;
            };

            const currentTime = formatTime(new Date());
            this.download(
                '/material/slt_agreement_info/exportRepairList',
                {
                ...this.queryParams,
                },
                `维修费用报表_${currentTime}.xlsx`
            )

        },
    },
}
</script>

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