<template>
    <!-- 完工结算和结算明细页面 -->
    <div>
        <PageHeader :pageContent="pageContent" @goBack="goBack" />
        <div class="row-header">
            <div>领用单位：{{ currRowInfo.unitName }}</div>
            <div>工程名称：{{ currRowInfo.projectName }}</div>
            <div>总合计：{{ totalAmount }}元</div>
            <div>
                <el-button size="mini" type="primary" @click="handleExportAll()"
                    >导出全部明细表</el-button
                >
            </div>
        </div>
        <!-- 01承担方 -->
        <FinishTable
            :listType="1"
            :constBear="1"
            :isCostBear="true"
            :isSettle="isSettle_01"
            @submitSell="submitSell"
            :tableTitle="`设备结算清单`"
            @handleExport="handleExport"
            :tableData="settleTableData_01"
            :totalPrice="settleTotalPrice_01"
            :tableColumns="settleTableColumns"
            v-if="settleTableData_01.length > 0"
            @handelSaveSuccess="handelSaveSuccess"
        />
        <!-- 03承担方 -->
        <FinishTable
            :listType="2"
            :constBear="3"
            :isCostBear="true"
            :isSettle="isSettle_03"
            @submitSell="submitSell"
            :tableTitle="`设备结算清单`"
            @handleExport="handleExport"
            :tableData="settleTableData_03"
            :totalPrice="settleTotalPrice_03"
            :tableColumns="settleTableColumns"
            v-if="settleTableData_03.length > 0"
            @handelSaveSuccess="handelSaveSuccess"
        />
        <FinishTable
            :listType="3"
            :isRepair="true"
            :tableTitle="`设备维修清单`"
            :currRowInfo="currRowInfo"
            :tableData="repairTableData"
            @handleExport="handleExport"
            :totalPrice="repairTotalPrice"
            :tableColumns="repairTableColumns"
            @onChangeRepairPrice="onChangeRepairPrice"
        />
        <FinishTable
            :listType="4"
            @handleExport="handleExport"
            :tableData="noReturnTableData"
            :tableTitle="`工机具未还赔偿清单`"
            :totalPrice="noReturnTotalPrice"
            :tableColumns="noReturnTableColumns"
        />
        <FinishTable
            :listType="5"
            @handleExport="handleExport"
            :tableData="scrapTableData"
            :totalPrice="scrapTotalPrice"
            :tableTitle="`工机具报废赔偿清单`"
            :tableColumns="scrapTableColumns"
        />
        <FinishTable
            :listType="6"
            @handleExport="handleExport"
            :tableTitle="`工机具待报废清单`"
            :tableData="stayScrapTableData"
            :tableColumns="stayScrapTableColumns"
        />

        <OtherCost
            ref="otherCostRef"
            :addCost="addCost"
            :pageContent="pageContent"
            @setOtherCostPrice="setOtherCostPrice"
            :otherCostListDetailsNew="otherCostListDetails"
        />

        <el-row class="submit-btn">
            <el-button
                size="mini"
                type="primary"
                @click="submitComSett"
                v-if="currRowInfo.isSlt == 0"
                >确认完工结算</el-button
            >
        </el-row>
    </div>
</template>

<script>
import PageHeader from '@/components/pageHeader'
import FinishTable from './finishTable.vue'
import OtherCost from './other-cost.vue'
import {
    getComSellQueryApi,
    submitFeeBearApi,
    submitAllFeeBearApi,
} from '@/api/cost/cost.js'
export default {
    components: {
        PageHeader,
        FinishTable,
        OtherCost,
    },
    props: {
        // 页面标题
        pageContent: {
            type: String,
            default: () => '完工结算',
        },
        // 当前行的数据信息
        currRowInfo: {
            type: Object,
            default: () => null,
        },
    },
    computed: {
        totalAmount() {
            return (
                this.settleTotalPrice_01 * 1 +
                this.settleTotalPrice_03 * 1 +
                this.repairTotalPrice * 1 +
                this.noReturnTotalPrice * 1 +
                this.scrapTotalPrice * 1 +
                this.addCost
            )
        },
    },
    data() {
        return {
            // 结算清单配置项
            settleTableColumns: [
                { t_prop: 'typeName', t_label: '机具名称' },
                { t_prop: 'modelName', t_label: '规格型号' },
                { t_prop: 'nuitName', t_label: '计量单位' },
                { t_prop: 'num', t_label: '数量' },
                { t_prop: 'leasePrice', t_label: '台班费单价（元/天）' },
                { t_prop: 'startTime', t_label: '起租日期' },
                { t_prop: 'endTime', t_label: '终止日期', t_slot: 't_date' },
                { t_prop: 'leaseDays', t_label: '应结算天数' },
                { t_prop: 'costs', t_label: '应结算金额（元）' },
                { t_prop: 'trimDay', t_label: '调整天数', t_slot: 't_ipt' },
                { t_prop: 'realDays', t_label: '实际结算天数' },
                { t_prop: 'realCosts', t_label: '实际结算金额（元）' },
                // { t_prop: '', t_label: '已入账金额（元）' },
                // { t_prop: '', t_label: '本次结算金额（元）' },
            ],
            // 维修清单配置项
            repairTableColumns: [
                { t_prop: 'typeName', t_label: '机具名称' },
                { t_prop: 'modelName', t_label: '规格型号' },
                { t_prop: 'nuitName', t_label: '计量单位' },
                { t_prop: 'partName', t_label: '维修配件名称' },
                { t_prop: 'partModelName', t_label: '维修配件型号' },
                { t_prop: 'partNum', t_label: '使用数量' },
                { t_prop: 'partPrice', t_label: '配件单价' },
                { t_prop: 'partAllCosts', t_label: '配件总价' },
                // { t_prop: '', t_label: '委外维修费用' },
                // { t_prop: '', t_label: '费用总价' },
            ],
            // 未还赔偿清单配置项
            noReturnTableColumns: [
                { t_prop: 'typeName', t_label: '机具名称' },
                { t_prop: 'modelName', t_label: '规格型号' },
                { t_prop: 'nuitName', t_label: '计量单位' },
                { t_prop: 'maCode', t_label: '设备编码' },
                { t_prop: 'num', t_label: '未还数量' },
                { t_prop: 'buyPrice', t_label: '赔偿单价' },
                { t_prop: 'costs', t_label: '赔偿金额' },
            ],
            // 报废清单单配置项
            scrapTableColumns: [
                { t_prop: 'typeName', t_label: '机具名称' },
                { t_prop: 'modelName', t_label: '规格型号' },
                { t_prop: 'nuitName', t_label: '计量单位' },
                { t_prop: 'maCode', t_label: '设备编码' },
                { t_prop: 'num', t_label: '报废数量' },
                { t_prop: 'costs', t_label: '赔偿单价' },
                { t_prop: 'buyPrice', t_label: '赔偿金额' },
            ],
            // 待报废清单配置项
            stayScrapTableColumns: [
                { t_prop: 'typeName', t_label: '机具名称' },
                { t_prop: 'modelName', t_label: '规格型号' },
                { t_prop: 'nuitName', t_label: '计量单位' },
                { t_prop: 'maCode', t_label: '设备编码' },
                { t_prop: 'num', t_label: '报废数量' },
                { t_prop: '', t_label: '状态', t_slot: 'status' },
            ],
            // 结算清单数据源 01承担方
            settleTableData_01: [],
            // 结算清单数据源 03承担方
            settleTableData_03: [],
            // 维修清单数据源
            repairTableData: [],
            // 未还赔偿清单数据源
            noReturnTableData: [],
            // 报废清单数据源
            scrapTableData: [],
            // 待报废清单数据源
            stayScrapTableData: [],
            // 其他费用
            otherCostListDetails: [],
            // 合计金额
            settleTotalPrice_01: 0,
            settleTotalPrice_03: 0,
            repairTotalPrice: 0,
            noReturnTotalPrice: 0,
            scrapTotalPrice: 0,
            // 是否结算
            isSettle_01: 0,
            isSettle_03: 0,
            // 选中的维修数据
            repairSelectList: [],
            addCost: 0,
        }
    },
    created() {
        this.getComSellList()
    },
    methods: {
        /** 获取结算信息 */
        async getComSellList() {
            const { data: res } = await getComSellQueryApi([
                { agreementId: this.currRowInfo.agreementId },
            ])

            this.settleTableData_01 = res.leaseListOne // 01承担方
            this.settleTableData_03 = res.leaseListThree // 03承担方
            this.repairTableData = res.repairList // 维修单
            this.noReturnTableData = res.loseList // 未还赔偿
            this.scrapTableData = res.scrapList // 报废单
            this.stayScrapTableData = res.preScrapList // 报废单
            this.otherCostListDetails = res.addCostList

            this.settleTotalPrice_01 = res.relations[0].leaseCostOne
            this.settleTotalPrice_03 = res.relations[0].leaseCostThree
            this.scrapTotalPrice = res.relations[0].scrapCost
            this.noReturnTotalPrice = res.relations[0].loseCost
            this.repairTotalPrice = res.relations[0].repairCost
            this.addCost = res.relations[0].addCost
            this.isSettle_01 = res.relations[0].isSltOne
            this.isSettle_03 = res.relations[0].isSltThree
        },
        /** 确认结算 01或03 */
        async submitSell(type) {
            const sellParams = {
                agreementId: this.currRowInfo.agreementId,
                costBearingParty: type,
            }
            const res = await submitFeeBearApi(sellParams)

            if (res.code == 200) {
                this.$message.success('结算成功！')
                this.getComSellList()
            }
        },
        /** 确认完工结算 */
        submitComSett() {
            // if (this.$refs.otherCostRef.isFailed) return
            const isCheckPass = this.$refs.otherCostRef.onCheckOtherCost()
            if (!isCheckPass) return
            this.$confirm(
                '确定后则会生成财务报表，数据将不可修改，请确认检查无误',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                },
            )
                .then(async () => {
                    // 1. 先判断01 03 承担方是否有数据  若有数据 先确认终结日期是否为空 若为空 提示客户修改
                    this.$message.closeAll()
                    let isFlag = false
                    try {
                        // 1.1  先循环列表数据 判断 终结日期是否为空
                        if (this.settleTableData_01.length > 0) {
                            this.settleTableData_01.map((e, v) => {
                                if (!e.endTime) {
                                    this.$message.error(
                                        '结算清单内终止日期不能有空值！',
                                    )
                                    isFlag = true
                                    throw new Error()
                                }
                            })
                        }

                        if (this.settleTableData_03.length > 0) {
                            this.settleTableData_03.map((e, v) => {
                                if (!e.endTime) {
                                    this.$message.error(
                                        '结算清单内终止日期不能有空值！',
                                    )
                                    isFlag = true
                                    throw new Error()
                                }
                            })
                        }
                    } catch {}
                    if (isFlag) return
                    let repairIds = []
                    //  2. 处理勾选需要收费的维修数据 ids
                    if (this.repairSelectList.length > 0) {
                        this.repairSelectList.forEach((e) => {
                            repairIds.push(e.id)
                        })
                    }

                    // 3. 组装请求参数
                    const params = {
                        repairIds: repairIds.join(','),
                        agreementId: this.currRowInfo.agreementId,
                        relation: {
                            leaseCostOne: this.settleTotalPrice_01, // 01承担方费用
                            leaseCostThree: this.settleTotalPrice_03, // 0.承担方
                            repairCos: this.repairTotalPrice, // 维修
                            scrapCost: this.scrapTotalPrice, // 报废
                            loseCost: this.noReturnTotalPrice, // 遗失
                            cost: this.totalAmount, // 总价
                            applyRelation:
                                this.$refs.otherCostRef.addOtherCostList, // 其他费用
                        },
                    }

                    // 4. 发送请求
                    console.log(params, '参数---')

                    const res = await submitAllFeeBearApi(params)

                    if (res.code === 200) {
                        this.$message.success('结算成功！')
                        this.$emit('closeCurrPage', true)
                    }
                    console.log(res, '结果结果')
                })
                .catch(() => {})
        },
        // 编辑后保存成功刷新列表
        handelSaveSuccess() {
            this.getComSellList()
        },
        /** 全部导出 */
        handleExportAll() {
            for (let i = 1; i < 7; i++) {
                this.handleExport(i)
            }
        },
        /** 单个导出 */
        handleExport(type) {
            let exportUrl = 'material/sltAgreementInfo/'
            let exportTitle = ''
            switch (type) {
                case 1:
                    exportUrl += 'exportLeaseOne'
                    exportTitle = '设备结算清单(费用承担方01)'
                    break
                case 2:
                    exportUrl += 'exportLeaseThree'
                    exportTitle = '设备结算清单(费用承担方03)'
                    break
                case 3:
                    exportUrl += 'exportRepair'
                    exportTitle = '设备维修清单'
                    break
                case 4:
                    exportUrl += 'exportLose'
                    exportTitle = '工机具未还赔偿清单'
                    break
                case 5:
                    exportUrl += 'exportScrap'
                    exportTitle = '工机具报废赔偿清单'
                    break
                case 6:
                    exportUrl += 'exportPreScrap'
                    exportTitle = '工机具待报废清单'
                    break
            }

            this.downloadJson(
                exportUrl,
                JSON.stringify([{ agreementId: this.currRowInfo.agreementId }]),
                `${exportTitle}-${new Date().getTime()}.xlsx`,
            )
        },

        /** 维修费用选择时 */
        onChangeRepairPrice(val, list) {
            this.repairTotalPrice = val
            this.repairSelectList = list
        },
        /** 返回按钮 关闭当前页面 */
        goBack() {
            this.$emit('closeCurrPage')
        },

        /* 其他费用变化时事件 */
        setOtherCostPrice(val) {
            this.addCost = val
        },
    },
}
</script>

<style scoped lang="scss">
.row-header {
    margin-top: 20px;
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: bold;

    div {
        margin-right: 30px;
    }

    & div:nth-child(3) {
        margin-right: 15px;
        color: rgb(255, 0, 0);
    }
}

.submit-btn {
    margin-top: 20px;
    text-align: right;

    .el-button {
        padding: 10px 14px;
    }
}
</style>
