<template>
    <div class="app-container" id="costApplyList">
        <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-cascader v-model="unitIds"
                    :show-all-levels="false"
                    :options="unitList"
                    :props="selectTreeProps"
                    filterable
                    clearable
                    collapse-tags
                    @change="unitChange"
                    placeholder="请选择单位"
                ></el-cascader>  -->
            </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-cascader v-model="projectIds"
                        :show-all-levels="false"
                        :options="proList"
                        :props="selectTreeProps"
                        filterable clearable
                        collapse-tags
                        @change="proChange"
                        placeholder="请选择工程"
                    ></el-cascader>  -->
            </el-form-item>
            <el-form-item prop="agreementCode">
                <el-input v-model="queryParams.agreementCode" placeholder="请输入协议号" clearable disabled />
            </el-form-item>
            <el-form-item prop="sltStatus">
                <el-select v-model="queryParams.sltStatus" placeholder="请选择结算状态" clearable filterable>
                    <el-option
                        v-for="dict in statusList"
                        :key="dict.id"
                        :label="dict.name"
                        :value="dict.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-form-item>
        </el-form>

        <el-table v-loading="loading" :data="tableList" :max-height="650">
            <el-table-column label="序号" align="center" type="index">
                <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="costs" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    {{ parseFloat(scope.row.costs || 0).toFixed(2) }}
                </template>
            </el-table-column>

            <el-table-column label="结算类型" align="center" prop="sltStatus" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.settlementType === 1" effect="plain">工器具</el-tag>
                    <el-tag type="warning" v-if="scope.row.settlementType === 2" effect="plain">安全工器具</el-tag>
                    <el-tag v-if="scope.row.settlementType == null || scope.row.settlementType === 0" effect="plain">
                        总费用
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column label="审批人" align="center" prop="auditor" :show-overflow-tooltip="true" />
            <el-table-column label="审批时间" align="center" prop="auditTime" width="100" />
            <el-table-column label="结算状态" align="center" prop="sltStatus" :show-overflow-tooltip="true">
                <!--                <template slot-scope="scope">-->
                <!--                    <dict-tag :options="dict.type.cost_status" :value="scope.row.sltStatus"/>-->
                <!--                </template>-->
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.sltStatus == '1'">待审核</el-tag>
                    <el-tag type="success" v-if="scope.row.sltStatus == '2'">审核通过</el-tag>
                    <el-tag type="danger" v-if="scope.row.sltStatus == '3'">审核驳回</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="normal" icon="el-icon-search" @click="handleView(scope.row)">
                        查看
                    </el-button>
                    <el-button
                        size="mini"
                        type="primary"
                        icon="el-icon-edit"
                        @click="handleExame(scope.row)"
                        v-if="scope.row.sltStatus == '1'"
                    >
                        审批
                    </el-button>
                    <!-- <el-button size="mini" type="danger" icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >撤销申请</el-button> -->
                    <el-button type="primary" plain size="mini" @click="openPrintDialog(scope.row)">协议书</el-button>
                </template>
            </el-table-column>
        </el-table>

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

        <!-- 审批弹窗 -->
        <el-dialog title="结算审批" :visible.sync="applyVisible" width="650px" append-to-body>
            <el-form ref="aform" :model="aform" label-width="120px">
                <el-form-item label="结算审批" prop="status">
                    <el-radio v-model="aform.status" label="2">通过</el-radio>
                    <el-radio v-model="aform.status" label="3">不通过</el-radio>
                </el-form-item>
                <el-form-item label="原因" prop="remark">
                    <el-input
                        v-model="aform.remark"
                        maxlength="100"
                        placeholder="请输入"
                        show-word-limit
                        size="small"
                        style="width: 350px"
                        type="textarea"
                        rows="4"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="submitListForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 协议单弹窗 -->
        <el-dialog :visible.sync="openPrint" width="1100px" append-to-body>
            <div style="height: 600px; overflow-y: scroll">
                <vue-easy-print tableShow ref="remarksPrintRef" class="print">
                    <div style="text-align: center; font-weight: 600; font-size: 16px">
                        机具设备有偿使用费结算协议书
                    </div>
                    <div class="info" style="margin-top: 10px; display: flex; flex-wrap: wrap">
                        <div class="item" style="width: 65%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px"></div>
                        <div class="item" style="width: 35%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
                            <span>协议号：{{ agreementContent.agreementCode }}</span>
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 20%">工程名称：</div>
                        <div class="columnContent" style="width: 80%">{{ agreementContent.projectName }}</div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 20%">承租单位：</div>
                        <div class="columnContent" style="width: 40%">{{ agreementContent.unitName }}</div>
                        <div class="columnLabel" style="width: 10%; border-left: 1px solid #9c9c9c">日期：</div>
                        <div class="columnContent" style="width: 30%">{{ agreementContent.applyTime }}</div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 100%">结算项目及金额(元)</div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">一、施工机具有偿使用费：</div>
                        <div class="columnContent" style="width: 40%">
                            ￥ {{ Number(agreementContent.leaseCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">二、施工机具维修费：</div>
                        <div class="columnContent" style="width: 40%">
                            ￥ {{ Number(agreementContent.repairCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">三、施工机具丢失费：</div>
                        <div class="columnContent" style="width: 40%">
                            ￥ {{ Number(agreementContent.loseCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">四、施工机具损坏赔偿费：</div>
                        <div class="columnContent" style="width: 40%">
                            ￥ {{ Number(agreementContent.scrapCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 60%">五、施工机具租赁减免费：</div>
                        <div class="columnContent" style="width: 40%">
                            ￥ {{ Number(agreementContent.reductionCost).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 20%">费用合计金额（大写）：</div>
                        <div class="columnContent" style="width: 40%">{{ agreementContent.costAllUpper }}</div>
                        <div class="columnContent" style="width: 40%">
                            ￥ {{ Number(agreementContent.costAll).toFixed(2) }}
                        </div>
                    </div>
                    <div class="tabelColumn">
                        <div class="columnLabel" style="width: 20%">说明：</div>
                        <div class="columnContent" style="width: 80%">
                            本协议一式两份，甲方一份，乙方一份，经双方签字后生效。
                        </div>
                    </div>
                    <div class="tabelColumn" style="border: 1px solid #9c9c9c">
                        <div class="columnLabel" style="width: 20%">备注：</div>
                        <div class="columnContent" style="width: 80%">
                            此费用仅为在机具设备分公司发生费用，未计从项目部领用机具费用。
                        </div>
                    </div>

                    <div class="fillIn" style="margin-top: 20px; display: flex; justify-content: space-between">
                        <div class="item" style="width: 33%">
                            <div>
                                <span>部门负责人：</span>
                            </div>
                        </div>

                        <div class="item" style="width: 33%">
                            <div>
                                <span>承租负责人：</span>
                            </div>
                        </div>

                        <div class="item" style="width: 33%">
                            <div>
                                <span>核算员：</span>
                            </div>
                        </div>
                    </div>
                </vue-easy-print>
            </div>

            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button @click="exportExcel">导出Excel</el-button>
                <el-button type="primary" @click="print">打 印</el-button>
                <el-button @click="openPrint = false">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getProjectList, getUnitList, getAgreementInfoById, getUnitListFilterTeam } from '@/api/back/index.js'
import { getSltList, costExamine, getSltInfo } from '@/api/cost/cost'
import { toChineseAmount } from '@/utils/bonus.js'
import vueEasyPrint from 'vue-easy-print'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { formatTime } from '@/utils/bonus'
import { saveAs } from 'file-saver'
import ExcelJS from 'exceljs'

export default {
    name: 'ExamHome',
    dicts: ['cost_status'],
    components: { Treeselect, vueEasyPrint },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 单位数据
            unitList: [],
            // 工程数据
            proList: [],
            unitIds: null,
            projectIds: null,
            selectTreeProps: {
                children: 'children',
                label: 'name',
                value: 'id'
                // multiple: true,//false
            },
            statusList: [
                { id: '1', name: '待审核' },
                { id: '2', name: '审核通过' },
                { id: '3', name: '审核驳回' }
            ], //集合
            // 表格数据
            tableList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: undefined,
                sltStatus: '',
                isCommit: '',
                unitId: null,
                projectId: null,
                agreementId: null,
                agreementCode: null
            },
            openPrint: false,
            // 审批弹窗
            aform: { status: '2' },
            //审批弹窗是否开启
            applyVisible: false,
            id: '',
            agreementIdTemp: '',
            // 协议书内容
            agreementContent: {
                agreementCode: '',
                projectName: '',
                unitName: '',
                leaseCost: '', // 租赁费用
                repairCost: '', // 维修费用
                loseCost: '', // 丢失费用
                scrapCost: '', // 报废费用
                reductionCost: '', // 减免费用
                costAll: '', // 合计费用
                costAllUpper: '' // 合计费用大写
            }
        }
    },
    created() {
        this.GetUnitData()
        this.GetProData()
        this.getList()
    },
    methods: {
        /** 转换菜单数据结构 */
        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 = {
                // projectId: this.queryParams.projectId /*  */,
            }
            const res = await getUnitListFilterTeam(params)
            this.unitList = res.data

            this.getAgreementInfo()
        },
        unitChange(val) {
            // if(val&&val.length>0){
            //     this.queryParams.unitId=this.unitIds[this.unitIds.length - 1]
            // }else if(val&&val.length==0){
            //     this.queryParams.unitId=""
            // }
            // this.GetProData()
            setTimeout(() => {
                this.queryParams.projectId = null
                this.queryParams.agreementId = 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) {
            // if(val&&val.length>0){
            //     this.queryParams.projectId=this.projectIds[this.projectIds.length - 1]
            // }else if(val&&val.length==0){
            //     this.queryParams.projectId=""
            // }
            // this.GetUnitData()
            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)
                console.log(res)
                if (!(res.data && res.data.agreementId)) {
                    this.$message.error('当前单位和工程无协议！')
                    this.queryParams.unitId = null
                    this.queryParams.projectId = null
                    this.GetUnitData()
                    this.GetProData()
                } else {
                    this.queryParams.agreementId = res.data.agreementId
                    this.queryParams.agreementCode = res.data.agreementCode
                }
            }
        },

        /** 查询列表 */
        getList() {
            this.loading = true
            getSltList(this.queryParams).then(response => {
                this.tableList = response.rows
                this.total = response.total
                this.loading = false
            })
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                sltStatus: '',
                isCommit: '',
                unitId: null,
                projectId: null,
                agreementId: '',
                agreementCode: ''
            }
            this.resetForm('queryForm')
            this.handleQuery()
        },
        //结算审批查看
        handleView(row) {
            let arr = []
            arr.push(row)
            this.$emit('goDetail', JSON.stringify(arr))
        },
        //结算审批
        handleExame(row) {
            this.id = row.id
            this.agreementIdTemp = row.agreementId
            this.applyVisible = true
        },
        //提交按钮
        submitListForm() {
            let param = {
                id: this.id,
                status: this.aform.status,
                remark: this.aform.remark,
                agreementId: this.agreementIdTemp
            }
            costExamine(param)
                .then(res => {
                    if (res.code == 200) {
                        this.$modal.msgSuccess('审批成功')
                        this.getList()
                        this.applyVisible = false
                    } else {
                        this.$modal.msgError(res.msg)
                    }
                })
                .catch(() => {})
        },

        //取消按钮
        cancel() {
            this.applyVisible = false
            this.aform = { status: '2' }
        },

        async openPrintDialog(row) {
            this.openPrint = true
            try {
                const res = await getSltInfo([row])
                console.log('🚀 ~ openPrintDialog ~ res:', res)
                if (!res.data) return
                this.agreementContent = res.data
                this.agreementContent.agreementCode = row.agreementCode
                this.agreementContent.costAll =
                    Number(res.data.leaseCost) +
                    Number(res.data.repairCost) +
                    Number(res.data.scrapCost) +
                    Number(res.data.loseCost) -
                    Number(res.data.reductionCost)
                // costAllUpper 中文大写
                this.agreementContent.costAllUpper = toChineseAmount(this.agreementContent.costAll.toFixed(2))
            } catch (error) {
                console.log('🚀 ~ openPrintDialog ~ error:', error)
            }
        },
        //维修任务单打印
        print() {
            this.$refs.remarksPrintRef.print()
        },
        async exportExcel() {
            const data = this.agreementContent
            const workbook = new ExcelJS.Workbook()
            const sheet = workbook.addWorksheet('结算协议')

            // ======= 公共边框样式 =======
            const borderStyle = {
                top: { style: 'thin' },
                left: { style: 'thin' },
                bottom: { style: 'thin' },
                right: { style: 'thin' }
            }

            // ======= 列宽设置 =======
            sheet.columns = [{ width: 25 }, { width: 50 }, { width: 25 }, { width: 35 }]

            // ======= 标题 =======
            sheet.mergeCells('A1:D1')
            const title = sheet.getCell('A1')
            title.value = '机具设备有偿使用费结算协议书'
            title.font = { bold: true, size: 16 }
            title.alignment = { horizontal: 'center', vertical: 'middle' }

            // ======= 协议号 =======
            sheet.mergeCells('A2:D2')
            const codeCell = sheet.getCell('A2')
            codeCell.value = `协议号：${data.agreementCode}`
            codeCell.alignment = { horizontal: 'right', vertical: 'middle' }

            // ======= 工程名称 =======
            const r3 = sheet.addRow(['工程名称：', data.projectName, '', ''])
            sheet.mergeCells(`B${r3.number}:D${r3.number}`)
            r3.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 承租单位 + 日期 =======
            const r4 = sheet.addRow(['承租单位：', data.unitName, '日期：', data.applyTime])
            r4.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 表头 =======
            const r6 = sheet.addRow(['结算项目及金额(元)', '', '', ''])
            sheet.mergeCells(`A${r6.number}:D${r6.number}`)
            r6.eachCell(c => {
                c.border = borderStyle
                c.font = { bold: true }
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 金额明细 =======
            const items = [
                ['一、施工机具有偿使用费：', `￥ ${Number(data.leaseCost).toFixed(2)}`],
                ['二、施工机具维修费：', `￥ ${Number(data.repairCost).toFixed(2)}`],
                ['三、施工机具丢失费：', `￥ ${Number(data.loseCost).toFixed(2)}`],
                ['四、施工机具损坏赔偿费：', `￥ ${Number(data.scrapCost).toFixed(2)}`],
                ['五、施工机具租赁减免费：', `￥ ${Number(data.reductionCost).toFixed(2)}`]
            ]
            items.forEach(row => {
                const r = sheet.addRow([row[0], '', '', row[1]])
                sheet.mergeCells(`A${r.number}:C${r.number}`)
                r.eachCell(c => {
                    c.border = borderStyle
                    c.alignment = { horizontal: 'center', vertical: 'middle' }
                })
            })

            // ======= 合计 =======
            const totalRow = sheet.addRow([
                '费用合计金额（大写）：',
                data.costAllUpper,
                '',
                `￥ ${Number(data.costAll).toFixed(2)}`
            ])
            sheet.mergeCells(`B${totalRow.number}:C${totalRow.number}`)
            totalRow.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 说明 =======
            const explainRow = sheet.addRow([
                '说明：',
                '本协议一式两份，甲方一份，乙方一份，经双方签字后生效。',
                '',
                ''
            ])
            sheet.mergeCells(`B${explainRow.number}:D${explainRow.number}`)
            explainRow.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 备注 =======
            const remarkRow = sheet.addRow([
                '备注：',
                '此费用仅为在机具设备分公司发生费用，未计从项目部领用机具费用。',
                '',
                ''
            ])
            sheet.mergeCells(`B${remarkRow.number}:D${remarkRow.number}`)
            remarkRow.eachCell(c => {
                c.border = borderStyle
                c.alignment = { horizontal: 'center', vertical: 'middle' }
            })

            // ======= 空行 =======
            sheet.addRow(['', '', '', ''])

            // ======= 签名行（无边框 + 左对齐 + 三等分） =======
            const signRow = sheet.addRow(['部门负责人：', '承租负责人：', '核算员：'])
            signRow.eachCell(cell => {
                cell.border = undefined
                cell.alignment = { horizontal: 'left', vertical: 'middle' }
            })

            // ======= 导出文件 =======
            const buf = await workbook.xlsx.writeBuffer()
            saveAs(new Blob([buf]), `机具设备有偿使用费结算协议书-${data.agreementCode}_${formatTime(new Date())}.xlsx`)
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
    width: 80px !important;
    margin-bottom: 10px;
}
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}
.tabelColumn {
    width: 1000px;
    height: 50px;
    display: flex;
    align-items: center;
    border: 1px solid #9c9c9c;
    // margin-bottom: 1px;
    border-bottom: none;
}
.columnLabel {
    height: 50px;
    line-height: 50px;
    text-align: center;
    border-left: none;
}
.columnContent {
    height: 50px;
    line-height: 50px;
    text-align: center;
    border-left: 1px solid #9c9c9c;
}
</style>
