<template>
    <!-- 完工结算和结算明细页面的表格组件 -->
    <div style="margin-top: 60px">
        <el-row class="table-title" type="flex">
            <div class="batch-system-day" v-if="isCostBear && isEdit">
                调整天数批量设置：
                <el-input
                    v-model="batchNum"
                    ref="batchNumRef"
                    type="number"
                    clearable
                    style="width: 120px"
                    @change="iptChange"
                />
            </div>
            <span class="repair-tip" v-if="isRepair">
                {{
                    currRowInfo.isSlt == 0
                        ? '勾选需要赔偿的维修项目'
                        : '已选的维修赔偿项目'
                }}</span
            >
            <el-col :span="5" class="cost-bear">
                <span v-if="isCostBear">{{
                    constBear === 1 ? '费用承担方：01' : '费用承担方：03'
                }}</span>
                <span v-else />
                <span v-if="totalPrice !== -1">合计：{{ totalPrice }}元</span>
            </el-col>
            <el-col :span="14" class="title">{{ tableTitle }}</el-col>
            <el-col :span="5" class="btn-item">
                <el-button
                    size="mini"
                    type="warning"
                    v-if="!isEdit"
                    @click="handleExport"
                    >导出</el-button
                >
                <el-button
                    size="mini"
                    type="primary"
                    v-if="
                        isSettle == 0 &&
                        (isCostBear || (isRepair && currRowInfo.isSlt == 0)) &&
                        tableData.length > 0
                    "
                    @click="handleEdit"
                    >{{ isEdit ? '取消编辑' : '编辑' }}</el-button
                >
                <el-button
                    size="mini"
                    type="success"
                    v-if="!isEdit && isCostBear && isSettle == 0"
                    @click="submitSell"
                    >确认结算</el-button
                >
                <el-button
                    size="mini"
                    type="success"
                    v-if="isEdit && isCostBear && isSettle == 0"
                    @click="handleSave"
                    >保存</el-button
                >
            </el-col>
        </el-row>

        <el-table
            border
            :data="tableData"
            ref="tableRef"
            :header-cell-class-name="setClassName"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                v-if="isRepair && currRowInfo.isSlt == 0"
                :selectable="() => !this.selDisabled"
            />
            <el-table-column
                align="center"
                width="55"
                v-if="isRepair && currRowInfo.isSlt == 1"
            >
                <template slot-scope="{ row }">
                    <el-checkbox :checked="row.isSlt == 1" disabled />
                </template>
            </el-table-column>

            <el-table-column
                align="center"
                v-for="(t, index) in tableColumns"
                :key="index"
                :label="t.t_label"
                :width="t.t_slot === 't_date' ? '180' : ''"
                show-overflow-tooltip
            >
                <template slot-scope="scope">
                    <template v-if="t.t_slot && isEdit">
                        <!-- 调整天数时的输入框 -->
                        <el-input
                            v-if="t.t_slot === 't_ipt'"
                            v-model.number="scope.row[t.t_prop]"
                            style="width: 80px"
                            type="number"
                            :ref="`editIpt_${scope.$index}`"
                            :class="{
                                active: activeIndex === scope.$index,
                            }"
                        />

                        <!-- 调整终结日期的日期选择组件 -->
                        <el-date-picker
                            v-model="scope.row[t.t_prop]"
                            type="date"
                            placeholder="选择日期"
                            v-if="t.t_slot === 't_date'"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            :ref="`editTime_${scope.$index}`"
                            :class="{
                                active: activeIndexTime === scope.$index,
                            }"
                            :picker-options="{
                                disabledDate: (time) => {
                                    const currentDate = new Date(
                                        scope.row.startTime || new Date(),
                                    )
                                    currentDate.setDate(
                                        currentDate.getDate() - 1,
                                    )
                                    return (
                                        time.getTime() < currentDate.getTime()
                                    )
                                },
                            }"
                            style="width: 150px"
                        />
                    </template>
                    <template v-else-if="t.t_slot && t.t_slot === 'status'">
                        <el-tag size="mini" type="warning">待报废</el-tag>
                    </template>
                    <template v-else>
                        {{ scope.row[t.t_prop] }}
                    </template>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import { editSaveApi } from '@/api/cost/cost.js'
export default {
    props: {
        // 列表每一列配置项
        tableColumns: {
            type: Array,
            default: () => [],
        },
        // 列表上方标题
        tableTitle: {
            type: String,
            default: () => '',
        },
        // 是否显示费用承担方
        isCostBear: {
            type: Boolean,
            default: () => false,
        },
        // 是否是维修单
        isRepair: {
            type: Boolean,
            default: () => false,
        },
        // 列表数据源
        tableData: {
            type: Array,
            default: () => [],
        },
        // 01 或者 03 承担方
        constBear: {
            type: Number,
            default: () => 1,
        },
        // 合计金额
        totalPrice: {
            type: [Number, String],
            default: () => -1,
        },
        // 是否结算  0是未结算 1是已结算
        isSettle: {
            type: [Number, String],
            default: () => 0,
        },
        // 列表类型 1 01承担方 2 03承担方 3 维修 4 未还 5 报废 6 待报废
        listType: {
            type: Number,
            default: () => 0,
        },
        // 当前行的数据信息
        currRowInfo: {
            type: Object,
            default: () => null,
        },
    },

    data() {
        return {
            isEdit: false, // 是否编辑数据
            batchNum: '', // 批量调整天数的数据源
            activeIndex: '', // 调整天数输入框不合格时的 index 用来设置动态 class 增加一个红色边框
            activeIndexTime: '', // 调整终结日期时的 index 用来设置动态 class 增加一个红色边框
            selDisabled: true,
        }
    },

    methods: {
        /** 编辑按钮 */
        handleEdit() {
            this.isEdit = !this.isEdit
            if (!this.isEdit) {
                this.batchNum = ''
                this.$emit('handelSaveSuccess')
            }

            if (this.isRepair) {
                this.$refs.tableRef.clearSelection()
                this.selDisabled = !this.selDisabled
            }
        },
        /** 调整天数 */
        iptChange(val) {
            const regex = /^-?\d+$/
            const isNum = regex.test(val)
            if (!isNum) {
                this.$message.error('请输入正整数或负整数或0！')
                return
            }

            this.tableData.map((e) => {
                e.trimDay = val
            })
        },
        /** 保存按钮 */
        async handleSave() {
            const regex = /^-?\d+$/
            let isNum = false
            try {
                // 1. 先循环列表数据 判断调整的天数是否符合要求
                this.tableData.map((e, v) => {
                    console.log(e)
                    this.$message.closeAll()
                    if (!e.endTime) {
                        this.$message.error('请选择终结日期！')
                        this.activeIndexTime = v
                        this.$refs[`editTime_${v}`][0].focus()
                        isNum = true
                        throw new Error()
                    }
                    if (!regex.test(e.trimDay)) {
                        this.$message.error('请输入正整数或负整数或0！')
                        this.activeIndex = v
                        this.$refs[`editIpt_${v}`][0].focus()
                        isNum = true
                        throw new Error()
                    }
                    if (e.trimDay < 0 && Math.abs(e.trimDay) > e.leaseDays) {
                        this.$message.error('减免天数不能大于应结算天数！')
                        this.activeIndex = v
                        this.$refs[`editIpt_${v}`][0].focus()
                        isNum = true
                        throw new Error()
                    }
                })

                if (isNum) return

                // 2. 组装保存时的参数
                let saveParams = []
                this.tableData.map((e) => {
                    const item = {
                        agreementId: e.agreementId, // 协议id
                        id: e.id,
                        typeId: e.typeId, // 设备id
                        trimDay: e.trimDay, // 调整的天数
                        maId: e.maId || '',
                        endTime: e.endTime, // 终结时间
                    }

                    saveParams.push(item)
                })

                // 3. 请求后台接口传递更改后的数据
                const res = await editSaveApi(saveParams)

                if (res.code == 200) {
                    this.$message.success('保存成功！')
                    this.activeIndex = ''
                    this.activeIndexTime = ''
                    this.batchNum = ''
                    this.isEdit = false
                    this.$emit('handelSaveSuccess')
                }
            } catch {}
        },
        /** 单个列表确认结算 */
        submitSell() {
            let isFlag = false
            this.$message.closeAll()
            try {
                // 1. 先循环列表数据 判断 终结日期是否为空
                this.tableData.map((e, v) => {
                    if (!e.endTime) {
                        this.$message.error('终止日期不能有空值！')
                        isFlag = true
                        throw new Error()
                    }
                })
                if (isFlag) return
                // 2. 提示并通知父组件请求后台接口
                this.$confirm(
                    '确定后则会生成财务报表，数据将不可修改，请确认检查无误',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    },
                ).then(() => {
                    this.$emit('submitSell', `0${this.constBear}`)
                })
            } catch {}
        },
        /** 导出按钮 */
        handleExport() {
            this.$emit('handleExport', this.listType)
        },
        setClassName({ column }) {
            // 若为选择框,且数据皆为不可选时
            if (column.type == 'selection' && this.selDisabled) {
                return 'all-disabled'
            }
        },
        /** 列表复选框选择事件 */
        handleSelectionChange(list) {
            let repairPriceAmount = 0
            console.log(list, 'list')
            list.forEach((e) => {
                repairPriceAmount += e.partAllCosts * 1
            })
            this.$emit('onChangeRepairPrice', repairPriceAmount, list)
        },
    },
}
</script>

<style scoped lang="scss">
.table-title {
    position: relative;
    min-height: 48px;
    border: 1px solid #7e7e7e;
    background: linear-gradient(to right, #b4b3b3, #edebeb);
    align-items: center !important;
    justify-content: space-around;

    .cost-bear {
        display: flex;
        padding-left: 12px;
        font-weight: bold;
        color: red;

        span {
            width: 50%;
        }
    }

    .title {
        margin: auto 0;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
        letter-spacing: 4px;
    }

    .btn-item {
        text-align: right;
        padding-right: 12px;

        .el-button {
            padding: 6px 10px;
        }
    }

    // 维修单提示
    .repair-tip {
        position: absolute;
        left: 2px;
        bottom: 2px;
        color: red;
        font-size: 12px;
    }

    // 批量调整天数设置
    .batch-system-day {
        position: absolute;
        top: -50px;
        right: 30px;
        height: 36px;
        line-height: 36px;
    }
}
::v-deep .active {
    .el-input__inner:focus {
        border-color: #f56c6c;
    }
}
::v-deep .all-disabled .el-checkbox__input .el-checkbox__inner {
    background-color: #edf2fc;
    border-color: #dcdfe6;
    cursor: not-allowed;
}
</style>
