import { ReportPanel, PropsPanel, Tree } from "./report/view";
import { XMLOperate, Api } from "./utility";
import Modal from "./report/view/Modal";
class ReportApp {
  constructor(canvas, container) {
    this.canvas = canvas;
    this.report = null;
    this.container = container;
    this.iscriptBool = true;
    this.CodeMirrorEditor;
  }

  Init() {
    if (this.canvas.getContext) {
      // const $contentId = $("#contentId");

      this.initReportPanel(this.canvas);

      if (params.reportId ) {
        //xh contentId的value值用来保存报表文件id
        const fileId = params.reportId;

        const xml = this.getXMLConf(fileId);

        if (xml) {
          this.XMLOperate(xml);
        }
      }

      this.initPropsPanel($("#propsBoard"));
      this.initTreeView($("#tree"));
      this.bindEvent();
    } else {
      throw new Error("context is not exist");
    }
  }

  XMLOperate(xml) {
    const parse = new DOMParser();
    const xmldoc = parse.parseFromString(xml, "text/xml");
    console.log(xmldoc);
    new XMLOperate(xmldoc, this.report).parserXML();
    this.canvas.width = this.report.width;
    this.report.resetChunkBaseline();
    this.report.paint();
  }

  initReportPanel(canvas) {
    if (canvas) {
      this.report = new ReportPanel(canvas);
      this.report.myId = $("#parentId").val();
      this.report.init();
      //console.log(this.report)
    }
  }

  initPropsPanel($container) {
    const propsPanel = PropsPanel.getInstance();

    propsPanel.init({ container: $container, report: this.report || null });
  }

  renderPropsPanel() {
    const propsPanel = PropsPanel.getInstance();

    propsPanel.render();
  }

  initTreeView($container) {
    const tree = Tree.getInstance();

    tree.init({ container: $container, report: this.report || null });
  }

  renderTreeView() {
    const tree = Tree.getInstance();

    tree.render();
  }

  getReportBasicConf() {
    const api = new Api();
    const report = this.report;

    if (report && report.getProp("queryString") == params.dataSourceSqlScript) {
      return false;
    } else {
      params.data = {
        "scriptString": params.dataSourceSqlScript
      }
      return api.getReportBasicConf(params);
    }
  }

  getXMLConf(fileId) {
    const api = new Api();

    return api.getXMLConf(fileId);
  }

  isOpenDefaultStyle() {
    return this.report.isOpenDefaultStyle();
  }
  bindEvent() {
    const $container = $(this.container);
    const that = this;
    const report = this.report;
    const $component = $container.find("#component");
    const $diagramFlow = $container.find("#diagramFlow");
    const $saveBtn = $("#save_btn");
    const $dynaprinter = $("[name='dynaprinter']");
    const $span_tab1 = $("#span_tab1");
    const $span_tab2 = $("#span_tab2");
    const $checkSqlScript = $("#checkSqlScript"); //用于检测数据源swl语句是否合法（是否可以从数据源拿到数据）
    $checkSqlScript.on("click", function () {
      let api = new Api();
      // const name = $("#content_dataSourceName").val();
      // const sql = $("#content_dataSourceSqlScript").val();
      // const appId = $("#applicationId").val();
      let result = api.getReportBasicConf();

      if (typeof result == "object" && result["error"]) {
        //alert(result['error']);
        alert("测试失败，请检查sql语句");
        return false;
      } else if (result && result["success"]) {
        alert("测试成功");
      }
    });
    //console.log($dynaprinter)
    $diagramFlow.on("click", e => {
      //console.log($diagramFlow,e.target)
      if ($(e.target).attr("id") == "diagramFlow") {
        report.clearCurrToEdit();
      }

      that.renderPropsPanel();

      e.stopPropagation();
      return false;
    });
    $("#showCode").on("click", e => {
      if(report.toXML() == 'haveNoChunkElement'){
        $("#showCode").removeAttr('data-toggle')
      }else{
        $("#showCode").attr('data-toggle', 'modal')
        new Modal(e.target, $("#xmlText"), report).render();
      }
    });

    $saveBtn.on("click", e => {
      params.subReportId=""
      // if(report.canvasHeightError){
      //     alert("画布高度必须小于换页高度，请合理分配各区域高度")
      //     return false;
      // }
      let data={};
      const reportName = $("#content_name").val();
      report.setProps({ reportName: reportName });
      const xmlString = report.toXML();
      if (xmlString == "chartNoData") {
        // alert("请为图表指定数据");
        data={
          result:'chartNoData',
        }
        params={...data}
        return false;
      } else if (xmlString == "haveNoChunkElement") {
        alert("请将区域中未放置正确的组件重新放置")
        data={
          result:'haveNoChunkElement',
        }
        params={...data}
        return false;
      } else if (xmlString == "haveGroupNoName") {
        data={
          result:'haveGroupNoName',
        }
        params={...data}
        // alert("请为分组设置名称");
        return false;
      }
      console.log(xmlString);
      //const reportName = report.getProp('reportName');
      const style = that.isOpenDefaultStyle();
      const $jrxmlString = $("#jrxmlString");
      const $contentName = $("#content_name");
      const $subReportId = $("#subReportId");

      const $isDefaultStyle = $("#isDefaultStyle");
      const $scriptTemplate = $("#code");
      const $templateType = $("#templateType");
      //console.log($scriptTemplate.val())
      // console.log(reportName)
      if (
        reportName == "" ||
        reportName == "/" ||
        !reportName ||
        reportName == "undefined" ||
        reportName == "null"
      ) {
        alert("报表名称不能为空！");
        return false;
      } else {
        $jrxmlString.val(xmlString);
        $contentName.val(reportName);
        $isDefaultStyle.val(style);
        $subReportId.val(params.subReportId);

        const dateSourceType = $("#dateSourceType").val();

        const reportId = $("#content.id").val();
        if (dateSourceType == "DATASOURCE_TYPE_VIEW") {
          if ($contentName == "") {
            alert("请填写名称");
            return false;
          } else {
          }
        } else if (dateSourceType == "DATASOURCE_TYPE_SQL") {
          // //重新获取field的字段
          // const name = $("#content_dataSourceName").val();
          // const sql = $("#content_dataSourceSqlScript").val();
          // const applicationId = $("#applicationId").val();
          if (params.dataSourceName == "" || params.dataSourceSqlScript == "") {
            alert("请选择数据源并且填写查询sql");
            return false;
          } else {
            var result = that.getReportBasicConf();

            if (typeof result == "object" && result["error"]) {
              alert(result["error"]);
              return false;
            } else if (result && result["success"]) {
              // const sql = $("#content_dataSourceSqlScript").val();

              report.handleBasicConf(result["success"]);

              report.setProps({ queryString: params.dataSourceSqlScript });
              that.renderTreeView();
            } else {
            }
          }
        }
        if ($("#xmltemplate").css("display") !== "none") {
          $templateType.val("JRXML");
        } else {
          $templateType.val("SCRIPT");
        }
        //console.log($dynaprinter.submit())
        // $dynaprinter.submit();
        data={
          name:$contentName.val(),
          jrxmlString:$jrxmlString.val(),
          isDefaultStyle:$isDefaultStyle.val(),
          subReportId:$subReportId.val(),
          templateType:$templateType.val(),
          xmlTemplate:$scriptTemplate.val(),
          parentId:$("#s_module").val(),
          scriptTemplate:$("#code").val(),
          reportExampleName:$("#reportExampleName").val(),
          result:true,
        }
        // debugger
        params={...data}
        return true;
      }
    });

    $component.on("click", e => {
      return false;
    });

    $component.on("mousedown", "#staticText", () => {
      report.addStaticText();
    });

    $component.on("mousedown", "#textField", () => {
      report.addTextField();
    });

    $component.on("mousedown", "#line", () => {
      report.addLine();
    });

    $component.on("mousedown", "#rectangle", () => {
      report.addRectangle();
    });

    $component.on("mousedown", "#ellipse", () => {
      report.addEllipse();
    });
    //console.log($component.find("#uploadImage"))
    //<input id="uploadImage" style="display:none" class='btn btn-default' type="file" accept="image/jpg, image/png, image/gif" value="Image">
    $component.on("mousedown", "#image", () => {
      let uploadImage = $("#uploadImage");
      report.addImage(uploadImage);
      // console.log(uploadImage[0].files)
    });
    $component.on("mousedown", "#CurrentDate", () => {
      report.addCurrentDate();
    });
    $component.on("mousedown", "#PageNumber", () => {
      report.addPageNumber();
    });
    $component.on("mousedown", "#Chart", () => {
      report.addChart();
    });
    $component.on("mousedown", "#SubReport", () => {
      report.addSubReport();
    });
    $component.on("mouseup", "#SubReport", () => {
      report.delElement();
    });
    $component.on("mouseup", "#Chart", () => {
      report.delElement();
    });
    $component.on("mouseup", "#CurrentDate", () => {
      report.delElement();
    });
    $component.on("mouseup", "#PageNumber", () => {
      report.delElement();
    });
    $component.on("mouseup", "#image", () => {
      report.delElement();
    });
    $component.on("mouseup", "#staticText", e => {
      report.delElement();
    });

    $component.on("mouseup", "#textField", e => {
      report.delElement();
    });

    $component.on("mouseup", "#line", e => {
      report.delElement();
    });

    $component.on("mouseup", "#ellipse", e => {
      report.delElement();
    });

    $component.on("mouseup", "#rectangle", e => {
      report.delElement();
    });

    $span_tab1.off("click").on("click", e => {
      $("#showCode").hide();
      $("#preview_btn").hide();
      $span_tab2.removeClass("span_tabCheck");
      $span_tab1.addClass("span_tabCheck");
      $("#1").css("display", "table-row");
      $("#2").css("display", "none");
    });

    $span_tab2.off("click").on("click", e => {
      const sql = $("#content_dataSourceSqlScript").val();

      report.handleBasicConf(params.fields);

      report.setProps({ queryString: sql });
      const reportName = $("#content_name").val();
      report.setProps({ reportName: reportName });
      that.renderTreeView();
      
      e.stopPropagation();
      if ($("#templateType").val() == "SCRIPT") {
        $("#reportExampleName").val(params.reportExampleName);
        $(".scriptDivDemoConSecInp").each(function () {
          if ($(this).prop("id") == params.reportExampleName) {
            $(this).prop("checked", true);

          } else {
            $(this).prop("checked", false);
          }
        })
        $("#xmltemplate").css("display", "none");
        $("#scripttemplate").css("display", "block");
        if ($(".CodeMirror").length == 0) {
          var myTextarea = document.getElementById("code");
          var myTextareaV = document.getElementById("code").value;

          that.CodeMirrorEditor = CodeMirror.fromTextArea(myTextarea, {
            mode: "javascript", //编辑器语言
            lineNumbers: true, //显示行号
            autofocus: true //初始化时自动获取焦点
          });
          if (myTextareaV) {
            that.CodeMirrorEditor.setValue(myTextareaV);
          }

          setTimeout(function () {
            that.CodeMirrorEditor.refresh();
          }, 1);
          window.top.CodeMirrorEditor = that.CodeMirrorEditor;
          $("#frontSize").change(function () {
            var codeFontSize = $("#frontSize option:selected").val();
            var cssfontSize = $(".CodeMirror").css("font-size");
            var unit = cssfontSize.slice(-2);
            var fontSize = codeFontSize;
            $(".CodeMirror").css("font-size", fontSize + unit);
          });
          $(".scriptDivDemoConSec").each(function () {
            $(this).on("click", function () {
              $(this)
                .siblings()
                .each(function () {
                  $(this)
                    .find("input")
                    .prop("checked", "false");
                });
              $(this)
                .find("input")
                .prop("checked", "true");
            });
          });
        }
      } else {
        $("#xmltemplate").css("display", "block");
        $("#scripttemplate").css("display", "none");
      }

    });
    
    $(".undo").on("click", function () {
      that.CodeMirrorEditor.undo();
    });
    $(".redo").on("click", function () {
      that.CodeMirrorEditor.redo();
    });
  }
}

export const render = (canvas, container) => {
  new ReportApp(canvas, container).Init();
};
