<!-- 编辑信息点页面,添加设备,设备组,空间 三个共用 -->
<template>
    <el-dialog
        custom-class="edit-info-point-dialog"
        append-to-body
        title="编辑信息点"
        :visible="dialogVisible"
        @close="close"
        :close-on-press-escape="false"
    >
        <div class="tabs">
            <div class="tab tab-left" :class="{ active: tab === 0 }" @click="tab = 0">信息点</div>
            <div class="tab tab-right" :class="{ active: tab === 1 }" @click="tab = 1">属性</div>
        </div>

        <!-- 信息点 -->
        <div class="info-point-tab" v-if="tab === 0">
            <!-- 公式 -->
            <div class="formula">
                <div class="header">公式</div>
                <div class="tag-container">
                    <el-tag
                        :key="`${index}_${tag}`"
                        v-for="(tag, index) in chooseList"
                        closable
                        :disable-transitions="false"
                        @close="handleClose(tag)"
                    >
                        {{ tag }}
                    </el-tag>
                    <el-input
                        class="input-new-tag m-input"
                        v-if="inputVisible"
                        v-model="inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm"
                        @blur="handleInputConfirm"
                        :maxlength="20"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag add-tag" size="small" @click="showInput">+ 自定义公式</el-button>
                </div>
            </div>
            <!-- 信息点 -->
            <div class="info-point">
                <div class="header">
                    <div>选择信息点</div>
                </div>
                <div v-for="(item, index) in list" :key="index">
                    <div class="title">{{ item[0].firstName || "信息" }}</div>
                    <el-checkbox-group v-model="chooseList" class="m-check-group">
                        <el-checkbox v-for="({ name }, secIndex) in item" :title="name" :label="name" :key="secIndex" />
                    </el-checkbox-group>
                </div>
                <!-- <div class="instantaneous">
                    <div class="title">瞬时状态</div>
                    <el-checkbox-group v-model="instantaneousCheckList" class="m-check-group">
                        <el-checkbox v-for="({ name }, index) in instantaneousList" :label="name" :key="index" />
                    </el-checkbox-group>
                </div>
                <div class="accumulative">
                    <div class="title">累计指标</div>
                    <el-checkbox-group v-model="accumulativeCheckList" class="m-check-group">
                        <el-checkbox v-for="({ name }, index) in accumulativeList" :label="name" :key="index" />
                    </el-checkbox-group>
                </div> -->
            </div>
        </div>

        <!-- 属性 -->
        <div class="property-tab" v-if="tab === 1">
            <!-- 设备的属性 -->
            <div class="equipment" v-if="true && type === 'equipment'">
                <div class="color">
                    <p>字符颜色</p>
                    <div class="color-select">
                        <el-color-picker
                            @change="changeColor"
                            popper-class="m-color-picker"
                            show-alpha
                            class="fix-box-1"
                            v-model="equipmentData.color"
                        ></el-color-picker>
                    </div>
                </div>
                <div class="size">
                    <p>字符大小</p>
                    <el-input-number
                        style="width: 90px"
                        v-model="equipmentData.size"
                        controls-position="right"
                        size="mini"
                        :min="1"
                        :max="20"
                        :maxlength="100"
                    ></el-input-number>
                </div>
                <div class="icon">
                    <p>显示图标</p>
                    <el-upload
                        class="avatar-uploader"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        :on-success="handleAvatarSuccess"
                    >
                        <img v-if="equipmentData.url" :src="equipmentData.imgUrl" class="avatar" />

                        <el-button v-else type="small">替换图标</el-button>
                    </el-upload>
                </div>
            </div>
            <!-- 设备组的属性 -->
            <div class="equipment-group" v-else-if="false && type === 'equipment-group'"></div>
            <!-- 空间的属性 -->
            <div class="space" v-else-if="true || type === 'space'">
                <!-- 字符 -->
                <div class="font">
                    <div class="color">
                        <p>字符色</p>
                        <div class="color-select">
                            <el-color-picker
                                show-alpha
                                popper-class="m-color-picker"
                                @change="changeColor"
                                class="fix-box-1"
                                v-model="spaceData.color"
                            ></el-color-picker>
                        </div>
                    </div>
                    <div class="size">
                        <p>字符大小</p>
                        <el-input-number
                            style="width: 90px"
                            v-model="spaceData.size"
                            controls-position="right"
                            size="mini"
                            :min="1"
                            :max="20"
                            :maxlength="100"
                        ></el-input-number>
                    </div>
                </div>
                <!-- 填充色 -->
                <div class="fill-color">
                    <p>填充色</p>
                    <div class="color-select">
                        <el-color-picker
                            show-alpha
                            popper-class="m-color-picker"
                            @change="changeColor"
                            class="fix-box-1"
                            v-model="spaceData.fillColor"
                        ></el-color-picker>
                    </div>
                </div>
                <!-- 边框 -->
                <div class="border">
                    <p>边框</p>
                    <div class="property">
                        <div class="color-box">
                            <div class="cololorSelect">
                                <el-color-picker
                                    show-alpha
                                    popper-class="m-color-picker"
                                    @change=""
                                    class="fix-box-1"
                                    v-model="spaceData.borderColor"
                                ></el-color-picker>
                            </div>
                            <span class="text">颜色</span>
                        </div>
                        <div class="line-width">
                            <el-input-number
                                style="width: 80px"
                                v-model="spaceData.linewidth"
                                controls-position="right"
                                @change="changeLineWidth"
                                size="mini"
                                :min="1"
                                :max="20"
                                :maxlength="100"
                            ></el-input-number>
                            <span class="text">线宽</span>
                        </div>

                        <div class="line-width">
                            <el-select
                                v-model="spaceData.linestyle"
                                :default-value="borderLineOption[0].id"
                                size="mini"
                                style="width: 90px"
                                placeholder="请选择"
                                :ref="`selectLine`"
                                @change="changeLineStyle()"
                            >
                                <el-option v-for="item in borderLineOption" :key="item.id" :label="item.src" :value="item.id">
                                    <img :src="item.src" alt width="60" />
                                </el-option>
                            </el-select>
                            <span class="text">线型</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 确定,取消按钮 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
        </div>
    </el-dialog>
</template>
<script>
/* eslint-disable no-case-declarations */
/**
 * 编辑信息点页面
 * 添加设备,设备组,空间 三个共用
 */
import { mapState, mapMutations } from "vuex";
import { planerSave, planerUpdate, pubPlanerUpdate } from "@/api/labsl";
import { dictQuery } from "@/api/datacenter";
import { imgBaseUrl, imgServeUpload } from "@/api/imageservice";
import { cloneDeep } from "lodash";
import { rgbaNum, svgTobase64 } from "@persagy-web/big-edit/lib/until";

import { SColor } from "@persagy-web/draw/lib";
const list = [
    { name: "运行状态", id: "yxzt" },
    { name: "故障状态", id: "gzzt" },
    { name: "云端控制状态", id: "gzzt1" },
    { name: "故障状态2", id: "gzzt2" },
    { name: "故障状态3", id: "gzzt3" },
    { name: "故障状态4", id: "gzzt4" },
    { name: "故障状态5", id: "gzzt5" },
    { name: "故障状态6", id: "gzzt6" },
    { name: "故障状态7", id: "gzzt7" },
    { name: "故障状态8", id: "gzzt8" },
    { name: "故障状态9", id: "gzzt9" },
    { name: "故障状态10", id: "gzzt10" },
    { name: "故障状态11", id: "gzzt11" },
    { name: "故障状态12", id: "gzzt12" },
    { name: "故障状态13", id: "gzzt13" },
];
export default {
    name: "editInfoPoint",
    props: {
        showDialog: {
            type: Boolean,
            required: true,
        },
        // 类型, equipment 设备, equipmentGroup 设备组, space 空间
        type: {
            type: String,
            required: true,
        },
        // 设备code值
        code: {
            type: String,
        },
    },
    components: {},
    data() {
        return {
            dialogVisible: false,
            tab: 0,
            chooseList: [],
            inputVisible: false,
            inputValue: null,

            //瞬时状态列表
            // instantaneousCheckList: [],
            // instantaneousList: cloneDeep(list),
            // 累计指标列表
            list: [],
            // accumulativeCheckList: [],
            // accumulativeList: cloneDeep(list),
            /** -------------------设备属性使用值start-------------------------- */
            equipmentData: {
                color: "#000000",
                size: 1,
                url: "",
                imgUrl: "", //图片路径,页面显示使用
            },
            /** -------------------设备属性使用值end-------------------------- */
            /** -------------------空间属性使用值start-------------------------- */
            spaceData: {
                color: "",
                size: 1,
                fillColor: "",
                borderColor: "#cccccc",
                linewidth: 1,
                linestyle: "Solid",
                linestyle: "",
            },
            borderLineOption: [
                {
                    id: "Solid",
                    src: require("@/assets/images/solidLine.png"),
                },
                {
                    id: "Dashed",
                    src: require("@/assets/images/dashedLine.png"),
                },
                {
                    id: "Dotted",
                    src: require("@/assets/images/dotLine.png"),
                },
            ],
            /** -------------------空间属性使用值end-------------------------- */
        };
    },
    computed: {
        ...mapState(["styleMap", "state", "id", "graphId", "buildingId", "floorId"]),
    },
    watch: {
        // 是否打开弹窗
        showDialog(val) {
            this.dialogVisible = val;
            // 打开弹窗
            val && this.initDialog();
        },
        spaceData: {
            handler(newV, oldV) {
                // // console.log("spaceData");
                if (newV.linestyle) {
                    this.$nextTick(() => {
                        this.setLineStyle();
                    });
                }
            },
            deep: true,
        },
        code(newV, oldV) {
            if (newV && newV !== oldV) {
                // this.getInfoPoint();
            }
        },
    },
    mounted() {
    },
    methods: {
        ...mapMutations(["ADDSTYLE"]),
        // 展示标签输入框
        showInput() {
            this.inputVisible = true;
        },
        initDialog() {
            this.spaceData = {
                color: "",
                size: 1,
                fillColor: "",
                borderColor: "#cccccc",
                linewidth: 1,
                linestyle: "",
            };
            this.tab = 0;
            this.$nextTick(() => {
                this.setLineStyle();
            });
            // 获取信息点值
            this.getInfoPoint();
            // 获取公式,属性信息
            const styleMap = { ...this.styleMap.defaultEquipStyle, ...(this.styleMap[this.code] || {}) };
            const { formula, url, color, size } = styleMap;
            this.chooseList = JSON.parse(formula || "[]");
            // color 8位hex转rgba
            this.equipmentData = { url, color: new SColor(color).toRgba(), size, imgUrl: "" };
            // 设置设备/设备组/空间 图片地址
            const imgUrl = url ? imgBaseUrl + url : "";
            // equipment 设备, equipmentGroup 设备组, space 空间
            const dict = {
                equipment: "equipmentData",
                equipmentGroup: "equipmentGroupData",
                space: "spaceData",
            };
            // console.log(imgUrl);
            imgUrl && this.initImgUrl(imgUrl, dict[this.type]);
        },
        /**
         * 设置设备/设备组/空间 图片地址
         */
        initImgUrl(imgUrl, data) {
            svgTobase64(imgUrl)
                .then((res) => {
                    this[data].imgUrl = res ? res : "";
                })
                .catch((res) => {
                    debugger;
                    this[data].imgUrl = res;
                });
        },
        async getInfoPoint() {
            // console.time(1);
            const res = await dictQuery({ pageNumber: 1, pageSize: 1000, type: this.code });
            // console.timeEnd(1);
            // console.time(2);
            let data = res.content;
            // 按照一级名称,将一维数组拆分成二维数组
            data = this._(data).groupBy("firstName").values().value();
            this.list = data;
            // console.timeEnd(2);
        },
        // 添加标签
        handleInputConfirm() {
            const inputValue = this.inputValue;
            if (inputValue) {
                this.chooseList.push(inputValue);
            }
            this.inputVisible = false;
            this.inputValue = "";
        },
        // 删除标签
        handleClose(tag) {
            this.chooseList.splice(this.chooseList.indexOf(tag), 1);
        },
        /**
         *  关闭弹窗
         */
        close() {
            this.dialogVisible = false;
            this.$emit("closeModal");
        },
        /**
         * 点击弹窗确定,提交接口
         */
        async confirm() {
            // equipment 设备, equipmentGroup 设备组, space 空间
            const formula = JSON.stringify(this.chooseList);
            // eslint-disable-next-line prefer-const
            let { color, url, size } = this.equipmentData;
            // eslint-disable-next-line prefer-const
            let colorlist = rgbaNum(color);
            let style = {};
            switch (this.type) {
                case "equipment":
                    color = new SColor(Number(colorlist[0]), Number(colorlist[1]), Number(colorlist[2]), colorlist[3] * 255).value;
                    style = { color, size, formula, url };
                    break;
                case "equipmentGroup":
                    break;
                case "space":
                    break;

                default:
                    break;
            }
            // console.log({ id: this.code, style });
            let res = "";
            // 上传的style全量信息
            const postStyle = { ...this.styleMap, [this.code]: style };
            delete postStyle.defaultEquipStyle;
            // console.log("===================");
            // console.log(postStyle);
            // console.log("===================");
            // 未发布接口
            if (this.state === "Draft") {
                res = await planerUpdate({
                    content: [
                        {
                            buildingId: this.buildingId,
                            floorId: this.floorId,
                            id: this.id,
                            graphId: this.graphId,
                            style: postStyle,
                        },
                    ],
                    projection: ["style"],
                });
            } else if (this.state === "Publish") {
                //已发布接口
                res = await pubPlanerUpdate({
                    content: [
                        {
                            buildingId: this.buildingId,
                            floorId: this.floorId,
                            id: this.id,
                            graphId: this.graphId,
                            style: postStyle,
                        },
                    ],
                    projection: ["style"],
                });
            }
            if (res.result === "success") {
                this.ADDSTYLE({ id: this.code, style });
                this.dialogVisible = false;
                this.$emit("closeModal");
            } else {
                this.$message(res.message);
            }
        },
        /**
         * 属性
         */
        /** ----------设备的属性---------- */
        // 改变颜色
        changeColor(val) {
            // // console.log("changeColor: ", val);
        },
        beforeAvatarUpload(file) {
            // eslint-disable-next-line @typescript-eslint/no-this-alias
            const that = this;
            const fileReader = new FileReader();
            fileReader.readAsDataURL(file); //读取图片
            // console.log(file);
            const ftype = file.type;
            const fname = file.name;
            const uploadKey = file.uid;
            const imgType = ftype.split(".")[ftype.length - 1];
            fileReader.addEventListener("load", function () {
                // 读取完成
                const res = fileReader.result;
                //将canvas的base64位图片转换成图片png的file
                const blob = that.dataURLtoBlob(res, ftype);
                //将其转换成file对象
                const file = new File([blob], fname, {
                    type: ftype,
                    lastModified: Date.now(),
                }); //blob转file

                // try sending
                const reader = new FileReader();
                const fileType = file.name.split(".");
                const imgType = fileType[fileType.length - 1];
                const CreateTime = that.formatDate(new Date(file.lastModified));
                reader.onloadend = function () {
                    // 这个事件在读取结束后，无论成功或者失败都会触发
                    // eslint-disable-next-line no-empty
                    if (reader.error) {
                    } else {
                        // 构造 XMLHttpRequest 对象，发送文件 Binary 数据
                        const xhr = new XMLHttpRequest();
                        xhr.open("POST", `${imgServeUpload}${uploadKey}.${imgType}`);
                        xhr.send(reader.result);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == 4) {
                                if (xhr.status == 200) {
                                    that.equipmentData.url = uploadKey + "." + imgType;
                                    // console.log(uploadKey + "." + imgType);
                                    // bus.$emit("updateStyle", "url", baseUrl + uploadKey + "." + imgType);
                                }
                            }
                        };
                    }
                };
                reader.readAsArrayBuffer(file);
            });
        },
        handleAvatarSuccess(res, file) {
            // console.log(res, file);
            this.equipmentData.imgUrl = URL.createObjectURL(file.raw);
        },
        dataURLtoBlob(dataURI, type) {
            const binary = atob(dataURI.split(",")[1]);
            const array = [];
            for (let i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], { type: type });
        },
        formatDate(now) {
            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const date = now.getDate();
            const hour = now.getHours();
            const minute = now.getMinutes();
            const second = now.getSeconds();
            return (
                year +
                "-" +
                month +
                "-" +
                (date > 10 ? date : "0" + date) +
                " " +
                hour +
                ":" +
                (minute > 10 ? minute : "0" + minute) +
                ":" +
                (second > 10 ? second : "0" + second)
            );
        },
        /**------------空间的属性----------------- */
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        changeLineWidth() {},
        changeLineStyle() {
            // this.setLineStyle();
        },
        setLineStyle() {
            const img = this.borderLineOption.filter((v) => v.id === this.spaceData.linestyle)[0]?.src;
            // // console.log(img);
            if (img) {
                this.$refs.selectLine?.$el?.children[0].children[0].setAttribute(
                    "style",
                    `
                        background: url(${img}) no-repeat;
                        color: rgba(0,0,0,0);
                        text-indent: -9999px;
                        background-position: 15px center;
                        background-size: 40px 1px;
                    `
                );
            } else {
                this.$refs.selectLine?.$el?.children[0].children[0].setAttribute(
                    "style",
                    `
                        background: inherit;
                        color:inherit;
                        text-indent: 0;
                    `
                );
            }
        },
    },
};
</script>
<style lang="less">
.m-color-picker {
    .el-color-dropdown__value {
        width: 170px !important;
    }
}
</style>
<style lang='less' scoped>
/deep/ .edit-info-point-dialog {
    width: 1200px;
    height: 648px;
    display: flex;
    flex-direction: column;
    .el-dialog__header {
        border-bottom: 1px solid #e4e5e7;
    }
    .el-dialog__body {
        flex: 1;
        padding-bottom: 0 !important;
    }
    .tabs {
        width: 100%;
        height: 30px;
        display: flex;
        .tab {
            width: 74px;
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #1f2429;
            text-align: center;
            border-radius: 0 4px 4px 0;
            border: 1px solid #c3c7cb;
        }
        .tab-left {
            border-radius: 4px 0 0 4px;
        }
        .active {
            color: #0091ff;
            background: #e1f2ff;
            border: 1px solid #0091ff;
        }
    }
    // 信息点tab
    .info-point-tab {
        width: 100%;
        // 大标题
        .header {
            width: 100%;
            height: 22px;
            margin: 20px 0 15px 0;
            padding-left: 5px;
            font-size: 16px;
            font-weight: 500;
            color: #1f2329;
            line-height: 22px;
            border-left: 2px solid #0091ff;
        }
        // 公式
        .formula {
            width: 100%;

            .tag-container {
                width: 100%;
                height: 80px;
                border-radius: 4px;
                border: 1px solid #e4e5e7;
                padding: 7px 12px;
                line-height: 1;
                overflow: auto;
                .el-tag {
                    background: #eff0f1;
                    border-radius: 2px;
                    color: #1f2429ff;
                    margin: 0 8px 8px 0;
                    padding: 5px 6px 5px 8px;
                    font-size: 14px;
                    height: 24px;
                    line-height: 1;
                    border: none;
                    &:hover {
                        border: none;
                    }
                    .el-icon-close {
                        color: #9ca2a9ff;
                        right: 0;
                        &:hover {
                            color: #fff;
                            background-color: #ccc;
                        }
                    }
                }
                .m-input {
                    width: auto !important;
                }
                .add-tag {
                    border-radius: 2px;
                    border: 1px dotted #0091ff;
                    font-weight: 400;
                    color: #0091ff;
                }
            }
        }
        // 信息点
        .info-point {
            flex: 1;
            max-height: 300px;
            overflow: auto;
            .header {
                border-left: none;
                height: auto;
                margin: 0;
                padding: 20px 0 15px 0;
                position: sticky;
                top: 0;
                background-color: #fff;
                z-index: 100;
                div {
                    border-left: 2px solid #0091ff;
                    // height: 22px;

                    padding-left: 5px;
                    font-size: 16px;
                    font-weight: 500;
                    color: #1f2329;
                    line-height: 22px;
                }
            }
        }
        // 瞬时状态,累计指标等
        .title {
            margin-bottom: 15px;
            font-weight: 500;
            color: #1f2329;
            font-size: 14px;
        }
        .m-check-group {
            // max-height: 90px;
            margin-bottom: 5px;
            overflow: auto;
            .el-checkbox {
                width: 150px;
                height: 30px;
                .el-checkbox__input {
                    vertical-align: initial;
                }
                .el-checkbox__label {
                    width: 120px;
                    line-height: 1;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
                // color: #1f2429;
                // font-size: 14px;
                // font-weight: 400;
            }
        }
    }
    // 属性tab
    .property-tab {
        margin-top: 20px;
        // 设备样式
        .equipment {
            & > div {
                margin-bottom: 15px;
                // font-size: 12px;
                color: #8d9399;
                // line-height: 16px;
                .color-select {
                    width: 32px;
                    height: 20px;
                    overflow: hidden;
                    position: relative;
                    margin: 4px 0;
                    .fix-box-1 {
                        margin-top: -8px;
                        margin-left: -8px;
                        /deep/ .el-color-picker__trigger {
                            width: 200px;
                            height: 200px;
                        }
                    }
                }
            }
        }
        // 空间样式
        .space {
            & > div {
                margin-bottom: 15px;
                font-size: 12px;
                color: #8d9399;
                line-height: 16px;
            }
            .color-select {
                width: 32px;
                height: 20px;
                overflow: hidden;
                position: relative;
                margin: 4px 0;
                .fix-box-1 {
                    margin-top: -8px;
                    margin-left: -8px;
                    /deep/ .el-color-picker__trigger {
                        width: 200px;
                        height: 200px;
                    }
                }
            }
            .font {
                display: flex;
                // height: 20px;
                .color {
                    margin-right: 20px;
                    p {
                        margin-bottom: 10px;
                    }
                    .color-select {
                        top: 4px;
                    }
                }
            }
            // 边框
            .border {
                width: 240px;
                .property {
                    display: flex;
                    align-items: center;
                    // justify-content: space-around;
                    .color-box {
                        display: flex;
                        align-items: center;
                        flex-direction: column;
                        .cololorSelect {
                            width: 32px;
                            height: 20px;
                            overflow: hidden;
                            position: relative;
                            margin: 4px 0;
                            .fix-box-1 {
                                margin-top: -16px;
                                margin-left: -8px;
                                /deep/ .el-color-picker__trigger {
                                    width: 200px;
                                    height: 200px;
                                }
                            }
                        }
                    }
                    .line-width {
                        display: flex;
                        align-items: center;
                        flex-direction: column;
                        margin-left: 20px;
                        position: relative;
                    }
                    span.text {
                        font-size: 12px;
                        color: #1f2429;
                        margin-top: 4px;
                    }
                }
            }
        }
        // 图标大小
        .avatar {
            width: 60px;
            height: 60px;
        }
    }
}
</style>