<template>
    <div class="" id="lostReportList">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
            <el-row>
            <el-form-item label="结算单位" 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 label="结算工程" 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 style="width: 220px"/>
            </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-row>

            <el-row>
            <el-form-item label="物资名称" prop="typeName">
            <el-select
                v-model="queryParams.typeName"
                placeholder="请选择物资名称"
                style="width: 240px"
                clearable
                filterable
            >
                <el-option
                v-for="item in typeNameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                />
            </el-select>
            </el-form-item>

            <el-form-item label="规格型号" prop="modelName">
            <el-select
                v-model="queryParams.modelName"
                placeholder="请选择规格型号"
                style="width: 240px"
                clearable
                filterable
            >
                <el-option
                v-for="item in typeModelNameOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                />
            </el-select>
            </el-form-item>
                    <el-form-item prop="keyWord">
            <el-input
                v-model="queryParams.keyWord"
                placeholder="请输入关键字"
                clearable :maxlength="20"
                style="width: 220px"
            />
            </el-form-item>
              <el-form-item prop="isFinish">
                <el-select v-model="queryParams.isFinish" placeholder="请选择竣工状态" clearable filterable>
                  <el-option
                    v-for="item in proStatus"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>

              </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-row>
        </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="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(2) }}
                </template>
            </el-table-column>
            <el-table-column label="竣工状态" align="center" prop="isFinish" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.isFinish == 1" effect="plain">已竣工</el-tag>
                <el-tag type="warning" v-if="scope.row.isFinish == 0" effect="plain">未竣工</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="竣工日期" align="center" prop="actualEndDate" :show-overflow-tooltip="true"/>
        </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 {getDeviceType} from "@/api/ma/device";
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,
                typeName: null,
                modelName: null,
                keyWord: null,
                isFinish: null,
            },
            typeNameOptions:[],
            typeModelNameOptions:[],
            proStatus:[
              { id: 0, name: '未竣工' },
              { id: 1, name: '已竣工' },
              { id: 2, name: '空白' },
            ],
        }
    },
    created() {
        this.initDefaultDateRange()
        this.GetUnitData()
        this.GetProData()
        this.getDeviceType()
        this.getList()
    },
    methods: {
        // async handleTypeNameChange(e){
        //     this.queryParams.modelName=null
        //     this.typeModelNameOptions=[]
        //     getDeviceType({ level: 4, typeId:e }).then(response => {
        //     let matNameRes = response.data
        //     this.typeModelNameOptions = matNameRes.map((item) => {
        //         return {
        //         label: item.typeName,
        //         value: item.typeId
        //         }
        //     })
        //     })
        // },
        getDeviceType() {
            getDeviceType({ level: 3 }).then(response => {
            let matNameRes = response.data
            this.typeNameOptions = matNameRes.map((item) => {
                return {
                label: item.typeName,
                value: item.typeName
                }
            })
            })
            getDeviceType({ level: 4 }).then(response => {
            let matModelRes = response.data
            this.typeModelNameOptions = matModelRes.map((item) => {
                return {
                label: item.typeName,
                value: item.typeName
                }
            })
            })
        },


        // 初始化默认日期范围（当月第一天到最后一天）
        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.data.rows || []
                this.total = response.data.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,
                typeName: null,
                modelName: null,
                keyWord: null,
            }
            // 重新初始化默认日期范围
            this.initDefaultDateRange()
            this.resetForm('queryForm')
            this.handleQuery()
            this.getDeviceType()
        },

        // 导出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/exportLostList',
                {
                ...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>
