<template>
    <el-dialog :title="'批量维护信息点 - ' + mess.name" width="65%" top="10vh" :visible.sync="batchDialog" class="batchContainer">
        <el-steps :active="active" simple align-center>
            <el-step @click.native="active = 0" title="填写需维护的信息点" />
            <el-step @click.native="active = 1" title="选择批量维护的对象实例" />
        </el-steps>
        <hr />
        <div v-show="active === 0" style="height: 555px; overflow: auto">
            <section>
                <p class="text-message">维护多选枚举类型信息点</p>
                <span class="small">请选择需维护的信息点</span>
                <el-form ref="ruleForm" :model="formData" :inline="true" :label-position="'left'">
                    <div
                        v-for="item in tableHeader"
                        v-show="
                            item.dataType === 'MENUM' || (item.dataType == 'ENUM' && item.multiple) || (item.dataType == 'BOOLEAN' && item.multiple)
                        "
                        :key="item.code"
                        style="width: 50%; display: inline-block"
                    >
                        <el-form-item
                            :label="item.name"
                            :prop="item.code"
                            v-if="
                                item.dataType === 'MENUM' ||
                                (item.dataType == 'ENUM' && item.multiple) ||
                                (item.dataType == 'BOOLEAN' && item.multiple)
                            "
                            :class="{
                                FloorTypeSelect:
                                    item.dataType == 'MENUM' ||
                                    (item.dataType == 'ENUM' && item.multiple) ||
                                    (item.dataType == 'BOOLEAN' && item.multiple),
                            }"
                        >
                            <el-select v-model="formData[item.path]" collapse-tags multiple placeholder="请选择">
                                <el-option
                                    v-for="opt in formatDataSource(item.dataSource)"
                                    :key="`${item.code}-${opt.Code}`"
                                    :label="opt.Name"
                                    :value="opt.Code"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </el-form>
            </section>
            <!-- 维护有多个值的信息 -->
            <section>
                <p class="text-message">维护有多个值的信息点</p>
                <span class="small">选择值的更新方式</span>
                <el-radio-group v-model="radio">
                    <el-radio :label="1">以增量方式维护</el-radio>
                    <el-radio :label="2">以覆盖方式维护</el-radio>
                </el-radio-group>
                <div style="margin: 15px"></div>
                <div class="checkbox">
                    <p v-for="item in newEnclosure" :key="item.code">
                        <el-checkbox v-model="form[item.path]"> </el-checkbox>
                        <span style="cursor: pointer">{{ item.name }}</span>
                        <el-button @click="multiple(item.path)" type="text">请选择</el-button>
                        <span class="text-color" v-for="i in item.value" :key="i.key">{{ i.name | filterImgName }}</span>
                    </p>
                </div>
            </section>
        </div>
        <div v-show="active === 1" class="all-message">
            <el-row class="filters">
                <el-col :span="7" style="width: 268px">
                    <el-input
                        placeholder="输入设备名称、设备本地编码、数字化交付编码进行查询"
                        v-model="keycode"
                        @clear="inputMsg"
                        clearable
                        @keyup.enter.native="inputMsg"
                    >
                        <i slot="suffix" class="el-input__icon el-icon-search" @click="inputMsg"></i>
                    </el-input>
                </el-col>
                <el-col :span="8.5" style="padding: 0 0">
                    <floor-cascader ref="buildFloor" @change="changeFloor" style="margin-left: 15px"></floor-cascader>
                </el-col>
            </el-row>
            <el-table
                ref="multipleTable"
                :data="tableData"
                height="460"
                tooltip-effect="dark"
                style="width: 100%; margin-bottom: 10px"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column label="设备本地名称">
                    <template slot-scope="scope">{{ scope.row.localName }}</template>
                </el-table-column>
                <el-table-column prop="localId" label="设备本地编码" />
                <el-table-column :label="`数字化交付编码`" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <div>{{ scope.row.infos ? (scope.row.infos.digitalDeliveryID ? scope.row.infos.digitalDeliveryID : "") : "" }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="build" label="所属建筑楼层" show-overflow-tooltip />
            </el-table>
            <my-pagination @change="getAllData" :page="page"></my-pagination>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button v-show="active === 0" class="next-step" @click="next">下一步 </el-button>
            <el-button v-show="active === 1" @click="active = 0" style="margin-right: 10px">上 一 步 </el-button>
            <el-button v-show="active === 1" type="primary" :loading="loading" @click="maintenanceSelect">维护已选 </el-button>
        </div>
    </el-dialog>
</template>

<script>
import myPagination from "@/components/ledger/lib/myPagination";
import floorCascader from "@/components/ledger/lib/floorCascader";
import { queryUpdate, updateEquip } from "@/api/scan/request";
import { queryEquip } from "@/api/object/equip";
import tools from "@/utils/buildfloor/tools";
import scanTools from "@/utils/scan/tools";

export default {
    name: "batchDialog",
    props: ["mess", "tableHeader", "information", "newEnclosure"],
    components: { myPagination, floorCascader },
    data() {
        return {
            formData: {},
            form: {},
            batchDialog: false, //dialog
            loading: false, //批量维护加载状态
            active: 0, //进度条
            radio: 1, //1增加，2覆盖
            checkedFile: [], //多项
            multipleSelection: [], //checkbox选择的对象数组
            allObject: [], //设备数据
            deviceList: [], //过滤全选数据
            keycode: "", // 设备检索关键字
            Buildfloor: ["all"], //建筑楼层
            page: {
                size: 100,
                sizes: [100, 200, 500, 1000],
                total: 0,
                currentPage: 1,
            },
            videoModel: {
                archive: false,
                checkReport: false,
                drawing: false,
                installDrawing: false,
                insuranceFile: false,
                installPic: false,
                nameplate: false,
                pic: false,
            },
        };
    },
    watch: {
        information() {
            return this.information;
        },
        newEnclosure: {
            immediate: true,
            handler(val) {
                this.newEnclosure = val;
            },
        },
        batchDialog: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.active = 0;
                    this.page.pageSize = 1;
                    this.keycode = "";
                    this.Buildfloor = ["all"];
                    this.$nextTick(() => {
                        this.$refs.buildFloor && this.$refs.buildFloor.setValue(["all"]);
                    });
                    this.getEquipData();
                }
            },
        },
    },
    created() {
        this.$forceUpdate();
    },
    computed: {
        tableData() {
            this.allObject.map((item) => {
                let build = "";
                if (item.building && item.floor) {
                    build = item.building.localName + " - " + item.floor.localName;
                } else if (item.building) {
                    build = item.building.localName;
                } else if (item.floor) {
                    build = item.floor.localName;
                } else {
                    build = "-";
                }
                item.build = build;
                return item;
            });
            return this.allObject;
        },
    },
    filters: {
        filterImgName(value) {
            if (value && value.length > 16) {
                return value.substring(0, 12) + "...";
            } else {
                return value;
            }
        },
        filterImgNames(value) {
            if (value && value.length > 16) {
                return value.substring(0, 16) + "...";
            } else {
                return value;
            }
        },
    },
    methods: {
        /**
         * 格式化下拉数据
         */
        formatDataSource(dataSource) {
            return dataSource ? scanTools.formatDataSource(dataSource) : [];
        },
        next() {
            //下一步按钮
            let flag = false; // formData的值是否维护
            Object.keys(this.formData).forEach((key) => {
                if (this.formData[key].length) {
                    flag = true;
                }
            });
            if (!flag && !Object.keys(this.form).length) {
                this.$message({
                    message: "请维护信息后再操作！",
                    type: "warning",
                });
                return false;
            }
            this.active++;
        },
        /**
         * 获取设备信息
         */
        getEquipData() {
            if (!!this.mess.deviceId) {
                //   查询step2
                let params = {
                    cascade: [
                        {
                            name: "property",
                        },
                        {
                            Name: "building",
                            Projection: ["localName", "name", "id"],
                        },
                        {
                            Name: "floor",
                            Projection: ["localName", "name", "id"],
                        },
                    ],
                    filters: `classCode='${this.mess.deviceId}'`,
                    pageSize: this.page.size,
                    orders: "createTime desc, id desc",
                    pageNumber: this.page.currentPage,
                    projection: ["buildingId", "floorId", "classCode", "localName", "localID", "id", "bimId"],
                };
                if (this.Buildfloor[0] == "noKnow") {
                    params.filters += `;buildingId isNull`;
                } else if (this.Buildfloor[0] && this.Buildfloor[0] != "all") {
                    params.filters += `;buildingId='${this.Buildfloor[0]}'`;
                }
                if (this.Buildfloor[1] == "noKnow") {
                    params.filters += `;floorId isNull`;
                } else if (this.Buildfloor[1] && this.Buildfloor[1] != "all") {
                    params.filters += `;floorId='${this.Buildfloor[1]}'`;
                }
                if (this.keycode != "") {
                    params.filters += `;localName contain '${this.keycode}' or localId contain '${this.keycode}' or infos.digitalDeliveryID contain '${this.keycode}'`;
                }
                queryEquip(params, (res) => {
                    this.multipleSelection = [];
                    this.allObject = res.content;
                    this.page.total = res.total;
                });
            }
        },
        /**
         * 检索关键字
         */
        inputMsg() {
            this.page.pageNumber = 1;
            this.getEquipData();
        },
        /**
         * 切换建筑楼层
         */
        changeFloor(value) {
            this.Buildfloor = value;
            this.page.pageNumber = 1;
            this.getEquipData();
        },
        maintenanceSelect() {
            //维护已选
            if (!this.multipleSelection.length) {
                this.$message({
                    message: "还没有选择实例哦",
                    type: "warning",
                });
                return false;
            }

            let arr = [];
            this.multipleSelection.forEach((item) => {
                let id = item.id;
                arr.push({ id });
            });

            // let single = {};
            let param = {};
            this.newEnclosure.forEach(({ path, value }) => (param[path] = value));
            let newValuable = [];
            this.newEnclosure.filter((i) => this.form[i.path] && i.value).forEach(({ code, value }) => (newValuable[code] = value));

            console.log(newValuable, "多选信息");

            if (this.radio === 1) {
                //组装数据，根据是覆盖该是增量，1是增量
                //    1:单选数据
                let formData = tools.formatData(this.formData);
                let arr1 = this.deepCopy(arr).map((item) => ({
                    ...item,
                    ...formData,
                }));
                // 附件数据
                let arr2 = this.deepCopy(arr).map((item) => ({
                    ...item,
                    ...newValuable,
                }));
                this.upDataDevice(1, arr1, arr2);
            } else if (this.radio === 2) {
                let param = {};
                this.newEnclosure.forEach(({ path, value }) => (param[path] = value));
                let pa = Object.assign(param, this.formData);
                pa = tools.formatData(pa);
                let arr3 = this.deepCopy(arr).map((item) => ({
                    ...item,
                    ...pa,
                }));
                this.upDataDevice(2, arr3);
            } else {
                this.closeDialog();
            }
        },
        upDataDevice(type, data1, data2) {
            this.loading = true;
            let param = { content: data1 };
            let param1 = { content: data2 };
            if (type === 1) {
                //增量
                let filterParam = this.filterCheck(param, "sole");
                let filterParam1 = this.filterCheck(param1, "multiple");
                if (filterParam) {
                    updateEquip(param, (res) => {
                        if (res.result === "success") {
                            this.loading = false;
                            this.$emit("upDataDevice");
                        } else {
                            this.$message.error(res.message);
                        }
                        this.closeDialog();
                    });
                }
                if (filterParam1) {
                    param1.content.map((i) => {
                        i.equipId = i.id;
                        delete i.id;
                        return i;
                    });
                    setTimeout(() => {
                        queryUpdate(param1, (res) => {
                            if (res.result === "success") {
                                this.loading = false;
                                this.$emit("upDataDevice");
                            } else {
                                this.$message.error(res.message);
                            }
                            this.closeDialog();
                        });
                    });
                }
                if (!filterParam && !filterParam1) {
                    this.loading = false;
                    this.closeDialog();
                }
            } else if (type === 2) {
                //覆盖
                let filterParams = this.filterCheck(param, "sole");
                console.log("filterParams", filterParams);
                console.log(param);
                if (filterParams) {
                    updateEquip(param, (res) => {
                        if (res.result === "success") {
                            this.loading = false;
                            this.$emit("upDataDevice");
                        } else {
                            this.$message.error(res.message);
                        }
                        this.closeDialog();
                    });
                } else {
                    this.loading = false;
                    this.closeDialog();
                }
            }
        },
        filterCheck(arr, type) {
            if (type === "sole") {
                for (let i of arr.content) {
                    for (let j in i.infos) {
                        if (Array.isArray(i.infos[j]) && i.infos[j].length < 1) {
                            delete i.infos[j];
                        }
                    }
                    return Object.keys(i.infos).length;
                }
            } else if (type === "multiple") {
                let nArr = [];
                arr.content.forEach((i) => {
                    let { id, ...value } = i;
                    nArr.push({ infos: value });
                });
                for (let j of nArr) {
                    return Object.keys(j.infos).length;
                }
            }
        },
        closeDialog() {
            //关闭弹窗，返回初始状态
            this.batchDialog = false;
            this.clearData();
        },
        clearData() {
            this.active = 0;
            this.radio = 1; //返回到默认增量
            // 清空formData数据
            this.formData = {};
            //清空附件信息
            for (let i in this.form) {
                this.form[i] = false;
            }
            this.newEnclosure.map((i) => {
                this.$set(i, "value", []);
            });
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        getAllData() {
            this.getEquipData();
        },
        multiple(val) {
            this.$emit("multiples", val);
        },

        deepCopy(obj) {
            return JSON.parse(JSON.stringify(obj));
        },
    },
};
</script>

<style scoped lang="less">
.batchContainer {
    /deep/ .el-dialog__body {
        padding-top: 10px;
    }

    /deep/ .FloorTypeSelect .el-form-item__content {
        width: 200px;
    }
    /deep/ .el-table-column--selection .cell {
        padding: 0;
    }

    /deep/ .el-step__description {
        margin: 2% 0;
    }

    .text-color {
        color: #409eff;
    }

    .el-checkbox-group {
        display: flex;
        justify-content: space-between;
        flex-direction: row;
        flex-wrap: wrap;

        .el-checkbox {
            width: 43%;
        }

        .el-checkbox:last-of-type {
            margin-right: 30px;
        }
    }

    .next-step {
        display: block;
        float: right;
    }

    .filters {
        margin: 10px 0;
    }

    .checkbox {
        display: flex;
        justify-content: space-between;
        flex-direction: row;
        flex-wrap: wrap;

        p {
            width: 50%;
        }

        .el-checkbox:last-of-type {
            margin-right: 10px;
        }
    }

    .text-message {
        overflow: hidden;
        margin-top: 10px;
        color: #333;
        border-left: 8px solid #333;
        text-indent: 10px;
        font-weight: 600;
    }

    .small {
        font-size: 12px;
        color: #555;
    }
    .dialog-footer {
        height: 32px;
    }

    .all-message {
        overflow: hidden;

        button {
            float: right;
            padding: 10px;
            margin-left: 5px;
        }
    }
}
</style>
