<template>
    <div id="deviceList">
        <el-row class="left">
            <span style="float: left">当前选择的部件类型:{{ category.name }}</span>
            <!-- <div style="width:200px;display:inline-block;text-align:left;color:gray;">
        <span>隐藏自动填充的信息</span>
        <el-checkbox v-model="isWatch" @change="getTableHeader"></el-checkbox>
      </div> -->
            <span style="float: right">
                <el-select v-model="showType" @change="initTable" style="width: 100px; margin-right: 10px; vertical-align: bottom">
                    <el-option v-for="item in showTypes" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                </el-select>
                <span>增加</span>
                <el-input-number v-model="addNum" :controls="false" style="width: 50px" :min="1" :max="50"></el-input-number>
                <span>个{{ category.name }}</span>
                <el-button @click="handleAddTableRow">增加</el-button>
            </span>
        </el-row>
        <div class="tableBox">
            <div class="center middle_sty" style="flex: 2" v-show="tableData && !tableData.length">
                <p>
                    <i class="icon-wushuju iconfont"></i>
                    暂无数据
                </p>
            </div>
            <div class="tableLeft" v-show="tableData && tableData.length">
                <handson-table ref="table"></handson-table>
            </div>
        </div>
        <el-row class="center">
            <el-button type="primary" size="medium" @click="handleCreateTableData" class="create_button" :disabled="createDisable"
                >创建部件</el-button
            >
        </el-row>
        <!-- 二维码弹窗 -->
        <qrcode :dialog="myDialog" :qrcodeUrl="qrcodeUrl" :addBody="true" ref="qrcode"></qrcode>
        <upload-files-dialog :read="onlyRead ? true : false" ref="upload" @changeFile="fileChange" :keysArr="filesArr" :dialog="myDialog">
        </upload-files-dialog>
        <upload-img-dialog :read="onlyRead ? true : false" @changeFile="imgChange" :keysArr="imgsArr" :dialog="myDialog"></upload-img-dialog>
        <pic-dialog :read="onlyRead ? true : false" :dialog="myDialog" :keysArr="picsArr" @change="changePics"></pic-dialog>
        <details-dialog :iframeSrc="iframeSrc" v-if="myDialog.details" :dialog="myDialog"></details-dialog>
        <!-- 多选枚举类型维护 -->
        <menum :dialog="myDialog" :updateInfoData="updateInfoData" :updateInput="updateInput" @change="handleChangeMenum"></menum>
        <!-- 不支持的输入方式 -->
        <el-dialog title="临时维护信息点" :visible.sync="myDialog.update" @close="handleCloseUpdate" width="670px">
            <el-row>
                该信息点未定义对应组件，现在维护数据不确定后续是否可用。如确实需要维护，请点击
                <el-link @click="updateInputShow = true" type="primary" :underline="false">继续维护</el-link>
                。
            </el-row>
            <el-row style="margin-top: 20px" v-show="updateInputShow">
                <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8 }" placeholder="请输入内容" v-model="updateInput"></el-input>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="myDialog.update = false">取 消</el-button>
                <el-button type="primary" @click="handleClickUpdate">确 认</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import tools from "@/utils/scan/tools";
import handsonUtils from "@/utils/hasontableUtils";
import showTools from "@/utils/handsontable/notShow";
import text from "@/utils/handsontable/mainText";
import session from "@/framework/utils/storage";

import handsonTable from "@/components/common/handsontable";
import {
    // getDataDictionary,
    createPart,
    createPropertyData,
    getEquipBelongs,
} from "@/api/scan/request";
import { getDataDictionary } from "@/api/dict";

import { mapGetters, mapActions } from "vuex";

import qrcode from "@/components/ledger/lib/qrcode";
import uploadFilesDialog from "@/components/dialogs/list/filesDialog";
import uploadImgDialog from "@/components/dialogs/list/uploadImgDialog";
import picDialog from "@/components/dialogs/list/picDialog";
import menum from "@/components/dialogs/list/menum";

export default {
    components: {
        qrcode, //二维码页面
        uploadFilesDialog,
        uploadImgDialog,
        picDialog,
        handsonTable,
        menum,
    },
    data() {
        return {
            addNum: 1,
            onlyRead: false,
            tableHeader: [],
            // tableData: session.get("partsAddData")
            //     ? session.get("partsAddData").length
            //         ? session.get("partsAddData")
            //         : [{ Checked: 1 }]
            //     : [{ Checked: 1 }],
            tableData: session.get("partsAddData")
                ? session.get("partsAddData").length
                    ? session.get("partsAddData")
                    : [{}]
                : [{}],
            showTypes: [
                // { value: "partInfo", label: '隐藏信息点' },
                { value: "Visible", label: "只看采集信息" },
                { value: "all", label: "全部" },
            ],
            showType: this.$route.query.showType,
            copyTableData: [],
            category: "", //当前设备类
            myDialog: {
                qrcode: false, //二维码弹窗
                uploadFiles: false, //上传文件
                uploadImgs: false, //上传单个图片
                pic: false, //多个图片
                addDevice: false,
                systemType: false,
                details: false, //详情页
                changeRea: false,
                lookPic: false, //图片查看
                update: false, //临时维护信息点
                menum: false, //临时多选枚举类型信息点
            },
            inputMap: {
                flowBuild: {
                    editable: true,
                    code: "flowBuild",
                    name: "建筑楼层",
                    path: "flowBuild",
                    category: "STATIC",
                    dataType: "ENUM",
                },
            }, //信息点和输入方式映射表
            updateInputShow: false, //是否显示临时维护输入框
            updateInfoData: {}, //当前信息点信息
            updateInfoPoint: "", //临时维护信息点
            updateInput: "", //临时维护信息点值
            qrcodeUrl: "", //二维码图片地址
            filesArr: [], //保存临时的文件key
            imgsArr: [], //临时保存的图片key数组
            picsArr: [], //临时设备图片keys数组
            systemId: null,
            graphyId: null,
            id: 0,
            EquipmentList: [],
            firmId: "", //品牌型号所需字段--族id三位编码(传设备类id或部件类id)
            createDisable: false,
        };
    },
    computed: {
        ...mapGetters("layout", ["projectId", "secret", "userId"]),
    },
    created() {
        this.category = this.$route.query;
        this.category.parentId = this.category.code.substr(0, this.category.code.length - 2);
        this.getBelongs();
        this.getTableHeader();
    },
    methods: {
        //查询部件类对应的 族
        getBelongs() {
            let params = {
                data: {
                    filters: `equipCode='${this.category.code}'`,
                    pageNumber: 1,
                    pageSize: 50,
                },
            };
            getEquipBelongs(params, (res) => {
                if (res.content.length) {
                    this.firmId = res.content[0].family;
                }
            });
        },
        // 获取表头数据(初始化表格)
        async getTableHeader() {
            let params = {
                orders: "sort asc, name desc",
                pageNumber: 1,
                pageSize: 1000,
                type: this.category.code,
                // Filters: `type='Equipment' or type='${this.category.Code}'`
            };
            await getDataDictionary(params, (res) => {
                this.tableHeader = res.content;
                this.tableHeader.forEach((item) => {
                    if (item.path) {
                        this.inputMap[item.path] = item;
                    }
                });
                this.initTable();
            });
        },
        // 创建部件数据
        async handleCreateTableData() {
            let newData = this.tableData.filter((item) => {
                let keys = Object.keys(item);
                keys.map((key) => {
                    //将值为空字符串的属性删除
                    if (item[key] == "") {
                        delete item[key];
                    }
                });
                let newK = Object.keys(item);
                if ((item.Checked && newK.length > 1) || (!item.Checked && newK.length)) {
                    return item;
                }
            });
            if (!newData.length) {
                this.$message("创建信息为空,请录入信息后再创建!");
                return;
            }
            let flag = false;
            newData.map((item) => {
                if (!item.localName || !item.localId) {
                    flag = true;
                }
            });
            if (flag) {
                this.$message.info("存在设备的本地名称或本地编码为空，请检查");
                return;
            }

            for (let i = 0; i < newData.length; i++) {
                newData[i].parentId = this.category.deviceId; //当前设备id
                newData[i].classCode = this.category.code; //当前部件分类
                newData[i].family = this.firmId;
                //待接口修改为关联创建
                let param = {
                    cascade: [],
                    content: [newData[i]],
                };
                this.createDisable = true;
                await createPart(param, async (res) => {
                    // if (newData[i].Checked) {
                    //     //同时创建资产
                    //     param.content[0].equipmentId = res.entityList[0].id;
                    //     await createPropertyData(param, (res) => {
                    //         // todo 创建资产
                    //     });
                    // }
                    if (i == newData.length - 1) {
                        this.createDisable = false;
                        this.$message.success("创建成功");
                        session.remove("partsAddData");
                        this.$router.push({
                            path: "/ledger/partsmanage",
                            query: {
                                deviceId: this.category.deviceId,
                                typeId: this.category.parentId,
                                pageNo: this.category.pageNo,
                                pageSize: this.category.pageSize,
                            },
                        });
                    }
                });
            }
        },
        // 删除表格行
        handleDeleteTableRow(a, b, c, d) {
            if (d && d === "ContextMenu.removeRow") {
                this.$message.success("删除成功");
                this.formaTableData();
            }
        },
        // 添加行
        handleAddTableRow() {
            let addRowLength = this.addNum;
            for (let i = 0; i < addRowLength; i++) {
                // this.tableData.push({ Checked: 1 });
                this.tableData.push({});
            }
            this.initTable();
            this.formaTableData();
        },
        //修改
        handleUpdataTable(changeData, source) {
            if (!this.onlyRead && source != "ObserveChanges.change") {
                this.formaTableData();
            }
        },
        //保存去掉空字段的新增数据
        formaTableData() {
            let newData = this.tableData.filter((item) => {
                let keys = Object.keys(item);
                keys.map((key) => {
                    //将值为空字符串的属性删除
                    if (item[key] == "") {
                        delete item[key];
                    }
                });
                if (keys.length && Object.keys(item).length) {
                    return item;
                }
            });
            session.set("partsAddData", newData);
        },
        //格式化表头显示的数据
        formatHeaderData(list) {
            let arr = tools.copyArr(list);
            let data = showTools.headerTextFilter(arr, "parts", this.onlyRead, this.showType, true);
            // data.unshift("同时创建资产");
            return data;
        },
        formatHeaderType(list) {
            //格式化表头头映射的数据
            let arr = tools.copyArr(list);
            let data = showTools.headerTypeFilter(arr, "parts", this.onlyRead, this.showType, true);
            // data.unshift({
            //     type: "checkbox",
            //     checkedTemplate: 1,
            //     uncheckedTemplate: 0,
            //     data: "Checked",
            //     label: {
            //         position: "after",
            //     },
            // });
            return data;
        },
        initTable() {
            //实例化表格
            let settings = {
                data: this.tableData,
                colHeaders: this.formatHeaderData(this.tableHeader),
                columns: this.formatHeaderType(this.tableHeader),
                rowHeights: 30,
                fillHandle: "vertical", //允许纵向填充
                maxRows: this.tableData.length,
                contextMenu: this.onlyRead
                    ? false
                    : {
                          items: {
                              remove_row: {
                                  name: "删除部件",
                              },
                          },
                      },
                // 事件
                afterChange: this.handleUpdataTable, //修改后
                afterFilter: this.trimmedRows, //排序前
                afterRemoveRow: this.handleDeleteTableRow, //右键删除
                afterOnCellMouseDown: this.handleTdClick, //鼠标点击
            };
            this.$nextTick(() => {
                this.tableExample = this.$refs.table.init(settings);
            });
        },
        //去除数组中相同的元素
        array_diff(a, b) {
            for (var i = 0; i < b.length; i++) {
                for (var j = 0; j < a.length; j++) {
                    if (a[j] == b[i]) {
                        a.splice(j, 1);
                        j = j - 1;
                    }
                }
            }
            return a;
        },
        //上传文件弹窗触发事件
        fileChange(keys) {
            this.setDataToMain(keys, this.messKey, this.row);
        },
        //上传图片弹窗触发事件
        imgChange(keys) {
            this.setDataToMain(keys, this.messKey, this.row);
        },
        //设备图片弹窗改变事件
        changePics(keys) {
            this.setDataToMain(keys, this.messKey, this.row);
        },
        //表格点击事件
        handleTdClick(el, rowArr) {
            //点击的是表头
            if (rowArr.row < 0) {
                return;
            }
            //被筛选过后的数组
            let trimmedArr = this.trimmedRows();
            //是否启用了排序
            let isSort = this.tableExample.getPlugin("columnSorting").isSorted();
            if (trimmedArr.length && isSort) {
                let sortArr = this.myHotArr.getPlugin("columnSorting").rowsMapper.__arrayMap;
                let infos = this.tableData[trimmedArr[sortArr[rowArr.row]]];
                this.getInfors(infos, { row: sortArr[rowArr.row], col: rowArr.col });
            } else if (isSort) {
                //排序后的数组
                let sortArr = this.tableExample.getPlugin("columnSorting").rowsMapper.__arrayMap;
                let infos = this.tableData[sortArr[rowArr.row]];
                this.getInfors(infos, { row: sortArr[rowArr.row], col: rowArr.col });
            } else if (trimmedArr.length) {
                let infos = this.tableData[trimmedArr[rowArr.row]];
                this.getInfors(infos, { row: trimmedArr[rowArr.row], col: rowArr.col });
            } else {
                let infos = this.tableData[rowArr.row];
                this.getInfors(infos, rowArr);
            }
        },
        //获取被筛选掉的行号
        trimmedRows() {
            var plugin = this.tableExample.getPlugin("trimRows").trimmedRows;
            let dataLength = this.tableData.length;
            let dataArr = new Array();
            for (let i = 0; i < dataLength; i++) {
                dataArr.push(i);
            }
            if (plugin.length <= 0) {
                dataArr = undefined;
            } else {
                dataArr = this.array_diff(dataArr, plugin);
            }
            return dataArr || [];
        },
        getInfors(infos, row) {
            //其他的开始判断
            let val = this.tableExample.colToProp(row.col);
            let inputData = this.inputMap[val];
            this.row = row.row;
            this.messKey = val;
            //设备二维码图片
            if (val == "defaultQRCode") {
                this.myDialog.qrcode = true;
                this.$refs.qrcode.getCanvas(1111);
            }
            //   if (
            //     val == "flowBuild" || //所属建筑楼层
            //     val == "infos.productDate" || //生产日期
            //     val == "infos.serialNum" || //出厂编号
            //     val == "infos.assetID" || //资产编号
            //     val == "infos.purchasePrice" || //采购价格
            //     val == "infos.insuranceNum" || //保险单号
            //     val == "infos.insuranceFile" //保险文件
            //   ) {
            //     const propertyId = this.tableData[row.row].propertyId;
            //     if (!propertyId) { //未关联资产
            //         this.$confirm('您暂未关联设备对应的资产，该信息点不可编辑', '提示', {
            //             confirmButtonText: '我知道了',
            //             showCancelButton: false,
            //             type: 'warning',
            //             center: true
            //         }).then(() => {
            //             return false;
            //         });
            //     }
            //     return false
            //   }
            //保险文件--设备文档--安装质检报告
            if (
                val == "infos.insuranceFile" || //保险文件
                val == "infos.archive" || //设备文档
                val == "infos.checkReport" || //安装质检报告
                val == "infos.maintainManual" || //维修保养手册
                val == "infos.approachingAcceptance" || //进场验收单
                val == "infos.acceptanceReport" || //验收报告
                val == "infos.operationManual" || //操作说明书
                val == "infos.originalCertificate" || //原厂证明
                val == "infos.testReport" || //检测报告
                val == "infos.productCertification" || //产品合格证
                val == "infos.installInstruction" || //
                val == "infos.supplierContract" || //供应合同
                val == "infos.drawing" || //设备图纸
                val == "infos.installDrawing" //安装图纸
            ) {
                let data = tools.dataForKey(this.tableData[row.row], val);
                this.filesArr = data ? data : [];
                this.myDialog.uploadFiles = true;
            }
            //安装照片--设备铭牌照片
            if (val == "infos.installPic" || val == "infos.nameplate") {
                let data = tools.dataForKey(this.tableData[row.row], val);
                this.imgsArr = data ? data : [];
                this.myDialog.uploadImgs = true;
            }
            //设备照片
            if (val == "infos.pic") {
                let data = tools.dataForKey(this.tableData[row.row], val);
                this.picsArr = data ? data : [];
                this.myDialog.pic = true;
            }
            if (!this.onlyRead && !inputData.editable) {
                this.$confirm("该信息点的值为自动生成，不可人工维护！", "提示", {
                    confirmButtonText: "我知道了",
                    showCancelButton: false,
                    type: "warning",
                    center: true,
                }).then(() => {
                    return false;
                });
            }
            // 维护多选枚举值
            if (!this.onlyRead && inputData.dataType == "MENUM") {
                this.updateInfoData = inputData;
                this.updateInfoPoint = val;
                this.updateInput = tools.dataForKey(this.tableData[row.row], val);
                this.myDialog.menum = true;
                return false;
            }
            if (!this.onlyRead && showTools.inputModeArr.indexOf(inputData.dataType) == "-1") {
                this.updateInfoPoint = val;
                this.updateInput = tools.dataForKey(this.tableData[row.row], val);
                this.myDialog.update = true;
                return false;
            }
        },
        //关闭临时维护弹窗回调
        handleCloseUpdate() {
            this.updateInputShow = false;
            this.updateInfoPoint = "";
            this.updateInput = "";
        },
        //更新临时维护信息点
        handleClickUpdate() {
            tools.setDataForKey(this.tableData[this.row], this.updateInfoPoint, this.updateInput);
            this.handleUpdataTable([[this.row, this.updateInfoPoint, null, this.updateInput]], "edit");
            this.updateInputShow = false;
            this.myDialog.update = false;
            this.updateInput = "";
        },
        //多选枚举类型值修改
        handleChangeMenum(newValue) {
            tools.setDataForKey(this.tableData[this.row], this.updateInfoPoint, newValue);
            this.handleUpdataTable([[this.row, this.updateInfoPoint, null, newValue]], "edit");
            this.myDialog.menum = false;
            this.updateInput = "";
        },
        utilToKey(key, name, data, messName) {
            if (key == name) {
                this.setDataToMain(data[key], messName, this.row);
            }
        },
        //判断是否有值，有值赋值
        setDataToMain(data, key, row) {
            if (!!data && data != "--") {
                if (!!this.tableData[row]) {
                    //铭牌照片特殊处理
                    tools.setDataForKey(this.tableData[row], key, data);
                    // this.tableData[row][key] = data;
                } else {
                    this.tableData[row] = {};
                    tools.setDataForKey(this.tableData[row], key, data);
                }
            } else {
                tools.setDataForKey(this.tableData[row], key, "");
            }
        },
    },
};
</script>
<style lang="less" scoped>
#deviceList {
    overflow: hidden;
    height: 100%;
    background-color: #fff;
    padding: 10px;
    position: relative;

    .right {
        background: #fff;
    }

    .search-header {
        overflow: hidden;
        padding: 0 10px 10px 10px;
        border-bottom: 1px solid #bcbcbc;
    }

    .tableBox {
        display: flex;
        height: calc(100% - 100px);
        margin-top: 10px;

        .tableLeft {
            flex: 1;
        }
    }

    .create_button {
        margin-top: 10px;
    }
}
</style>
