<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item prop="keyWord">
                <el-input
                    v-model="queryParams.keyWord"
                    placeholder="请输入关键字"
                    clearable
                    @keyup.enter.native="handleQuery"
                    maxlength="20"
                />
            </el-form-item>

            <el-form-item>
                <el-date-picker
                    v-model="queryParams.time"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>

            <!-- <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="删除" value="0"></el-option>
          <el-option label="启用" value="1"></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" border :data="houseList" ref="multipleTable" row-key="teamId">
            <el-table-column label="序号" align="center" width="80" 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="signTime" width="150" />
            <el-table-column label="协议编号" align="center" prop="agreementCode" width="180" />
            <el-table-column label="合同编号" align="center" prop="contractCode" width="120" />
            <el-table-column label="租赁单位" align="center" prop="unitName" width="150" />
            <el-table-column label="租赁工程" align="center" prop="projectName" width="150" />
            <el-table-column label="开始日期" align="center" prop="planStartTime" width="120" />
            <!--      <el-table-column label="租赁期限(天)" align="center" prop="leaseDay" width="100"/>-->
            <el-table-column label="授权人" align="center" prop="authPerson" width="100" />
            <el-table-column label="授权人电话" align="center" prop="phone" width="120" />
            <el-table-column label="分部工程" align="center" prop="branchProIdsStr" width="150"/>
            <el-table-column label="租赁单位类型" align="center" width="100">
                <template slot-scope="scope">
                    <span v-if="scope.row.protocol == '1'">内部单位</span>
                    <span v-if="scope.row.protocol == '2'">外部单位</span>
                </template>
            </el-table-column>

            <el-table-column label="附件图片" align="center" width="150">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleAllImg(scope.row)">
                        查看
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" width="100" />
            <el-table-column label="操作" align="center" width="240" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
                    <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(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="title" :visible.sync="showHouse" width="1000px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="租赁单位" prop="unitId">
                            <treeselect
                                v-model="form.unitId"
                                :disabled="isEdits"
                                :options="uniteList"
                                :normalizer="normalizer"
                                :show-count="true"
                                style="width: 100%"
                                :disable-branch-nodes="true"
                                noChildrenText="没有数据了"
                                noOptionsText="没有数据"
                                noResultsText="没有搜索结果"
                                placeholder="请选择租赁单位"
                                @select="unitSelect"
                            />
                            <!-- <el-cascader
                v-model="unitId"
                :show-all-levels="false"
                :options="uniteList"
                :props="selectTreeProps"
                filterable
                clearable
                collapse-tags
                @change="uniteChange"
                placeholder="请选择租赁单位"
                style="width: 100%;"
                :disabled="isEdits"
              ></el-cascader> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="授权人" prop="authPerson">
                            <el-input
                                maxlength="50"
                                v-model="form.authPerson"
                                placeholder="请输入授权人"
                                :disabled="isEdits"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="租赁工程" prop="projectId">
                            <treeselect
                                v-model="form.projectId"
                                :disabled="isEdits"
                                :options="projectList"
                                :normalizer="normalizer"
                                :show-count="true"
                                style="width: 100%"
                                :disable-branch-nodes="true"
                                noChildrenText="没有数据了"
                                noOptionsText="没有数据"
                                noResultsText="没有搜索结果"
                                placeholder="请选择租赁工程"
                            />
                            <!-- <el-cascader
                v-model="projectId"
                :show-all-levels="false"
                :options="projectList"
                :props="selectTreeProps"
                filterable
                clearable
                collapse-tags
                @change="projectChange"
                placeholder="请选择租赁工程"
                style="width: 100%;"
                :disabled="isEdits"
              ></el-cascader> -->
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="phone">
                            <el-input
                                v-model="form.phone"
                                placeholder="请输入联系电话"
                                maxlength="11"
                                :disabled="isEdits"
                                onkeyup="this.value = this.value.replace(/[^\d]/g,'');"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="合同编号" prop="contractCode">
                            <el-input
                                maxlength="50"
                                v-model="form.contractCode"
                                placeholder="请输入合同编号"
                                :disabled="isEdits"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开始日期" prop="planStartTime">
                            <el-date-picker
                                style="width: 100%"
                                v-model="form.planStartTime"
                                value-format="yyyy-MM-dd"
                                type="date"
                                placeholder="请选择开始日期"
                                :disabled="isEdits"
                            ></el-date-picker>
                        </el-form-item>
                    </el-col>

                    <!--          <el-col :span="12">
            <el-form-item label="租赁期限(天)" prop="leaseDay">
              <el-input-number
                v-model="form.leaseDay"
                placeholder="请输入租赁期限(天)"
                controls-position="right"
                :min="0"
                :max="9999"
                style="width: 100%"
                :disabled="isEdits"
              />
            </el-form-item>
          </el-col>-->
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="租赁单位类型" prop="protocol">
                            <el-select
                                style="width: 100%"
                                v-model="form.protocol"
                                placeholder="请选择租赁单位类型"
                                :disabled="isEdits"
                            >
                                <el-option label="内部单位" value="1"></el-option>
                                <el-option label="外部单位" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="分部工程" prop="remark">
                            <el-select
                                clearable
                                multiple
                                filterable
                                style="width: 100%"
                                placeholder="请选择分部工程"
                                v-model="form.branchProIds"
                            >
                                <el-option
                                    :key="dict.value"
                                    :label="dict.label"
                                    :value="dict.value * 1"
                                    v-for="dict in dict.type.branch_project"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="附件">
                            <el-upload
                                action="#"
                                :file-list="businessLicenseListTemp"
                                :show-file-list="true"
                                :auto-upload="false"
                                :key="uploadKey"
                                list-type="picture-card"
                                accept=".png, .jpg, .jpeg, .pdf"
                                :on-change="handleChangeBusinessList"
                                :class="{ disabled: uploadDisabled }"
                                :on-preview="picturePreview"
                                :on-remove="handleRemoveElectricianImgList"
                                :disabled="isEdits"
                            >
                                <!-- 文件格式下载，图片格式预览 -->
                                <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-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input
                                v-model="form.remark"
                                type="textarea"
                                placeholder="请输入备注"
                                maxlength="100"
                                :disabled="isEdits"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" v-if="showConfirmButton">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 查看 -->
        <el-dialog :title="title" :visible.sync="showSee" width="1000px" append-to-body>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="租赁单位">
                    {{ form.unitName }}
                </el-descriptions-item>
                <el-descriptions-item label="授权人">
                    {{ form.authPerson }}
                </el-descriptions-item>
                <el-descriptions-item label="租赁工程">
                    {{ form.projectName }}
                </el-descriptions-item>
                <el-descriptions-item label="联系电话">
                    {{ form.phone }}
                </el-descriptions-item>
                <el-descriptions-item label="合同编号">
                    {{ form.contractCode }}
                </el-descriptions-item>
                <!--        <el-descriptions-item label="租赁期限(天)">
          {{ form.leaseDay }}
        </el-descriptions-item>-->
                <el-descriptions-item label="开始日期">
                    {{ form.planStartTime }}
                </el-descriptions-item>
                <el-descriptions-item label="租赁单位类型">
                    {{ form.protocol === '1' ? '内部单位' : '外部单位' }}
                </el-descriptions-item>
                <el-descriptions-item label="分部工程">
                    {{ form.branchProIdsStr }}
                </el-descriptions-item>
                <el-descriptions-item label="备注">
                    {{ form.remark }}
                </el-descriptions-item>
            </el-descriptions>

            <el-descriptions :column="1" border style="width: 100%">
                <el-descriptions-item label="附件">
                    <el-upload
                        class="upload-demo"
                        style="width: 197px"
                        action="#"
                        :file-list="businessLicenseListTemp"
                        :show-file-list="true"
                        :auto-upload="false"
                        :key="uploadKey"
                        list-type="picture-card"
                        accept=".png, .jpg, .jpeg, .pdf"
                        :on-change="handleChangeBusinessList"
                        :class="{ disabled: true }"
                        :on-preview="picturePreview"
                        :on-remove="handleRemoveElectricianImgList"
                        :disabled="isEdits"
                    >
                        <!-- 文件格式下载，图片格式预览 -->
                        <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-descriptions-item>
            </el-descriptions>

            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 查看全部图片的弹窗 -->
        <el-dialog :title="title" :visible.sync="showAllImg" width="800px" append-to-body>
            <el-form ref="form" label-width="120px">
                <el-form-item label="附件">
                    <el-upload
                        class="upload-demo"
                        action="#"
                        :file-list="businessLicenseListTemp"
                        :show-file-list="true"
                        :auto-upload="false"
                        :key="uploadKey"
                        list-type="picture-card"
                        accept=".png, .jpg, .jpeg, .pdf"
                        :on-change="handleChangeBusinessList"
                        :class="{ disabled: true }"
                        :on-preview="picturePreview"
                        :on-remove="handleRemoveElectricianImgList"
                        :disabled="isEdits"
                    >
                        <!-- 文件格式下载，图片格式预览 -->
                        <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>
                        </div>
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" v-if="showConfirmButton">确 定</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 {
    getListAgreement,
    getAgreementDetail,
    editAgreement,
    addAgreement,
    delAgreement,
    deleteFile,
    getUnitList,
    getProjectList
} from '@/api/lease/protocol'
import { imgUpLoadThree, fileUpLoad } from '@/api/system/upload'
import { downloadFile, downloadFileData } from '@/utils/download'
import { getToken } from '@/utils/auth'
import { Base64 } from 'js-base64'
import { forEach } from 'jszip'
import { listUser } from '@/api/system/user'
import { getListProject, getListUnite } from '@/api/lease/apply'

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
    name: 'Protocol',
    dicts: ['branch_project'],
    components: { Treeselect },
    data() {
        return {
            uploadKey: Date.now(),
            // 遮罩层
            loading: false,
            loadingTwo: false,
            // 是否显示项目部Id
            showName: false,
            // 是否显示施工预警信息
            showWarn: false,
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 日期范围
            dateRange: [],
            // 显示搜索条件
            showSearch: true,
            showHouse: false,
            showSee: false,
            showAllImg: false,
            // 总条数
            total: 0,
            totalTwo: 0,
            // 租赁单位数据
            unitList: [],
            //租赁单位
            uniteList: [],
            selectTreeProps: {
                children: 'children',
                label: 'name',
                // multiple: false,
                value: 'id'
                // multiple: true,
            },
            unitId: null,
            projectId: null,
            maForm: {
                unitId: undefined,
                projectId: undefined
            },
            // 工程数据
            projectList: [],
            // 施工记录表格数据
            houseList: [],
            maxLength: 100, //已选列表上限，防止数据过多请求报错
            keeperDataRange: [],
            // 班组人员表格数据
            teamList: [],
            teamTempList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            showConfirmButton: true,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                keyWord: undefined,
                status: undefined,
                time: null //申请时间
            },
            fileList: [],
            businessLicenseFileList: [],
            businessLicenseListTemp: [],
            delBusinessFileIdList: [],
            base64Data: undefined,
            //图片查看弹窗
            dialogImageUrl: '',
            dialogVisible: false,
            // 表单参数
            form: {
                unitId: null,
                projectId: null,
                protocol: '1',
                branchProIds: [],
                planStartTime: ''
            },
            // 表单校验
            rules: {
                unitId: [
                    {
                        required: true,
                        message: '请选择租赁单位',
                        trigger: 'blur'
                    }
                ],
                projectId: [
                    {
                        required: true,
                        message: '请选择租赁工程',
                        trigger: 'blur'
                    }
                ],
                contractCode: [
                    {
                        required: false, //是否分包商(是：合同编号必填)
                        message: '请填写合同编号',
                        trigger: 'change'
                    }
                ],
                authPerson: [
                    {
                        required: true,
                        message: '授权人不能为空',
                        trigger: 'blur'
                    }
                ],
                phone: [
                    { required: true, message: '联系电话不能为空', trigger: 'blur' },
                    {
                        required: false,
                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                        message: '请输入正确的联系电话',
                        trigger: 'blur'
                    }
                ],
                protocol: [
                    {
                        required: true,
                        message: '请选择租赁类型',
                        trigger: 'change'
                    }
                ],
            },

            //上传
            upload: {
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/file/upload'
            },

            isEdit: false,
            isEdits: false
        }
    },
    computed: {
        //图片上传1张后，隐藏上传框
        uploadDisabled() {
            return this.businessLicenseListTemp.length > 9
        }
    },
    created() {
        this.getList()
        this.getUnitList()
        this.getProjectList()
    },
    methods: {
        //提交时循环fileList 获取raw文件
        async getFileData() {
            const fileTwo = []
            this.businessLicenseListTemp.forEach(item => {
                if (item?.hasOwnProperty('raw')) {
                    fileTwo.push(item.raw)
                }
            })
            return { fileTwo }
        },

        // 图片上传
        async imgUpLoadTwoAll(param) {
            param.type = 'ma'
            imgUpLoadThree(param)
                .then(res => {
                    if (res.code == 200) {
                        let obj = { name: res.data.name, url: res.data.url }
                        console.log('obj', obj)
                        this.businessLicenseFileList.push(obj)
                    } else {
                        // this.$msgError(res.msg)
                        this.$modal.msgError(res.msg)
                    }
                })
                .catch(error => {
                    // this.$msgError(error)
                    this.$modal.msgError(error)
                })
        },

        //上传组件-图片查看
        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.businessLicenseListTemp.forEach((item, index) => {
                if (item.uid == file.uid) {
                    sum = index
                }
            })
            this.businessLicenseListTemp.splice(sum, 1)
            if (file.status == 'success') {
                this.delBusinessFileIdList.push(file.url)
            }
            console.log('delBusinessFileIdList', this.delBusinessFileIdList)
        },
        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
                }
            }
        },
        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 })
            }
        },
        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 > 10) {
                this.$message.warning('最多上传10张附件')
                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.businessLicenseListTemp = fileList
        },

        //查询列表
        getList() {
            this.loading = true
            const params = {
                keyWord: this.queryParams.keyWord,
                startTime: this.queryParams.time && this.queryParams.time[0],
                endTime: this.queryParams.time && this.queryParams.time[1],
                pageSize: this.queryParams.pageSize,
                pageNum: this.queryParams.pageNum,
                status: this.queryParams.status
            }
            getListAgreement(this.addDateRange(params)).then(response => {
                this.houseList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        /** 转换菜单数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children
            }
        },
        //获取单位类型 ,getUnitList, getProjectList
        getUnitList() {
            getListUnite({ projectId: null }).then(response => {
                this.uniteList = response.data
            })
        },
        getProjectList() {
            getListProject({ unitId: null }).then(response => {
                this.projectList = response.data
            })
        },
        unitSelect(e) {
            console.log(e)
            if (e.typeKey == 'fbs') {
                this.rules['contractCode'][0].required = true
            } else {
                this.rules['contractCode'][0].required = false
            }
        },
        uniteChange(val) {
            if (val && val.length > 0) {
                this.maForm.unitId = this.unitId[this.unitId.length - 1]
            } else if (val && val.length == 0) {
                this.maForm.unitId = ''
            }
        },

        projectChange(val) {
            if (val && val.length > 0) {
                this.maForm.projectId = this.projectId[this.projectId.length - 1]
            } else if (val && val.length == 0) {
                this.maForm.projectId = ''
            }
        },

        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.uploadKey = Date.now()
            this.delBusinessFileIdList = []
            this.businessLicenseListTemp = []
            this.businessLicenseFileList = []
            this.showHouse = true
            this.showConfirmButton = true
            this.showSee = false
            this.isEdit = false
            this.isEdits = false
            this.title = '新增'

            const today = new Date()
            const yyyy = today.getFullYear()
            const mm = String(today.getMonth() + 1).padStart(2, '0')
            const dd = String(today.getDate()).padStart(2, '0')
            this.form.planStartTime = `${yyyy}-${mm}-${dd}`
        },

        handleUpdate(row) {
            this.reset()
            this.uploadKey = Date.now()
            this.delBusinessFileIdList = []
            this.businessLicenseListTemp = []
            this.businessLicenseFileList = []
            var id = row.agreementId

            getAgreementDetail(id).then(response => {
                this.form = response.data
                this.maForm.unitId = response.data.unitId
                this.maForm.projectId = response.data.projectId
                this.unitId = this.treeParentsById(this.uniteList, this.maForm.unitId)
                this.projectId = this.treeParentsById(this.projectList, this.maForm.projectId)
                console.log("vvvvvvvvvvvvvvvvv",this.form)
                var taskId = this.form.taskId
                console.log(taskId)
                if (taskId) {
                    this.isEdit = true
                } else {
                    this.isEdit = false
                }
                this.isEdits = false
                console.log(this.isEdit)

                if (response.data.bmFileInfos != null) {
                    this.businessLicenseListTemp = response.data.bmFileInfos
                    this.businessLicenseListTemp.forEach(item => {
                        if (item.name.includes('/')) {
                            const fileNameWithTimestamp = item.name.split('/').pop()
                            const parts = fileNameWithTimestamp.split('_')
                            const fileType = item.name.split('.').pop()
                            const mainFileName = parts.slice(0, parts.length - 1).join('_')
                            item.name = mainFileName + '.' + fileType
                        }
                    })
                } else {
                    this.businessLicenseListTemp = []
                }
                this.showHouse = true
                this.showConfirmButton = true
                this.showSee = false
                this.title = '修改'
            })
        },

        handleAllImg(row) {
            this.reset()
            this.uploadKey = Date.now()
            this.delBusinessFileIdList = []
            this.businessLicenseListTemp = []
            this.businessLicenseFileList = []

            var id = row.agreementId
            getAgreementDetail(id).then(response => {
                if (response.data.bmFileInfos != null) {
                    this.businessLicenseListTemp = response.data.bmFileInfos
                    this.businessLicenseListTemp.forEach(item => {
                        if (item.name.includes('/')) {
                            const fileNameWithTimestamp = item.name.split('/').pop()
                            const parts = fileNameWithTimestamp.split('_')
                            const fileType = item.name.split('.').pop()
                            const mainFileName = parts.slice(0, parts.length - 1).join('_')
                            item.name = mainFileName + '.' + fileType
                        }
                    })
                } else {
                    this.businessLicenseListTemp = []
                }
                this.isEdits = true

                this.showHouse = false
                this.showConfirmButton = false
                this.showAllImg = true
                this.title = '查看'
            })
        },

        handleView(row) {
            this.reset()
            this.uploadKey = Date.now()
            this.delBusinessFileIdList = []
            this.businessLicenseListTemp = []
            this.businessLicenseFileList = []

            var id = row.agreementId
            getAgreementDetail(id).then(response => {
                this.form = response.data
                this.maForm.unitId = response.data.unitId
                this.maForm.projectId = response.data.projectId

                this.unitId = this.treeParentsById(this.uniteList, this.maForm.unitId)
                this.projectId = this.treeParentsById(this.projectList, this.maForm.projectId)
                if (response.data.bmFileInfos != null) {
                    this.businessLicenseListTemp = response.data.bmFileInfos
                    this.businessLicenseListTemp.forEach(item => {
                        if (item.name.includes('/')) {
                            const fileNameWithTimestamp = item.name.split('/').pop()
                            const parts = fileNameWithTimestamp.split('_')
                            const fileType = item.name.split('.').pop()
                            const mainFileName = parts.slice(0, parts.length - 1).join('_')
                            item.name = mainFileName + '.' + fileType
                        }
                    })
                } else {
                    this.businessLicenseListTemp = []
                }
                this.isEdit = true
                this.isEdits = true
                this.showHouse = false
                this.showSee = true
                this.showConfirmButton = false
                this.title = '查看'
            })
        },

        // 表单重置
        reset() {
            this.form = {
                unitId: null,
                projectId: null,
                authPerson: '',
                phone: '',
                contractCode: '',
                planStartTime: '',
                protocol: '1',
                remark: '',
                branchProIds: []
            }
            this.unitId = null
            this.projectId = null
            this.maForm = {
                unitId: undefined,
                projectId: undefined
            }
            this.resetForm('form')
        },

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

        //** 提交按钮 */
        submitForm() {
            // this.form.unitId = this.maForm.unitId;
            // this.form.projectId = this.maForm.projectId;

            this.$refs['form'].validate(async valid => {
                console.log('this.maForm', this.maForm)
                console.log('this.form', this.form)
                // this.form.projectId = this.form.proId;
                if (valid) {
                    if (this.form.agreementId != undefined) {
                        this.form.projectName = null
                        this.form.unitName = null
                        // this.form.fileName =null;
                        const reqData = new FormData()
                        if (this.businessLicenseListTemp.length != 0) {
                             console.log("xxxxxxxxxxxxxx",this.form)
                            await this.getImaUploadEdit(), await this.editAgreementTemp(this.form)
                            await this.deleteFile()
                        } else {
                            console.log("xxxxxxxxxxxxxx",this.form)
                            await this.editAgreementTemp(this.form)
                            await this.deleteFile()
                        }
                    } else {
                        console.log(1)
                        if (this.businessLicenseListTemp.length != 0) {
                            // console.log(2)
                            await this.getImaUpload(), await this.addAgreementTemp(this.form)
                        } else {
                            // console.log(3)
                            await this.addAgreementTemp(this.form)
                        }
                    }
                }
            })
            this.uploadKey = Date.now()
        },

        async getImaUpload() {
            this.businessLicenseFileList = []
            const reqData = new FormData()
            const { fileTwo } = await this.getFileData()
            let res = await imgUpLoadThree(fileTwo)
            console.log('res', res)
            if (res.code === 200) {
                res.data.forEach(item => {
                    let objTwo = { name: item.name, url: item.url, taskType: 10 }
                    this.businessLicenseFileList.push(objTwo)
                })
            } else {
                this.$modal.msgError(res.msg)
            }
        },

        async getImaUploadEdit() {
            this.businessLicenseFileList = []
            const { fileTwo } = await this.getFileData()
            console.log('fileTwo', fileTwo)
            this.businessLicenseListTemp.forEach(item => {
                if (item.status == 'success') {
                    let objThree = { name: item.name, url: item.url, taskType: 10 }
                    this.businessLicenseFileList.push(objThree)
                }
            })
            if (fileTwo.length != 0) {
                let res = await imgUpLoadThree(fileTwo)
                if (res.code === 200) {
                    res.data.forEach(item => {
                        let objTwo = { name: item.name, url: item.url, taskType: 10 }
                        this.businessLicenseFileList.push(objTwo)
                    })
                } else {
                    this.$modal.msgError(res.msg)
                }
            }
        },

        async addAgreementTemp(form) {
            this.form.bmFileInfos = this.businessLicenseFileList
            addAgreement(form).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.showHouse = false
                this.getList()
                this.delBusinessFileIdList = []
                this.businessLicenseListTemp = []
                this.businessLicenseFileList = []
            })
        },

        async editAgreementTemp(form) {
            this.form.bmFileInfos = this.businessLicenseFileList
            editAgreement(form).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.showHouse = false
                this.getList()
                this.delBusinessFileIdList = []
                this.businessLicenseListTemp = []
                this.businessLicenseFileList = []
            })
        },

        async deleteFile() {
            if (this.delBusinessFileIdList.length > 0) {
                this.delBusinessFileIdList.forEach(async item => {
                    const urlcode = Base64.encode(item)
                    const urlen = encodeURIComponent(urlcode)
                    await deleteFile(urlen)
                })
            }
        },

        async convertToBase64(data) {
            const url = data

            try {
                const response = await fetch(url)
                if (!response.ok) {
                    throw new Error('网络响应不正常')
                }
                const blob = await response.blob()
                const reader = new FileReader()

                reader.onloadend = () => {
                    this.base64Data = reader.result // 获取 Base64 数据并存储
                }

                reader.readAsDataURL(blob) // 将 Blob 读取为 Data URL
            } catch (error) {
                console.error('获取文件失败:', error)
            }
        },

        // 取消按钮
        cancel() {
            this.showHouse = false
            this.showSee = false
            this.showAllImg = false
            this.delBusinessFileIdList = []
            this.businessLicenseListTemp = []
            this.businessLicenseFileList = []
            this.uploadKey = Date.now()
            this.reset()
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            var id = row.agreementId
            this.$modal
                .confirm('是否确认删除数据项？')
                .then(function () {
                    return delAgreement(id)
                })
                .then(() => {
                    this.$modal.msgSuccess('删除成功')
                    this.getList()
                })
                .catch(() => {})
        },

        handleExport() {
          const formatTime = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}${month}${day}_${hours}${minutes}${seconds}`;
          };

          const currentTime = formatTime(new Date());
            this.download(
                '/material/bm_agreement_info/export',
                {
                    ...this.queryParams
                },
                `协议管理 _${currentTime}.xlsx`
            )
        },

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

        //单位，工程树结构数据获取父
        treeParentsById(list, id) {
            for (let i in list) {
                if (list[i].id == id) {
                    //查询到就返回该数组对象的value
                    return [list[i].id]
                }
                if (list[i].children) {
                    let node = this.treeParentsById(list[i].children, id)
                    if (node !== undefined) {
                        //查询到把父节把父节点加到数组前面
                        node.unshift(list[i].id)
                        return node
                    }
                }
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.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.disabled {
    .el-upload--picture-card {
        display: none;
    }
}

// ::v-deep .el-upload-list--picture-card {
//   display: flex;
//   flex-wrap: wrap;
// }

::v-deep .el-upload-list__item {
    margin-bottom: 20px;
    overflow: revert;
}

::v-deep .el-upload-list__item-actions {
    overflow: hidden;
}
.el-upload--picture-card {
    display: flex;
    flex-wrap: wrap;
}

.upload-demo {
    display: flex;
    flex-wrap: wrap;
}

.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>
