/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .F88X
 *        X8888Y
 *      .}888888N;
 *        i888888N;        .:!              .I$WI:
 *          R888888I      .'N88~            i8}+8Y&8"l8i$8>8W~'>W8}8]KW+8IIN"8&
 *          .R888888I    .;N8888~          .X8'  "8I.!,/8"  !%NY8`"8I8~~8>,88I
 *            +888888N;  .8888888Y                                  "&&8Y.}8,
 *            ./888888N;  .R888888Y        .'}~    .>}'.`+>  i}!    "i'  +/'  .'i~  !11,.:">,  .~]!  .i}i
 *              ~888888%:  .I888888l      .]88~`1/iY88Ii+1'.R$8$8]"888888888>  Y8$  W8E  X8E  W8888'188Il}Y88$*
 *              18888888    E8888881    .]W%8$`R8X'&8%++N8i,8N%N8+l8%`  .}8N:.R$RE%N88N%N$K$R  188,FE$8%~Y88I
 *            .E888888I  .i8888888'      .:$8I;88+`E8R:/8N,.>881.`$8E/1/]N8X.Y8N`"KF&&FK!'88*."88K./$88%RN888+~
 *            8888888I  .,N888888~        ~88i"8W,!N8*.I88.}888%F,i$88"F88"  888:E8X.>88!i88>`888*.}Fl1]*}1YKi'
 *          i888888N'      I888Y          ]88;/EX*IFKFK88X  K8R  .l8W  88Y  ~88}'88E&%8W.X8N``]88!.$8K  .:W8I
 *        .i888888N;        I8Y          .&8$  .X88!  i881.:%888>I88  ;88]  +88+.';;;;:.Y88X  18N.,88l  .+88/
 *      .:R888888I
 *      .&888888I                                          Copyright (c) 2016-2020.  博锐尚格科技股份有限公司
 *        ~8888'
 *        .!88~                                                                     All rights reserved.
 *
 * *********************************************************************************************************************
 */

import { SGraphItem, SAnchorItem } from "@persagy-web/graph/lib";
import { SPoint, SPainter, SColor } from "@persagy-web/draw";
import { Example } from "../index";
import { SBaseIconTextEdit, SBaseTextEdit } from "@persagy-web/edit";
import { svgTobase64, uuid } from "@persagy-web/big-edit/lib/until";
/**
 * 编辑基础设备类
 *
 * @author 张宇 <taohuzy@163.com>
 */
export class SPlanEquipment extends SBaseIconTextEdit {
    /** 设备图例 */
    private _legendData: Example | null = null;
    set legendData(val) {
        this._legendData = val;
        this.initData();
    } // set legendData()
    get legendData(): Example | null {
        return this._legendData;
    } // get legendData()

    // 文件服务器key值
    defaultUrl: string = "";
    /** 图例url */
    private _url: string = "";
    set url(val) {
        this._url = val;
        this.initUrl();
    } // set url()
    get url(): string {
        return this._url;
    } // get url()

    /** 与BIM坐标关系连线的颜色 */
    _lineColor: SColor = new SColor("#F54E45ff");
    get lineColor(): SColor {
        return this._lineColor;
    }
    set lineColor(v: SColor) {
        this._lineColor = v;
        this.update();
    }

    /** 是否显示与BIM坐标的关系 */
    _showLine: boolean = false;
    get showLine(): boolean {
        return this._showLine;
    }
    set showLine(v: boolean) {
        if (v === this._showLine) {
            return;
        }
        this._showLine = v;
        this.update();
    }

    /** 公式 */
    private _formula: any[] = [];
    // private _formula: string = "";
    set formula(val) {
        this._formula = val;
        try {
            // const textList = JSON.parse(this._formula);
            if (this.scene) {
                this.textItemList.forEach((textItem) => {
                    this.scene?.removeItem(textItem);
                });
            }
            if (this._formula.length) {
                // if (textList.length) {
                const textItemList: any[] = [];
                this._formula.forEach((item: any, index: number) => {
                    // textList.forEach((item: any, index: number) => {
                    let obj = new SBaseTextEdit(this, null);
                    obj.propertyData = { ...item };
                    obj.text = item.name;
                    if (item.pos) {
                        obj.moveTo(item.pos.x, item.pos.y);
                    } else {
                        obj.moveTo(this.img.width * 0.5, this.font.size * (index - 0.125 - 0.5 * this._formula.length));
                    }
                    // TODO: obj.moveTo(this.img.width * 0.5, -(this.font.size * 1.25 * 0.5) + (index * this.font.size) - (textList.length - 1) * 0.5 * this.font.size);
                    // obj.moveTo(this.img.width * 0.5, this.font.size * (index - 0.125 - 0.5 * textList.length));
                    obj.connect("onMove", this, this.textMove.bind(this));
                    obj.font = this.font;
                    obj.color = this.color;
                    obj.isTransform = false;
                    obj.showSelect = false;
                    textItemList.push(obj);
                });
                this.textItemList = textItemList;
            } else {
                this.textItemList = [];
            }
            this.update();
        } catch (error) {
            console.error("公式数据错误", error);
        }
    } // set formula()
    // get formula(): string {
    get formula(): any[] {
        return this._formula;
    } // get formula()

    //  设备附加数据
    anotherMsg: string = "";

    /**
     * 构造函数
     *
     * @param parent    指向父对象
     * @param data      数据
     */
    constructor(parent: SGraphItem | null, data: Example) {
        super(parent);
        this.zOrder = 9700;
        this.isTransform = false;
        this.sWidth = 32;
        this.sHeight = 32;
        this.img.showSelect = false;
        this.moveable = true;
        this.selectable = true;
        this.legendData = data;
    } // Constructor

    /**
     * 设置 legendData 时对 item 做设置
     */
    initData() {
        if (!this.legendData) return;
        if (this.legendData.size) {
            this.sWidth = this.legendData.size.width;
            this.sHeight = this.legendData.size.height;
        }

        this.img.connect("onMove", this, this.changeAnchorPoint.bind(this));
        if (this.legendData.anchorList && this.legendData.anchorList.length) {
            this.anchorList = this.legendData.anchorList.map((t) => {
                let item = new SAnchorItem(this);
                if (t.anchorId) {
                    item.id = t.anchorId;
                }
                item.moveTo(t.pos.x, t.pos.y);
                return item;
            });
        } else {
            const anchorPoint = [{ x: this.img.x, y: this.img.y, anchorId: uuid() }];
            this.anchorList = anchorPoint.map((t) => {
                let item = new SAnchorItem(this);
                if (t.anchorId) {
                    item.id = t.anchorId;
                }
                item.moveTo(t.x, t.y);
                return item;
            });
        }
        this.id = this.legendData.id ? this.legendData.id : "";
        this.showAnchor = false;
        this.anotherMsg = this.legendData?.properties?.anotherMsg ? this.legendData.properties.anotherMsg : "";
        if (this.legendData.pos?.x && this.legendData.pos?.y) {
            this.x = this.legendData.pos.x;
            this.y = this.legendData.pos.y;
        }
    }

    initUrl() {
        svgTobase64(this.url)
            .then((res) => {
                this.img.url = res ? res : "";
            })
            .catch((res) => {
                this.img.url = res;
            });
    }

    /**
     * 文本位置移动回调函数
     * @param textItem 移动的文本元素
     * @param pointList 移动前后位置坐标信息
     */
    textMove(textItem: SBaseTextEdit, pointList: SPoint[]) {
        this.moveText();
    }
    moveText() {}

    /**
     * 返回对象储存的相关数据
     *
     * @return	对象储存的相关数据
     */
    toData(): any {
        if (this.legendData) {
            // 位置
            const objExtInfo = {
                attachObjectIds: [this.id],
                pos: this.pos,
                properties: {
                    id: this.id,
                    anotherMsg: this.anotherMsg,
                },
            };
            return objExtInfo;
        }
        return new Object();
    }

    /**
     * Item 绘制操作
     *
     * @param painter    绘制对象
     */
    onDraw(painter: SPainter): void {
        if (this.showLine && this.legendData?.bimLocation && this.legendData?.locationJson) {
            const bimX = (this.legendData.locationJson.x - this.x) / this.inverseScale;
            const bimY = (-this.legendData.locationJson.y - this.y) / this.inverseScale;
            const bimColor = new SColor(this.lineColor);
            bimColor.alpha = 51;
            painter.pen.color = this.lineColor;
            painter.pen.lineWidth = 1
            painter.drawLine(0, 0, bimX, bimY);

            painter.pen.color = SColor.Transparent;
            painter.brush.color = bimColor;
            painter.drawCircle(bimX, bimY, 5);
            painter.brush.color = this.lineColor;
            painter.drawCircle(bimX, bimY, 2);
        }

        super.onDraw(painter);
    } // Function onDraw()
}