<template>
    <!-- 业务办理审核  减免审核 -->
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            v-show="showSearch"
            :inline="true"
            label-width="80px"
        >
            <el-form-item prop="time" label-width="120px">
                <el-date-picker
                    v-model="queryParams.time"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    style="width: 350px"
                ></el-date-picker>
            </el-form-item>
            <el-form-item prop="keyWord">
                <el-input
                    maxlength="50"
                    v-model="queryParams.keyWord"
                    placeholder="请输入关键词"
                    clearable
                    style="width: 240px"
                />
            </el-form-item>
            <el-form-item prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                    <el-option label="待审核" value="0"></el-option>
                    <el-option label="审核中" value="1"></el-option>
                    <el-option label="已审核" value="2"></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-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">减免申请</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">
                    导出数据
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>

        <el-table v-loading="loading" :data="formList" ref="multipleTable" row-key="id" border>
            <el-table-column label="序号" align="center" width="80" type="index">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * 10 + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="申请时间" align="center" prop="createTime" show-overflow-tooltip width="200px" />
            <el-table-column label="申请人" align="center" prop="createBy" show-overflow-tooltip />
            <el-table-column label="租赁单位" align="center" prop="unitName" show-overflow-tooltip />
            <el-table-column label="租赁工程" align="center" prop="projectName" :show-overflow-tooltip="true" />
            <el-table-column label="租赁费用(元)" align="center" prop="leasePrice" :show-overflow-tooltip="true">
                <!-- <template slot-scope="scope">
              {{ scope.row.leasePrice.toFixed(2) }}
          </template> -->
            </el-table-column>
            <el-table-column
                label="本次减免费用（元）"
                align="center"
                prop="leaseMoney"
                :show-overflow-tooltip="true"
                width="150px"
            >
                <!-- <template slot-scope="scope">
              {{ scope.row.leaseMoney.toFixed(2) }}
          </template> -->
            </el-table-column>
            <el-table-column
                label="累计减免费用（元） "
                align="center"
                prop="leaseMoneyAll"
                :show-overflow-tooltip="true"
                width="150px"
            >
                <!-- <template slot-scope="scope">
              {{ scope.row.leaseMoneyAll.toFixed(2) }}
          </template> -->
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <span v-if="scope.row.status == '0'">待审核</span>
                    <span v-if="scope.row.status == '1'">审核中</span>
                    <span v-if="scope.row.status == '2'">已审核</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180">
                <template slot-scope="scope">
                    <!-- <el-button type="text" size="mini" icon="el-icon-search" @click="handleView(scope.row)">
                        查看
                    </el-button> -->
                    <el-button
                        v-if="scope.row.status != '2'"
                        type="text"
                        size="mini"
                        icon="el-icon-edit"
                        @click="handleAuditing(scope.row, 1)"
                    >
                        审核
                    </el-button>
                    <el-button
                        v-if="scope.row.taskStatus == 2"
                        type="text"
                        size="mini"
                        icon="el-icon-search"
                        @click="handleAuditing(scope.row, 2)"
                    >
                        查看
                    </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="title" :visible.sync="showApply" width="1400px" append-to-body @close="closeDiag">
            <el-form :model="dialogAppy" ref="dialogAppy" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="减免开始日期" prop="reduceStartTime">
                            <el-date-picker
                                style="width: 80%"
                                v-model="dialogAppy.reduceStartTime"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="请选择开始日期"
                                @input="updateTableStartTime"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="减免结束日期" prop="reduceEndTime">
                            <el-date-picker
                                style="width: 80%"
                                v-model="dialogAppy.reduceEndTime"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="请选择结束日期"
                                @input="updateTableEndTime"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="减免原因" prop="remark">
                            <el-input
                                type="textarea"
                                style="width: 80%"
                                :rows="5"
                                placeholder="请输入减免原因"
                                v-model="dialogAppy.remark"
                                maxlength="100"
                                show-word-limit
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="附件" prop="decreaseFile">
                            <el-upload
                                :action="uploadUrl"
                                :file-list="dialogAppy.decreaseFile"
                                :show-file-list="true"
                                :auto-upload="true"
                                :key="uploadKey"
                                :limit="3"
                                list-type="picture-card"
                                accept=".png, .jpg, .jpeg, .pdf"
                                :on-change="handleChangeBusinessList"
                                :class="{ disabledFbs: uploadDisabled }"
                                :on-preview="picturePreview"
                                :on-remove="handleRemoveElectricianImgList"
                            >
                                <!-- 文件格式下载，图片格式预览 -->
                                <div slot="file" slot-scope="{ file }">
                                    <img
                                        v-if="isImage(file)"
                                        class="el-upload-list__item-thumbnail"
                                        :src="file.url"
                                        alt=""
                                    />
                                    <div v-else class="picture-card-container">
                                        <img class="picture-card" :src="urlTemp" alt="" />
                                        <p class="file-name">{{ file.name }}</p>
                                    </div>
                                    <span class="el-upload-list__item-actions">
                                        <span
                                            v-if="updataIf(file)"
                                            class="el-upload-list__item-delete"
                                            @click="handleDownload(file)"
                                        >
                                            <i class="el-icon-download" />
                                        </span>
                                        <span v-else class="el-upload-list__item-preview" @click="picturePreview(file)">
                                            <i class="el-icon-zoom-in" />
                                        </span>
                                        <span
                                            class="el-upload-list__item-delete"
                                            @click="handleRemoveElectricianImgList(file)"
                                        >
                                            <i class="el-icon-delete" />
                                        </span>
                                    </span>
                                </div>
                                <i class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <el-row style="margin-bottom: 20px; margin-left: 20px">
                <el-col :span="10">
                    <span style="font-family: Arial; font-size: 16px; position: relative; padding-left: 20px">
                        <span
                            style="
                                position: absolute;
                                left: 0;
                                top: 50%;
                                transform: translateY(-50%);
                                width: 10px;
                                height: 10px;
                                background-color: #f5f7fa;
                                border-radius: 50%;
                                display: inline-block;
                            "
                        ></span>
                        当前减免时间符合的数据条数：{{ num1 }}
                    </span>
                </el-col>
                <el-col :span="8">
                    <span style="font-family: Arial; font-size: 16px; position: relative; padding-left: 20px">
                        <span
                            style="
                                position: absolute;
                                left: 0;
                                top: 50%;
                                transform: translateY(-50%);
                                width: 10px;
                                height: 10px;
                                background-color: #c0e6fa;
                                border-radius: 50%;
                                display: inline-block;
                            "
                        ></span>
                        当前减免时间不符合的数据条数：{{ num2 }}
                    </span>
                </el-col>
                <el-col :span="6">
                    <el-button type="success" size="small" @click="handleClean" v-if="num2 > 0">一键去除</el-button>
                </el-col>
            </el-row>

            <el-table
                v-loading="loading"
                row-key="id"
                :data="applyList"
                :span-method="objectSpanMethodApply"
                border
                :row-class-name="getRowClassName"
            >
                <el-table-column label="减免数量" align="center" prop="reduceNum" width="120px">
                    <template v-slot="scope">
                        <span
                            style="background-color: #f8f8f9; text-align: center"
                            v-if="scope.$index == applyList.length - 1"
                        >
                            小计：
                        </span>
                        <span v-else>
                            <el-input
                                v-model.number="scope.row.reduceNum"
                                controls-position="right"
                                type="number"
                                style="width: 100%"
                                :min="0"
                                @change="updateLeaseNum(scope.row)"
                            ></el-input>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="机具名称" align="center" prop="maName" :show-overflow-tooltip="true" />
                <el-table-column label="规格型号" align="center" prop="maModel" :show-overflow-tooltip="true" />
                <el-table-column label="领料数量" align="center" prop="num" :show-overflow-tooltip="true" />
                <el-table-column label="领料日期" align="center" prop="startTime" :show-overflow-tooltip="true" />
                <el-table-column label="退料日期" align="center" prop="endTime" :show-overflow-tooltip="true" />
                <el-table-column label="减免开始时间" align="center" prop="reduceStartTime" width="160px">
                    <template slot-scope="scope">
                        <el-date-picker
                            v-model="scope.row.reduceStartTime"
                            style="width: 100%"
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="开始时间"
                            clearable
                            v-if="scope.$index != applyList.length - 1"
                            @input="updateLeaseDaysStart(scope.row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="减免结束时间" align="center" prop="reduceEndTime" width="160px">
                    <template slot-scope="scope">
                        <el-date-picker
                            v-model="scope.row.reduceEndTime"
                            style="width: 100%"
                            value-format="yyyy-MM-dd"
                            type="date"
                            placeholder="结束时间"
                            clearable
                            v-if="scope.$index != applyList.length - 1"
                            @input="updateLeaseDaysEnd(scope.row)"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="租赁单价（元/天）" align="center" prop="leasePrice" width="130px" />
                <el-table-column label="减免天数" align="center" prop="reduceDays" :show-overflow-tooltip="true" />
                <el-table-column
                    label="减免费用（元）"
                    align="center"
                    width="126px"
                    prop="reduceLeaseMoney"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="scope">
                        <span>{{ scope.row.reduceLeaseMoney.toFixed(2) }}</span>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 图片查看弹窗 -->
        <el-dialog :visible.sync="dialogVisible" width="600px" height="600px">
            <img width="100%" height="500px" :src="dialogImageUrl" />
        </el-dialog>
    </div>
</template>

<script>
import { getReliefList, editRelief, getDiscountViewList } from '@/api/cost/cost'
import { getReliefRecordList, deleteRedif } from '@/api/business/index'
import { downloadFile, downloadFileData } from '@/utils/download'
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getReceiveApplyApi } from '@/api/reduction-apply/index.js'
export default {
    name: '',
    data() {
        return {
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,

            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,

            // 总条数
            total: 0,
            // 表格数据
            formList: [],
            // 费用推送审核表格数据
            pushReviewList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,

            //合计
            moneyAll: 0,
            //租赁合计
            leaseAll: 0,

            // 查询参数
            queryParams: {
                status: null,
                keyWork: '',
                time: null,
                pageSize: 10,
                pageNum: 1
            },

            // 多选框选中数据
            ids: [],

            //减免申请list
            applyList: [],
            //备份所选的数据
            applyListTemp: [],

            //减免费用弹窗
            showApply: false,
            dialogLeaseList: [], //租赁费用列表
            dialogAppy: {
                reduceStartTime: undefined,
                reduceEndTime: undefined,
                remark: '',
                decreaseFile: []
            },
            rules: {
                reduceStartTime: [{ required: true, message: '请选择减免开始日期', trigger: 'change' }],
                reduceEndTime: [{ required: true, message: '请选择减免结束日期', trigger: 'change' }],
                reason: [{ required: true, message: '减免原因不能为空', trigger: 'blur' }],
                decreaseFile: [{ required: true, message: '请上传减免附件', trigger: 'change' }]
            },
            //图片查看弹窗
            dialogImageUrl: '',
            dialogVisible: false,
            uploadKey: Date.now(),
            //上传
            // upload: {
            //   // 设置上传的请求头部
            //   headers: {Authorization: 'Bearer ' + getToken()},
            //   // 上传的地址
            //   url: process.env.VUE_APP_BASE_API + '/file/upload'
            // },
            uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload', // 上传的图片服务器地址

            delBusinessFileIdList: [], // 删除的图片id

            //弹窗确定按钮是否能点击
            btnDisabled: false,

            //当前符合的数据条数
            num1: 0,
            //当前不符合的数据条数
            num2: 0,
            isView: false,
            agreementId: '',
            idTemp: null
        }
    },
    created() {
        this.getList()
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.dialogAppy.decreaseFile && this.dialogAppy.decreaseFile.length == 3
        }
    },
    components: { Treeselect },
    methods: {
        getRowClassName({ row, rowIndex }) {
            if (this.dialogAppy.reduceStartTime && this.dialogAppy.reduceEndTime) {
                if ((!row.reduceStartTime || !row.reduceEndTime) && rowIndex != this.applyList.length - 1) {
                    return 'highlight-row'
                } else {
                }
            }
            return ''
        },

        /** 查询列表 */
        async getList() {
            this.loading = true

            const params = {
                keyWord: this.queryParams.keyWord,
                status: this.queryParams.status,
                startTime: this.queryParams.time && this.queryParams.time[0],
                endTime: this.queryParams.time && this.queryParams.time[1]
            }

            getReceiveApplyApi(params).then(response => {
                this.total = response.total
                this.formList = response.rows
                // console.log('22222222',this.pushReviewList)
                // this.leaseAll = this.pushReviewList.reduce((total, item) => {
                //   return total + Number(item.leaseMoney);
                // }, 0);
                // let obj = {
                //   id:null,
                //   leaseMoney: this.leaseAll,
                // }
                // this.pushReviewList.push(obj)
            })

            this.loading = false
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                keyWord: null,
                status: null,
                time: null
            }
            this.resetForm('queryForm')
            this.queryParams.pageNum = 1
            this.handleQuery()
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },

        handleDelete(row) {
            this.$modal
                .confirm('是否确认删除所选择的数据项？')
                .then(function () {
                    return deleteRedif(row.id)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess('删除成功')
                })
                .catch(() => {})
        },

        /** 减免申请按钮 */
        handleApply() {
            if (this.ids.length == 0) {
                this.$message({
                    type: 'warning',
                    message: '请选择数据'
                })
                return
            }
            this.uploadKey = Date.now()
            this.delBusinessFileIdList = []
            this.applyList = []
            this.applyListTemp = []
            // 去除 pushReviewList 数组的最后一个元素，将剩余元素赋值给 paramList
            const paramList = this.pushReviewList.slice(0, -1)
            paramList.forEach(item => {
                if (this.ids.includes(item.id)) {
                    // 创建对象的副本
                    const newItem = { ...item }
                    this.$set(newItem, 'reduceNum', newItem.num)
                    this.$set(newItem, 'reduceDays', 0)
                    this.$set(newItem, 'reduceLeaseMoney', 0)
                    this.applyList.push(newItem)
                }
            })
            //添加结尾合计
            let obj = {
                id: 0,
                reduceNum: 0,
                reduceLeaseMoney: 0
            }
            this.applyList.push(obj)
            this.applyListTemp = this.applyList
            this.showApply = true
            this.title = '减免申请'
        },

        //查看
        handleView(row) {
            this.isView = true
            this.title = '查看'
            this.uploadKey = Date.now()

            getDiscountViewList(row.id).then(async response => {
                if (response.code == 200) {
                    this.dialogAppy.decreaseFile = response.data.bmFileInfos
                    this.dialogAppy.reduceStartTime = response.data.reduceStartTime
                    this.dialogAppy.reduceEndTime = response.data.reduceEndTime
                    this.dialogAppy.remark = response.data.remark
                    this.applyList = response.data.detailList
                    this.leaseAll = this.applyList.reduce((total, item) => {
                        return total + Number(item.reduceLeaseMoney)
                    }, 0)
                    let obj = {
                        id: null,
                        reduceLeaseMoney: this.leaseAll
                    }
                    this.applyList.push(obj)
                    this.applyListTemp = this.applyList
                    await this.updateNum()
                }
            })
            this.showApply = true
        },

        //编辑
        handleAuditing(row, type) {
            this.$router.push({
                name: 'reduction-apply',
                query: {
                    id: row.id,
                    taskId: row.taskId,
                    type
                }
            }) // 跳转审核详情页面
            // this.isView = false
            // this.title = '修改'
            // this.uploadKey = Date.now()

            // getDiscountViewList(row.id).then(async response => {
            //     if (response.code == 200) {
            //         this.agreementId = response.data.agreementId
            //         this.idTemp = response.data.id
            //         this.dialogAppy.decreaseFile = response.data.bmFileInfos
            //         this.dialogAppy.reduceStartTime = response.data.reduceStartTime
            //         this.dialogAppy.reduceEndTime = response.data.reduceEndTime
            //         this.dialogAppy.remark = response.data.remark
            //         this.applyList = response.data.detailList
            //         this.leaseAll = this.applyList.reduce((total, item) => {
            //             return total + Number(item.reduceLeaseMoney)
            //         }, 0)
            //         let obj = {
            //             id: null,
            //             reduceLeaseMoney: this.leaseAll
            //         }
            //         this.applyList.push(obj)
            //         this.applyListTemp = this.applyList
            //         await this.updateNum()
            //     }
            // })
            // this.showApply = true
        },

        // 合并单元格 rowIndex=行数  columnIndex=列数
        // 这里是合并table的除表头外的第一行的第二列 + 除表头外的第二行的第二列
        // 注意列数和行数从 0 开始
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === this.pushReviewList.length - 1 && columnIndex == 1) {
                let rowspan = 2
                let colspan = 4
                return { rowspan, colspan }
            }
            // 解决偏移的重要代码
            // 重点在 else if 判断必须加因为合并单元格数据会出现偏移、
            // 否则如果是 第二行 的 第二列 那么隐藏原有第二行 的 第二列的数据使他隐藏
            else if (rowIndex === this.pushReviewList.length - 1 && columnIndex < 4) {
                return {
                    rowspan: 0,
                    colspan: 0
                }
            }
        },

        //减免费用申请弹窗合并
        objectSpanMethodApply({ row, column, rowIndex, columnIndex }) {
            if (rowIndex === this.applyList.length - 1 && columnIndex == 0) {
                let rowspan = 1
                let colspan = 4
                return { rowspan, colspan }
            }
            // 解决偏移的重要代码
            else if (rowIndex === this.applyList.length - 1 && columnIndex < 4) {
                return {
                    rowspan: 0,
                    colspan: 0
                }
            }
        },

        isImage(file) {
            this.urlTemp = require('@/assets/file.png')
            if (this.updataIf(file)) {
                return false
            } else {
                return true
            }
        },

        // 判断文件类型,图片预览，文件下载
        updataIf(e) {
            if (e.fileName) {
                const parts = e.fileName.split('.')
                const extension = parts.pop()
                if (extension === 'png' || extension === 'jpeg' || extension === 'jpg') {
                    return false
                } else {
                    return true
                }
            } else {
                const parts = e.name.split('.')
                const extension = parts.pop()
                if (extension === 'png' || extension === 'jpeg' || extension === 'jpg') {
                    return false
                } else {
                    return true
                }
            }
        },

        //附件
        handleChangeBusinessList(file, fileList) {
            const fileListTemp = fileList.filter(item => {
                return item.uid != file.uid
            })
            const parts = file.name.split('.')
            const extension = parts.pop()
            if (fileList.length > 3) {
                this.$message.warning('最多上传3张附件')
                fileList = fileList.filter(item => {
                    return item.uid != file.uid
                })
            } else if (!(extension === 'pdf' || extension === 'png' || extension === 'jpg' || extension === 'jpeg')) {
                this.$message.warning('文件格式不正确')
                fileList = fileList.filter(item => {
                    return item.uid != file.uid
                })
            } else if (file.size > 1024 * 1024 * 10) {
                this.$message.warning('文件大小不能超过10Mb')
                fileList = fileList.filter(item => {
                    return item.uid != file.uid
                })
            } else if (file.name.length > 40) {
                this.$message.warning('文件名长度不能超过40个字符')
                fileList = fileList.filter(item => {
                    return item.uid != file.uid
                })
            } else if (fileListTemp.some(item => item.name === file.name)) {
                this.$message.warning('文件名重复')
                fileList = fileList.filter(item => {
                    return item.uid != file.uid
                })
            }
            fileList.forEach(file => {
                if (extension === 'pdf') {
                    this.urlTemp = require('../../../assets/file.png')
                }
            })
            this.dialogAppy.decreaseFile = fileList
            // 手动触发表单验证
            this.$refs.dialogAppy.validateField('decreaseFile')
        },

        handleDownload(file) {
            console.log(file)
            if (file.status === 'ready') {
                downloadFile({
                    fileName: file.name,
                    fileData: file.raw,
                    fileType: 'application/vnd.ms-excel;charset=utf-8'
                })
            } else if (file.status === 'success') {
                downloadFileData({ fileName: file.name, fileUrl: file.url })
                // downloadFileData({ fileName: file.name,fileUrl:file.url })
            }
        },

        //上传组件-图片查看
        picturePreview(file) {
            this.dialogImageUrl = file.url.replaceAll('#', '%23')
            const parts = file.name.split('.')
            const extension = parts.pop()
            if (extension === 'pdf') {
                const windowName = file.name
                window.open(file.url, windowName)
            } else {
                this.dialogVisible = true
            }
        },

        //上传组件-图片删除
        handleRemoveElectricianImgList(file, fileList) {
            let sum = 0
            this.dialogAppy.decreaseFile.forEach((item, index) => {
                if (item.uid == file.uid) {
                    sum = index
                }
            })
            this.dialogAppy.decreaseFile.splice(sum, 1)
            if (file.status == 'success') {
                this.delBusinessFileIdList.push(file.url)
            }
        },

        updateNum() {
            if (this.dialogAppy.reduceStartTime && this.dialogAppy.reduceEndTime) {
                this.num2 = this.applyList
                    .slice(0, -1)
                    .filter(item => !item.reduceStartTime || !item.reduceEndTime).length
                this.num1 = this.applyList.filter(item => item.reduceStartTime && item.reduceEndTime).length
            }
        },

        // 更新表格中所有数据的减免开始时间
        updateTableStartTime() {
            this.applyList = this.applyListTemp
            if (this.dialogAppy.reduceEndTime) {
                const pickStartTime = new Date(this.dialogAppy.reduceStartTime)
                const pickEndTime = new Date(this.dialogAppy.reduceEndTime)
                if (pickStartTime > pickEndTime) {
                    this.$modal.msgError('开始日期不能大于结束日期')
                    return
                }
                this.applyList.slice(0, -1).forEach(item => {
                    const startTime = new Date(item.reduceStartTime)
                    const endTime = new Date(item.reduceEndTime)
                    const startTimeTemp = item.reduceStartTime
                    const endTimeTemp = item.reduceEndTime

                    const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
                    if (pickStartTime <= new Date(item.startTime) && pickEndTime >= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', new Date(item.startTime))
                        this.$set(item, 'reduceEndTime', new Date(item.endTime))
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (pickStartTime >= new Date(item.startTime) && pickEndTime <= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', pickStartTime)
                        this.$set(item, 'reduceEndTime', pickEndTime)
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (
                        pickStartTime >= new Date(item.startTime) &&
                        pickEndTime >= new Date(item.endTime) &&
                        pickStartTime <= new Date(item.endTime)
                    ) {
                        this.$set(item, 'reduceStartTime', pickStartTime)
                        this.$set(item, 'reduceEndTime', new Date(item.endTime))
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (
                        pickStartTime <= new Date(item.startTime) &&
                        pickEndTime <= new Date(item.endTime) &&
                        pickEndTime >= new Date(item.startTime)
                    ) {
                        this.$set(item, 'reduceStartTime', new Date(item.startTime))
                        this.$set(item, 'reduceEndTime', pickEndTime)
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (pickStartTime >= new Date(item.startTime) && pickStartTime >= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', null)
                        this.$set(item, 'reduceEndTime', null)
                        this.$set(item, 'reduceDays', 0)
                        this.$set(item, 'reduceLeaseMoney', 0)
                    } else if (pickEndTime <= new Date(item.startTime) && pickEndTime <= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', null)
                        this.$set(item, 'reduceEndTime', null)
                        this.$set(item, 'reduceDays', 0)
                        this.$set(item, 'reduceLeaseMoney', 0)
                    }
                    this.applyList[this.applyList.length - 1].reduceLeaseMoney = this.applyList
                        .slice(0, -1)
                        .reduce((total, item) => {
                            return total + Number(item.reduceLeaseMoney)
                        }, 0)
                })
            }
            this.updateNum()
        },
        // 更新表格中所有数据的减免结束时间
        updateTableEndTime() {
            this.applyList = this.applyListTemp
            if (this.dialogAppy.reduceStartTime) {
                const pickStartTime = new Date(this.dialogAppy.reduceStartTime)
                const pickEndTime = new Date(this.dialogAppy.reduceEndTime)
                console.log('dadad', pickStartTime, pickEndTime)
                if (pickStartTime > pickEndTime) {
                    this.$modal.msgError('结束日期不能小于开始日期')
                    return
                }
                this.applyList.slice(0, -1).forEach(item => {
                    const startTime = new Date(item.reduceStartTime)
                    const endTime = new Date(item.reduceEndTime)
                    const startTimeTemp = item.reduceStartTime
                    const endTimeTemp = item.reduceEndTime

                    const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
                    if (pickStartTime <= new Date(item.startTime) && pickEndTime >= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', new Date(item.startTime))
                        this.$set(item, 'reduceEndTime', new Date(item.endTime))
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (pickStartTime >= new Date(item.startTime) && pickEndTime <= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', pickStartTime)
                        this.$set(item, 'reduceEndTime', pickEndTime)
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (
                        pickStartTime >= new Date(item.startTime) &&
                        pickEndTime >= new Date(item.endTime) &&
                        pickStartTime <= new Date(item.endTime)
                    ) {
                        this.$set(item, 'reduceStartTime', pickStartTime)
                        this.$set(item, 'reduceEndTime', new Date(item.endTime))
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (
                        pickStartTime <= new Date(item.startTime) &&
                        pickEndTime <= new Date(item.endTime) &&
                        pickEndTime >= new Date(item.startTime)
                    ) {
                        this.$set(item, 'reduceStartTime', new Date(item.startTime))
                        this.$set(item, 'reduceEndTime', pickEndTime)
                        console.log('xxxxxxsadadadsa', item.reduceEndTime, item.reduceStartTime)
                        const diffDays =
                            Math.ceil(Math.abs((item.reduceEndTime - item.reduceStartTime) / oneDay)) +
                            (item.reduceEndTime - item.reduceStartTime === 0 ? 1 : 1)
                        this.$set(item, 'reduceDays', diffDays)
                        if (item.reduceNum && item.reduceDays && item.leasePrice) {
                            this.$set(item, 'reduceLeaseMoney', item.reduceDays * item.leasePrice * item.reduceNum)
                        }
                    } else if (pickStartTime >= new Date(item.startTime) && pickStartTime >= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', null)
                        this.$set(item, 'reduceEndTime', null)
                        this.$set(item, 'reduceDays', 0)
                        this.$set(item, 'reduceLeaseMoney', 0)
                    } else if (pickEndTime <= new Date(item.startTime) && pickEndTime <= new Date(item.endTime)) {
                        this.$set(item, 'reduceStartTime', null)
                        this.$set(item, 'reduceEndTime', null)
                        this.$set(item, 'reduceDays', 0)
                        this.$set(item, 'reduceLeaseMoney', 0)
                    }
                    this.applyList[this.applyList.length - 1].reduceLeaseMoney = this.applyList
                        .slice(0, -1)
                        .reduce((total, item) => {
                            return total + Number(item.reduceLeaseMoney)
                        }, 0)
                })
            }
            this.updateNum()
        },

        //table中时间改变
        updateLeaseDaysStart(row) {
            const startTime = new Date(row.reduceStartTime)
            const startTimeTemp = row.reduceStartTime
            console.log('1111111111111', startTime)
            const endTime = new Date(row.reduceEndTime)
            const endTimeTemp = row.reduceEndTime
            let pickStartTime = new Date(row.startTime)
            let pickEndTime = null
            if (row.endTime == null) {
                pickEndTime = new Date()
            } else {
                pickEndTime = new Date(row.endTime)
            }
            // 判断减免开始时间和结束时间是否在领料日期和退料日期之间
            if (startTime < pickStartTime || startTime > pickEndTime) {
                console.log('2222222222222', startTime, pickStartTime, pickEndTime)
                this.$set(row, 'reduceStartTime', null)
                this.$set(row, 'reduceDays', 0)
                this.$set(row, 'reduceLeaseMoney', 0)
                this.$modal.msgError('请选择有效的减免开始时间！!')
            } else if (
                startTimeTemp != null &&
                endTimeTemp != null &&
                startTime.getTime() != 0 &&
                endTime.getTime() != 0 &&
                endTime.getTime() >= startTime.getTime()
            ) {
                const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
                const diffDays =
                    Math.ceil(Math.abs((endTime - startTime) / oneDay)) + (endTime - startTime === 0 ? 1 : 1)
                this.$set(row, 'reduceDays', diffDays)
                if (row.reduceNum && row.reduceDays && row.leasePrice) {
                    this.$set(row, 'reduceLeaseMoney', row.reduceDays * row.leasePrice * row.reduceNum)
                }
                // row.leaseDays = diffDays;
            } else if (endTimeTemp != null && endTime.getTime() < startTime.getTime()) {
                console.log('333333333', endTime, startTime)
                // 如果日期无效，将减免天数设为 0 或者清空
                this.$set(row, 'reduceStartTime', null)
                this.$set(row, 'reduceDays', 0)
                this.$set(row, 'reduceLeaseMoney', 0)
                this.$modal.msgError('请选择有效的减免开始时间！')
            } else {
                this.$set(row, 'reduceDays', 0)
                this.$set(row, 'reduceLeaseMoney', 0)
            }
            this.applyList[this.applyList.length - 1].reduceLeaseMoney = this.applyList
                .slice(0, -1)
                .reduce((total, item) => {
                    return total + Number(item.reduceLeaseMoney)
                }, 0)
            this.updateNum()
        },

        updateLeaseDaysEnd(row) {
            const startTime = new Date(row.reduceStartTime)
            const startTimeTemp = row.reduceStartTime
            const endTimeTemp = row.reduceEndTime
            const endTime = new Date(row.reduceEndTime)
            let pickStartTime = new Date(row.startTime)
            let pickEndTime = null
            if (row.endTime == null) {
                pickEndTime = new Date()
            } else {
                pickEndTime = new Date(row.endTime)
            }
            // 判断减免开始时间和结束时间是否在领料日期和退料日期之间
            if (endTime < pickStartTime || endTime > pickEndTime) {
                this.$set(row, 'reduceEndTime', null)
                this.$set(row, 'reduceDays', 0)
                this.$set(row, 'reduceLeaseMoney', 0)
                this.$modal.msgError('请选择有效的减免结束时间！')
            } else if (
                startTimeTemp != null &&
                endTimeTemp != null &&
                startTime.getTime() != 0 &&
                endTime.getTime() != 0 &&
                endTime.getTime() >= startTime.getTime()
            ) {
                const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
                const diffDays =
                    Math.ceil(Math.abs((endTime - startTime) / oneDay)) + (endTime - startTime === 0 ? 1 : 1)
                // const diffDays = Math.round(Math.abs((endTime - startTime) / oneDay));
                this.$set(row, 'reduceDays', diffDays)
                if (row.reduceNum && row.reduceDays && row.leasePrice) {
                    this.$set(row, 'reduceLeaseMoney', row.reduceDays * row.leasePrice * row.reduceNum)
                }
                // row.leaseDays = diffDays;
            } else if (startTimeTemp != null && endTime.getTime() < startTime.getTime()) {
                // 如果日期无效，将减免天数设为 0 或者清空
                this.$set(row, 'reduceEndTime', null)
                this.$set(row, 'reduceDays', 0)
                this.$set(row, 'reduceLeaseMoney', 0)
                this.$modal.msgError('请选择有效的减免结束时间！')
            } else {
                this.$set(row, 'reduceDays', 0)
                this.$set(row, 'reduceLeaseMoney', 0)
            }
            this.applyList[this.applyList.length - 1].reduceLeaseMoney = this.applyList
                .slice(0, -1)
                .reduce((total, item) => {
                    return total + Number(item.reduceLeaseMoney)
                }, 0)
            this.updateNum()
        },

        //table中数量改变
        updateLeaseNum(row) {
            if (row.reduceNum > row.num) {
                this.$message.error('减免数量不能大于领料数量')
            } else {
                if (row.reduceNum && row.leasePrice && row.reduceDays) {
                    this.$set(row, 'reduceLeaseMoney', row.reduceDays * row.leasePrice * row.reduceNum)
                }
                this.applyList[this.applyList.length - 1].reduceLeaseMoney = this.applyList
                    .slice(0, -1)
                    .reduce((total, item) => {
                        return total + Number(item.reduceLeaseMoney)
                    }, 0)
            }
        },

        //减免申请确认按钮
        submitForm() {
            this.$refs.dialogAppy.validate(valid => {
                if (valid) {
                    let index = this.applyList
                        .slice(0, -1)
                        .findIndex(
                            item => new Date(item.reduceEndTime).getTime() < new Date(item.reduceStartTime).getTime()
                        )
                    let index2 = this.applyList.slice(0, -1).findIndex(item => item.reduceNum > item.num)
                    let index3 = this.applyList.slice(0, -1).findIndex(item => item.reduceNum == 0)
                    let index4 = this.applyList
                        .slice(0, -1)
                        .findIndex(
                            item =>
                                isNaN(new Date(item.reduceStartTime).getTime()) ||
                                new Date(item.reduceStartTime).getTime() == 0
                        )
                    let index5 = this.applyList
                        .slice(0, -1)
                        .findIndex(
                            item =>
                                isNaN(new Date(item.reduceEndTime).getTime()) ||
                                new Date(item.reduceEndTime).getTime() == 0
                        )
                    if (index3 > -1) {
                        this.$modal.msgError('减免数量不能为0！')
                    } else if (index4 > -1) {
                        this.$modal.msgError('请先去除减免时间不符合的数据！')
                    } else if (index5 > -1) {
                        this.$modal.msgError('请先去除减免时间不符合的数据！')
                    } else if (index2 > -1) {
                        this.$modal.msgError('减免数量不能大于领料数量！')
                    } else if (index > -1) {
                        this.$modal.msgError('请先去除减免时间不符合的数据！')
                    } else {
                        const param = {
                            id: this.idTemp,
                            agreementId: this.agreementId,
                            reduceStartTime: this.dialogAppy.reduceStartTime,
                            reduceEndTime: this.dialogAppy.reduceEndTime,
                            bmFileInfos: this.dialogAppy.decreaseFile,
                            remark: this.dialogAppy.remark,
                            detailList: this.applyList.slice(0, -1)
                        }
                        console.log('xxxxxxxxxxxxxx', param.bmFileInfos)
                        editRelief(param).then(response => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess('修改成功')
                                this.confirmShow = false
                                this.getList()
                                this.showApply = false
                            }
                        })
                    }
                } else {
                    return false
                }
            })
        },

        //减免申请取消按钮
        cancel() {
            this.$refs.dialogAppy.resetFields()
            this.dialogAppy.decreaseFile = []
            this.applyList = []
            this.showApply = false
        },
        closeDiag() {
            this.cancel()
        },

        handleClean() {
            // 过滤掉不符合的数据
            this.applyList = this.applyList.filter((item, index) => {
                return index === this.applyList.length - 1 || (item.reduceStartTime && item.reduceEndTime)
            })
            // 更新符合和不符合的数据条数
            this.updateNum()
        },

        handleAdd() {
            console.log('减免申请')
            this.$router.push({ path: '/business/businessHandling/discountApply' })
        },
        handleExport() {}
    }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table__body tr.highlight-row {
    background-color: #c0e6fa;
}
::v-deep .el-table {
    table-layout: auto;
}
.uploadImg {
    padding-top: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.deviceCode {
    margin-top: 10px;
    padding-bottom: 20px;
    font-size: 18px;
}
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}

//文件上传样式
//隐藏图片上传框的css
::v-deep.disabledFbs {
    .el-upload--picture-card {
        display: none;
    }
}
::v-deep .el-upload-list__item {
    margin-bottom: 20px;
    overflow: unset !important;
}
::v-deep .el-upload-list__item-actions {
    overflow: unset !important;
}

.el-upload-list__item-thumbnail {
    height: 145px !important;
}

.picture-card-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
}

.picture-card {
    width: 100%;
    height: 100%;
    object-fit: cover;
    justify-content: center;

    // border: 1px solid  #ddd;
    // border-radius: 4px;
}

.file-name {
    width: 90%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    position: absolute;
    bottom: -35px;
    margin-top: 8px;
    text-align: center;
    font-size: 12px;
    color: #333;
    z-index: 999999;
}

.file-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 20px;
}
</style>
