import { coordinate } from "../Coordinate.js";
import LayerEvents from "../enum/LayerEvents.js";
import UIEvents from "../enum/UIEvents.js";
import VectorType from "../enum/VectorType.js";
import { stateService } from "../Service/StateService.js";
import { floorplanService } from "../Service/FloorplanService.js";
import { historyService } from "../Service/HistoryService.js";
import { elementService } from "../Service/ElementService";
import { mathUtil } from "../MathUtil.js";
import { wallService } from "../Service/WallService.js";
import { tagService } from "../Service/TagService.js";
import { tableService } from "../Service/TableService.js";
import Constant from "../Constant";
import { addWall } from "../Controls/AddWall";
import { floorplanData } from "../FloorplanData.js";
import { signService } from "../Service/SignService.js";
import { customImageService } from "../Service/CustomImageService.js";
import mitt from "mitt";
import { history } from "../History/History.js";
import { iconService } from "../Service/IconService.js";
import { bgImageService } from "../Service/BgImageService.js";

export default class UIControl {
  constructor(layer) {
    this.layer = layer;
    this.bus = mitt();
    this.selectUI = null;
    this.appendData = null;

    // this.bus.emit('')
  }

  //点击左侧栏后，更新事件
  updateEventNameForSelectUI() {
    elementService.hideAll();
    //正在添加tag的时候，需要先删除
    const eventName = stateService.getEventName();
    // if (eventName == LayerEvents.AddTag) {
    //     let item = stateService.getDraggingItem()
    //     if (item && item.type == VectorType.Tag) {
    //         floorplanService.deleteTag(item.vectorId)
    //     }
    // }
    // stateService.clearItems()
    if (this.selectUI == UIEvents.Wall) {
      stateService.setEventName(LayerEvents.AddWall);
    } else if (this.selectUI == UIEvents.Table) {
      stateService.setEventName(LayerEvents.AddTable);
    } else if (this.selectUI == UIEvents.Rectangle) {
      stateService.setEventName(LayerEvents.AddRectangle);
    } else if (this.selectUI == UIEvents.Circle) {
      stateService.setEventName(LayerEvents.AddCircle);
    } else if (this.selectUI == UIEvents.Arrow) {
      stateService.setEventName(LayerEvents.AddArrow);
    } else if (this.selectUI == UIEvents.Icon) {
      stateService.setEventName(LayerEvents.AddIcon);
    } else if (this.selectUI == UIEvents.Tag) {
      stateService.setEventName(LayerEvents.AddTag);
    } else if (
      this.selectUI == UIEvents.Cigaret ||
      this.selectUI == UIEvents.FirePoint ||
      this.selectUI == UIEvents.LeftFootPrint ||
      this.selectUI == UIEvents.RightFootPrint ||
      this.selectUI == UIEvents.LeftShoePrint ||
      this.selectUI == UIEvents.RightShoePrint ||
      this.selectUI == UIEvents.FingerPrint ||
      this.selectUI == UIEvents.DeadBody ||
      this.selectUI == UIEvents.BloodStain
    ) {
      stateService.setEventName(LayerEvents.AddSign);
    }
  }

  /**
   * @param {*} type 部件类型
   * @param {*} name 属性名称
   * @param {*} value 属性值
   */
  async setAttributes(type, name, value) {
    let item = stateService.getFocusItem();
    let flag = true;
    switch (name) {
      case "delete":
        this.deleteItem();
        break;
      case 'update':
        if(type == VectorType.Tag){
            const tag = floorplanService.getTag(item.vectorId)
            if(value.hasOwnProperty('version')){
              value.color&&tag.setColor(value.color)
              value.fontSize&&tag.setFontSize(value.fontSize)
              value.text&&tag.setValue(value.text)
            }
            else{
                tag.setValue(value)
            }
        }
        else if(type == VectorType.Arrow){
            const arrow = floorplanService.getArrow(item.vectorId)
            if(value.hasOwnProperty('version')){
                arrow.setColor(value.color)
            }
        }
        else if(type == VectorType.Wall){
            const wall = floorplanService.getWall(item.vectorId)
            if(value.hasOwnProperty('version')){
                wall.setColor(value.color)
            }
        }
        else if(type == VectorType.Rectangle){
            const rectangle = floorplanService.getRectangle(item.vectorId)
            if(value.hasOwnProperty('version')){
                rectangle.setColor(value.color)
            }
        }
        else if(type == VectorType.Circle){
            const circle = floorplanService.getCircle(item.vectorId)
            if(value.hasOwnProperty('version')){
                circle.setColor(value.color)
            }
        }
        else if(type == VectorType.Table){
            const table = floorplanService.getTable(item.vectorId)
            if(value.hasOwnProperty('version')){
                table.setValue(value.content)
            }
            else{
                table.setValue(value)
            }
        }
        else if(type == VectorType.Title){
            if(value.hasOwnProperty('version')){
                floorplanService.updateTitle(value.text);
            }
            else{
                floorplanService.updateTitle(value);
            }
        }
        else if(type == VectorType.Compass){
          if(value.hasOwnProperty('version')){
            floorplanService.updateCompass(value.rotate)
            flag = value.save
          }
          else{
            floorplanService.updateCompass(value)
          }
        }
        else if(type == VectorType.CustomImage){
          const customImage = floorplanService.getCustomImage(item.vectorId)
          if(value.hasOwnProperty('rotate')){
            customImage.setAngle(value.rotate)
            flag = value.save
          }
          else if(value.hasOwnProperty('scale')){
            customImage.setScale(value.scale)
            flag = value.save
          }
          else if(value.hasOwnProperty('ratio')){
            customImage.setRatio(floor.customImages[key].ratio)
          }
        }
        else if(type == VectorType.BgImage){
          const bgImage = floorplanService.getBgImage()
          if(value.hasOwnProperty('scale')){
            bgImage.setScale(value.scale)
            flag = value.save
          }
        }
        else if(signService.isSign(type)){
          const sign = floorplanService.getSign(item.vectorId)
          if(value.hasOwnProperty('rotate')){
            sign.setAngle(value.rotate)
            flag = value.save
          }
          else if(value.hasOwnProperty('scale')){
            sign.setScale(value.scale)
            flag = value.save
          }
        }
        break;
      case "upload":
        if(type == VectorType.CustomImage){
          const customImage = await customImageService.createCustomImage(value.url,{
            x:0,
            y:0
          })

          //stateService.setEventName(LayerEvents.MoveCustomImage);
          let focusItem = {
            vectorId: customImage.vectorId,
            type: VectorType.CustomImage,
          };
          stateService.setFocusItem(focusItem);
          this.showAttributes(focusItem);
        }  
        else if(type == VectorType.BgImage){
          const bgImage = await bgImageService.createBgImage(value.url)
          //stateService.setEventName(LayerEvents.MoveBgImage);
          let focusItem = {
            vectorId: bgImage.vectorId,
            type: VectorType.BgImage,
          };
          stateService.setFocusItem(focusItem);
          this.showAttributes(focusItem);
        }
        break;
    }
    if(flag){
      history.save();
    }
    //stateService.clearFocusItem();
    this.layer.renderer.autoRedraw();
  }

  showAttributes(item) {
    let type = item.type;
    let value = null;

    if(signService.isSign(type)){
      const sign = floorplanService.getSign(item.vectorId);
      if (!sign) {
        return;
      }
      value = {
          version:'2.0',
          type: type,
          rotate:sign.angle,
          scale:sign.scale
      };
    }
    else{
      switch (item.type) {
        case VectorType.Tag:
          const tag = floorplanService.getTag(item.vectorId);
          if (!tag) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              text:tag.value,
              color: tag.color,
              fontSize: tag.fontSize,
          };
          break;
        case VectorType.Table:
          const table = floorplanService.getTable(item.vectorId);
          if (!table) {
            return;
          }
          const cellIds = table.cells;
          let content = [];
          for (let i = 0; i < cellIds.length; ++i) {
            for (let j = 0; j < cellIds[i].length; ++j) {
              const cell = floorplanService.getCell(cellIds[i][j]);
              content.push({
                width: cell.width,
                height: cell.height,
                value: cell.value,
                colIndex: cell.colIndex,
                rowIndex: cell.rowIndex,
              });
            }
          }
          value = {
              version:'2.0',
              type: type,
              content: content,
          };
          break;
        case VectorType.Title:
          const title = floorplanService.getTitle();
          if (!title) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              text: title.value,
          };
          break;
        case VectorType.Compass:
          const compass = floorplanService.getCompass();
          if (!compass) {
            return;
          }
          //value = compass.angle;
          value = {
            version:'2.0',
            type: type,
            rotate:compass.angle
          };
          break;
        case VectorType.CustomImage:
          const customImage = floorplanService.getCustomImage(item.vectorId);
          if (!customImage) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              url: customImage.url,
              rotate:customImage.angle,
              ratio:customImage.ratio,
              scale:customImage.scale
          };
          break;
        case VectorType.BgImage:
          const bgImage = floorplanService.getBgImage(item.vectorId);
          if (!bgImage) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              url: bgImage.url,
              scale:bgImage.scale
          };
          break;
        case VectorType.Circle:
          const circle = floorplanService.getCircle(item.vectorId);
          if (!circle) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              color: circle.color,
          };
          break;
        case VectorType.Rectangle:
          const rectangle = floorplanService.getRectangle(item.vectorId);
          if (!rectangle) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              color: rectangle.color,
          };
          break;
        case VectorType.Wall:
          const wall = floorplanService.getWall(item.vectorId);
          if (!wall) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              color: wall.color,
          };
          break;
        case VectorType.Arrow:
          const arrow = floorplanService.getArrow(item.vectorId);
          if (!arrow) {
            return;
          }
          value = {
              version:'2.0',
              type: type,
              color: arrow.color,
          };
          break;
      }
    }
    
    this.bus.emit("showAttribute", {
      type: type,
      value: value,
    });
  }

  clearUI() {
    this.selectUI = null;
    this.bus.emit("hideAttribute");
    this.bus.emit("hideUI");
  }

  deleteItem() {
    let item = stateService.getFocusItem();
    if (item) {
      if (item.type == VectorType.Wall) {
        floorplanService.deleteWall(item.vectorId);
      } else if (item.type == VectorType.Rectangle) {
        floorplanService.deleteRectangle(item.vectorId);
      } else if (item.type == VectorType.Circle) {
        floorplanService.deleteCircle(item.vectorId);
      } else if (item.type == VectorType.Arrow) {
        floorplanService.deleteArrow(item.vectorId);
      } else if (item.type == VectorType.Icon) {
        iconService.deleteIcon(item.vectorId);
      } else if (item.type == VectorType.Tag) {
        floorplanService.deleteTag(item.vectorId);
      } else if (item.type == VectorType.Table) {
        floorplanService.deleteTable(item.vectorId);
      } else if (signService.isSign(item.type)) {
        floorplanService.deleteSign(item.vectorId);
      } else if (item.type == VectorType.WallCorner) {
        wallService.deleteWallCorner(item.vectorId);
      } else if (item.type == VectorType.CustomImage) {
        floorplanService.deleteCustomImage(item.vectorId);
      } else if (item.type == VectorType.BgImage) {
        floorplanService.deleteBgImage();
      }
      history.save();
      this.layer.renderer.autoRedraw();
    }
  }

  getSignTypeForUI() {
    if (this.selectUI == UIEvents.Cigaret) {
      return VectorType.Cigaret;
    } else if (this.selectUI == UIEvents.FirePoint) {
      return VectorType.FirePoint;
    } else if (this.selectUI == UIEvents.LeftFootPrint) {
      return VectorType.LeftFootPrint;
    } else if (this.selectUI == UIEvents.RightFootPrint) {
      return VectorType.RightFootPrint;
    } else if (this.selectUI == UIEvents.LeftShoePrint) {
      return VectorType.LeftShoePrint;
    } else if (this.selectUI == UIEvents.RightShoePrint) {
      return VectorType.RightShoePrint;
    } else if (this.selectUI == UIEvents.FingerPrint) {
      return VectorType.FingerPrint;
    } else if (this.selectUI == UIEvents.DeadBody) {
      return VectorType.DeadBody;
    } else if (this.selectUI == UIEvents.BloodStain) {
      return VectorType.BloodStain;
    }
  }

  exportJSON() {
    const json = {
      version: floorplanData.version,
      floors: floorplanData.floors,
      currentId: floorplanService.getCurrentId(),
    };
    return json;
  }

  exportImg(canvas,filename, callback){
    coordinate.setRatio(3)
    canvas.width = canvas.width * coordinate.ratio
    canvas.height = canvas.height * coordinate.ratio
    stateService.clearItems();
    this.layer.renderer.autoRedrawForImg()
    setTimeout(() => {
      // let blobImg = this.downloadCadImg(canvas, filename)
      // // 完成callback传出blob  
      // callback(blobImg)
      canvas.toBlob(callback, 'image/jpeg', 1)
      
      canvas.width = canvas.width / coordinate.ratio
      canvas.height = canvas.height / coordinate.ratio
      coordinate.setRatio(1)
      this.layer.renderer.autoRedraw()
    },100)

  }

  downloadCadImg(canvas, filename) {
    
    // 图片导出为 png 格式
    var type = "image/png";
    var imgData = canvas.toDataURL(type, 1);

    //let blobImg = this.base64ToBlob(imgData);
    

    // 加工image data，替换mime type
    // let blobImg  = imgData.replace(this._fixType(type), 'image/octet-stream')
    // console.log(imgData)
    return imgData;
    // download
    //this.saveFile(imgData, filename)
  }

  saveFile(data, filename) {
    var save_link = document.createElementNS(
      "http://www.w3.org/1999/xhtml",
      "a"
    );
    save_link.href = data;
    save_link.download = filename;

    var event = document.createEvent("MouseEvents");
    event.initMouseEvent(
      "click",
      true,
      false,
      window,
      0,
      0,
      0,
      0,
      0,
      false,
      false,
      false,
      false,
      0,
      null
    );
    save_link.dispatchEvent(event);
  }

  _fixType(type) {
    type = type.toLowerCase().replace(/jpg/i, "jpeg");
    var r = type.match(/png|jpeg|bmp|gif/)[0];
    return "image/" + r;
  }

  base64ToBlob(base64) {
    let arr = base64.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  //截图
  menu_screenShot(fileName) {
    // this.menu_flex();
    // this.layer.stopAddVector()
    // setTimeout(function(){
    //     this.downloadCadImg(this.layer.canvas,fileName)
    // }.bind(this),100)

    this.layer.stopAddVector();
    return this.downloadCadImg(this.layer.canvas, fileName);
  }

  menu_flex() {
    coordinate.reSet();
    this.layer.renderer.autoRedraw();
  }

  initTopTable(value) {
    let center = {
      x: 770,
      y: 250,
    };
    center = coordinate.getXYFromScreen(center);
    let table = tableService.createTable(center);
    table.setValue(value);
    this.layer.renderer.autoRedraw();
  }

  initDownTable(value) {
    let center = {
      x: 770,
      y: 520,
    };
    center = coordinate.getXYFromScreen(center);
    let table = tableService.createTable(center);
    table.setValue(value);
    this.layer.renderer.autoRedraw();
  }
  /******************************************************************************************************************************************************************/
}
