/* eslint-disable quotes */
import { systemList } from "./system";
// import { DwHttpApiInterceptor } from "@webdpt/framework/http";
/* eslint-disable quotes */
import {
  AfterViewInit,
  Component,
  ElementRef,
  OnInit,
  Renderer2,
} from "@angular/core";
import {
  DigiMiddlewareAuthApp
} from "app/config/app-auth-token";
import { CommonService } from "../service/common.service";
import { NzMessageService } from "ng-zorro-antd/message";
import { tr } from "date-fns/locale";
import { NzModalService } from "ng-zorro-antd/modal";


@Component({
  selector: "app-layout",
  templateUrl: "./layout.component.html",
  styleUrls: ["./layout.component.less"],
})
export class LayoutComponent implements OnInit, AfterViewInit {
  // 登出： https://iam-test.digiwincloud.com.cn/api/iam/v2/identity/logout
  systemMaps = {};
  queryDisplayList = [];
  USER_ID = "";

  USER_TOKEN = "";

  dragEnable: boolean = false;

  isDragging: boolean = false;

  isDownloadVisible: boolean = false;

  layoutUsers = [
    "digiwin0001",
    "digiwin0002",
    "digiwin0003",
    "digiwin0004",
    "digiwin0005",
    "default",
    "M00020",
    "digiwin0006",
    "digiwin0007",
    "digiwin0008",
    "digiwin0009",
    "digiwin0010",
    "dongsk@digiwin.com",
  ];

  divContent = {
    sysId: "",
    top: "",
    left: "",
    height: "",
    width: "",
    userId: "default",
    tenantId: "",
    topPercent: "",
    leftPercent: "",
    heightPercent: "",
    widthPercent: "",
  };

  constructor(
    private commonService: CommonService,
    private el: ElementRef,
    private renderer: Renderer2,
    private message: NzMessageService,
    private modalService: NzModalService
  ) { }
  ngOnInit(): void {
    this.systemMaps = systemList;
    this.initSystemBySemcSSO();
  }

  ngAfterViewInit() {
    // const divElement = this.el.nativeElement.querySelector('.layout-body');
  }

  /**
   * 通过请求queryDisplayList接口登录
   */
  initSystemBySemcSSO() {
    const DwUserInfo = JSON.parse(sessionStorage.getItem("DwUserInfo"));
    this.USER_TOKEN = DwUserInfo.token;
    this.USER_ID = DwUserInfo.userId;
    this.dragEnable = this.USER_ID === "dongsk@digiwin.com" || this.USER_ID === "M00020";

    console.log(this.dragEnable);

    const headers = {
      "Digi-Middleware-Auth-App": DigiMiddlewareAuthApp,
      "Digi-Middleware-Auth-User": this.USER_TOKEN,
    };
    const url =
      this.commonService.semcUrl + "/tenant/semc/applink/queryDisplayList";
    this.commonService
      .getRequestWithHeaders(url, headers)
      .then((res) => {
        if (res && res.response) {
          this.queryDisplayList = res.response;
          this.queryDisplayList.forEach((item) => {
            this.systemMaps["SSO_" + item.id] = {
              key: item.id,
              id: item.id,
              title: item.name,
              mockLogin: false,
              ssoLogin: true,
              callBackUrl: item.callBackUrl,
              url: item.cloudwebsite,
              applicationAppId: item.applicationAppId,
            };

            // 非管理员加载
            this.divContent.userId = this.USER_ID;
            if (
              this.USER_ID === "dongsk@digiwin.com" ||
              this.USER_ID === "M00020"
            ) {
              this.divContent.userId = "default";
            }
          });
        }

        // 初始化布局
        this.initSysLayout();
        console.log("systemMaps", this.systemMaps);
      })
      .catch((error) => console.error(error));
  }

  initSysLayout() {
    if (!this.layoutUsers.includes(this.divContent.userId)) {
      return;
    }
    const DwUserInfo = JSON.parse(sessionStorage.getItem("DwUserInfo"));
    this.commonService
      .postWithHeaders(
        this.commonService.apiUrl +
        "/restful/standard/demo/api/517/config/list",
        {
          userId: this.divContent.userId,
          tenantId: DwUserInfo.tenantId,
          sysId: "",
        },
        {
          "Digi-Middleware-Auth-App": DigiMiddlewareAuthApp,
          "Digi-Middleware-Auth-User": this.USER_TOKEN,
        }
      )
      .then((res) => {
        if (res && res.response) {
          res.response.forEach((item) => {
            // console.log(item);
            const sysEL = this.el.nativeElement.querySelector("#" + item.sysId);
            // this.renderer.setStyle(sysEL, 'top', item.top);
            // this.renderer.setStyle(sysEL, 'left', item.left);
            // this.renderer.setStyle(sysEL, 'width', item.width);
            // this.renderer.setStyle(sysEL, 'height', item.height);
            if (sysEL != null) {
              this.renderer.setStyle(sysEL, "top", item.topPercent);
              this.renderer.setStyle(sysEL, "left", item.leftPercent);
              this.renderer.setStyle(sysEL, "width", item.widthPercent);
              this.renderer.setStyle(sysEL, "height", item.heightPercent);
              // this.renderer.setStyle(sysEL, "background-color", 'wheat');

              this.renderer.setStyle(sysEL, "display", 'block');
            }
          });
        }
      });
  }

  jumpToSystem(key: string) {
    const DwUserInfo = JSON.parse(sessionStorage.getItem("DwUserInfo"));

    if (
      DwUserInfo.userId === "dongsk@digiwin.com" ||
      DwUserInfo.userId === "M00020"
    ) {
      return;
    }

    if (key === 'download') {
      this.isDownloadVisible = true;
      return;
    }

    if (this.systemMaps[key] == null) {
      this.message.error(`${key} 未集成`);
      return;
    }

    const item = this.systemMaps[key];

    // 免密跳转
    if (item.linkLogin) {
      window.open(item.url, "_blank");
      return;
    }

    const headers = {
      "Digi-Middleware-Auth-App": DigiMiddlewareAuthApp,
      "Digi-Middleware-Auth-User": this.USER_TOKEN,
    };

    // 单点登录
    if (item.ssoLogin) {
      this.commonService
        .postWithHeaders(
          this.commonService.iamUrl + "/api/iam/v2/oauth2/authorize",
          {
            appId: item.applicationAppId,
            callbackUrl: item.callBackUrl,
          },
          headers
        )
        .then((res) => {
          if (res && res.data && res.data.code) {
            window.open(item.url + "&code=" + res.data.code);
          }
        });
      return;
    }

    // 模拟登录
    if (item.mockLogin) {
      this.commonService
        .postWithHeaders(
          this.commonService.apiUrl +
          "/restful/standard/demo/api/default/login",
          {
            userId: DwUserInfo.userId,
            tenantId: DwUserInfo.tenantId,
            productKey: item.id,
          },
          headers
        )
        .then((res) => {
          if (res && res.response) {
            window.open(
              item.url + "/sso-login?userToken=" + res.response.user_token
            );
          }
        });
    } else {
      // 切换租户登录
      this.commonService
        .postWithHeaders(
          this.commonService.iamUrl +
          "/api/iam/v2/identity/token/refresh/tenant",
          { tenantSid: item.sid },
          headers
        )
        .then((res) => {
          if (res) {
            window.open(item.url + "/sso-login?userToken=" + res.user_token);
          }
        });
    }
  }

  handleElementDrag(data: any) {
    // console.log(data);

    if (data.type === "mousedown") {
      this.isDragging = true;
      this.divContent.height = data.height;
      this.divContent.width = data.width;
      this.divContent.top = data.top;
      this.divContent.left = data.left;
      this.divContent.sysId = data.id;
    }

    if (data.type !== "mouseup") {
      return;
    }

    if (data.left === "" || data.top === "") {
      return;
    }

    const DwUserInfo = JSON.parse(sessionStorage.getItem("DwUserInfo"));

    this.divContent.sysId = data.id;
    this.divContent.top = data.top;
    this.divContent.left = data.left;
    this.divContent.height = data.height;
    this.divContent.width = data.width;
    this.divContent.tenantId = DwUserInfo.tenantId;

    console.log(this.divContent);
    // this.commonService.postWithHeaders(this.commonService.apiUrl + "/restful/standard/demo/api/517/config/save",
    //   divContentX,
    //   {
    //     "Digi-Middleware-Auth-App": DigiMiddlewareAuthApp,
    //     "Digi-Middleware-Auth-User": DigiMiddlewareAuthUser,
    //   }
    // ).then(res => {
    //   if (res && res.response) {
    //     alert('sucess!');
    //   }
    // });
    this.isDragging = false;
  }

  changeDiv(type: String) {
    const sysEL = this.el.nativeElement.querySelector(
      "#" + this.divContent.sysId
    );
    if (sysEL === null) {
      return;
    }
    if (type === "W") {
      this.renderer.setStyle(sysEL, "width", this.divContent.width);
    }
    if (type === "H") {
      this.renderer.setStyle(sysEL, "height", this.divContent.height);
    }
  }

  save() {
    if (!this.layoutUsers.includes(this.divContent.userId)) {
      return;
    }

    if (
      this.divContent.left === "" ||
      this.divContent.top === "" ||
      this.divContent.sysId === "" ||
      this.divContent.width === "" ||
      this.divContent.height === ""
    ) {
      return;
    }

    // 计算百分比
    const windowWidth: number = window.innerWidth;
    const windowHeight: number = window.innerHeight;

    const top = parseFloat(this.divContent.top.replace("px", ""));
    const left = parseFloat(this.divContent.left.replace("px", ""));
    const width = parseFloat(this.divContent.width.replace("px", ""));
    const height = parseFloat(this.divContent.height.replace("px", ""));

    this.divContent.topPercent =
      (Number((top / windowHeight).toFixed(4)) * 100).toString() + "%";
    this.divContent.leftPercent =
      (Number((left / windowWidth).toFixed(4)) * 100).toString() + "%";
    this.divContent.widthPercent =
      (Number((width / windowWidth).toFixed(4)) * 100).toString() + "%";
    this.divContent.heightPercent =
      (Number((height / windowHeight).toFixed(4)) * 100).toString() + "%";

    console.log("--save--divContent--", this.divContent);

    this.commonService
      .postWithHeaders(
        this.commonService.apiUrl +
        "/restful/standard/demo/api/517/config/save",
        this.divContent,
        {
          "Digi-Middleware-Auth-App": DigiMiddlewareAuthApp,
          "Digi-Middleware-Auth-User": this.USER_TOKEN,
        }
      )
      .then((res) => {
        if (res && res.response) {
          alert("sucess!");
          this.divContent.sysId = "";
        }
      });
  }

  handleModelCancel() {
    this.isDownloadVisible = false;
  }
}
