import { linearRegressionScatterChart, CATEGORIES } from "../../configuration/constants";
import { echartsBasicListen } from "../../feature/traits/common";
import { throttle } from "../../utils";

export default {
  // 组件名称
  name: linearRegressionScatterChart,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${linearRegressionScatterChart}" class="${linearRegressionScatterChart}"></div>
    `;
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${linearRegressionScatterChart} {
          position: absolute;
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: transparent;
          padding: 10px;
          width: 600px;
          height: 400px;
        }
      </style>
    `;
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
      <svg t="1598004370606" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11048" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M131.12 825.647l758.74-654.903 14.506 16.805-758.74 654.903z" p-id="11049" fill="#1890ff"></path><path d="M200.333 920.59L817.65 130.98l17.489 13.673-617.317 789.612zM775.7 642.4c-0.4 0.9-1.5 1.3-2.4 0.9M0 0h82v1024H0z" p-id="11050" fill="#1890ff"></path><path d="M1024 942v82H0v-82zM542 130h82v82h-82zM794 331h82v82h-82zM425.86 265.915l73.21 36.933-36.933 73.21-73.21-36.934zM772.86 506.904l73.209 36.933-36.933 73.21-73.21-36.934zM173.744 444.44l72.8-37.737 37.736 72.8-72.8 37.736zM511.74 625.417l72.799-37.736 37.736 72.8-72.8 37.736zM187.12 560.476l69.405 43.673-43.673 69.405-69.405-43.673zM406.117 794.486l69.405 43.673-43.673 69.405-69.405-43.673z" p-id="11051" fill="#1890ff"></path></svg>
        <div class="gjs-block-label">线性回归散点图</div>
      `,
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: "线性回归散点图",
      icon: "globe",
      docUrl:
        "https://www.yuque.com/docs/share/33c150c8-6f7f-4485-a24a-9b58989e022f#",
      author: '宗介',
      email: 'zongjie.wxt@xuelangyun.com',
      inPorts: [
        {
          uuid: "in1",
          subType: "json",
          description: {
            zh_CN: "输入数据",
          },
        },
        {
          uuid: "in2",
          subType: "all",
          description: {
            zh_CN: "输入架次信息",
          },
        },
        {
          uuid: "in3",
          subType: "all",
          description: {
            zh_CN: "loading",
          },
        },
      ],
      outPorts: [
        {
          uuid: 'out1',
          subType: 'json',
          description: {
            zh_CN: '请求数据'
          }
        },
        {
          uuid: 'out2',
          subType: 'all',
          description: {
            zh_CN: '控制报警'
          }
        }
      ]
    };
  },

  // 组件属性
  componentOptions() {
    return {
      name: linearRegressionScatterChart,
      resizable: true,
      dmode: "absolute",
      droppable: false,
      traits: [
        {
          name: "xAxisName",
          label: "x轴名称",
          changeProp: 1,
        },
        {
          name: "yAxisName",
          label: "y轴名称",
          changeProp: 1,
        },
        {
          name: "xAxisColor",
          label: "X坐标轴颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "yAxisColor",
          label: "Y坐标轴颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "axisLineType",
          label: "坐标轴线类型",
          type: "select",
          changeProp: 1,
          options: [
            { id: "solid", name: "实线" },
            { id: "dashed", name: "虚线" },
            { id: "dotted", name: "点线" },
          ],
        },
        {
          name: 'xAxisWidth',
          label: 'X坐标轴宽度',
          changeProp: 1
        },
        {
          name: 'yAxisWidth',
          label: 'Y坐标轴宽度',
          changeProp: 1
        },
        {
          name: "xAxisTick",
          label: "x轴刻度线",
          changeProp: 1,
          type: "checkbox",
        },
        {
          name: "yAxisTick",
          label: "y轴刻度线",
          changeProp: 1,
          type: "checkbox",
        },
        {
          name: 'xAxisTickWidth',
          label: 'X轴刻度线宽度',
          changeProp: 1
        },
        {
          name: 'yAxisTickWidth',
          label: 'Y轴刻度线宽度',
          changeProp: 1
        },
        {
          name: 'xAxisTickColor',
          label: 'x轴刻度线颜色',
          changeProp: 1,
          type: 'color'
        }, 
        {
          name: 'yAxisTickColor',
          label: 'y轴刻度线颜色',
          changeProp: 1,
          type: 'color'
        }, 
        {
          name: 'xAxisSplitLine',
          label: 'x轴分割线',
          changeProp: 1,
          type: 'checkbox'
        }, 
        {
          name: 'yAxisSplitLine',
          label: 'y轴分割线',
          changeProp: 1,
          type: 'checkbox'
        },
        {
          name: 'axisSplitLineColor',
          label: '分割线颜色',
          changeProp: 1,
          type: 'color'
        }, 
        {
          name: 'axisSplitLineType',
          label: '分割线类型',
          changeProp: 1,
          type: 'select',
          options: [
            { id: "solid", name: "实线" },
            { id: "dashed", name: "虚线" },
            { id: "dotted", name: "点线" },
          ],
        },
        {
          name: "gridPadding",
          label: "容器边距(左,上,右,下)",
          changeProp: 1,
        },
        {
          name: "xLabelRotate",
          label: "x轴标签旋转",
          changeProp: 1,
          type: "number",
        },
        {
          name: "markPointerDataValue",
          label: "标签文字",
          changeProp: 1,
        },
        {
          type: 'number',
          name: 'markPointerFontSize',
          label: '标签字号',
          changeProp: 1,
          min: 10,
          step: 1
        },
        {
          name: 'markPointTagOffset',
          label: '标注偏移(左,上)',
          changeProp: 1,
        },
        {
          name: 'markPointLabelPos',
          label: '标签位置(左,上)',
          changeProp: 1,
        },
        {
          name: 'markPointTagSize',
          label: '标注大小(宽,高)',
          changeProp: 1,
        },
        {
          name: 'markPointTriangleSize',
          label: '三角形大小(宽,高)',
          changeProp: 1,
        },
        {
          name: 'markPointTriangleOffset',
          label: '三角形偏移(左,上)',
          changeProp: 1,
        },
        {
          name: 'markPointRectSize',
          label: '矩形大小(宽,高)',
          changeProp: 1,
        },
        {
          name: 'markPointRectOffset',
          label: '矩形偏移(左,上)',
          changeProp: 1,
        },
        {
          name: "standardLineType",
          label: "阈值线类型",
          type: "select",
          changeProp: 1,
          options: [
            { id: "solid", name: "实线" },
            { id: "dashed", name: "虚线" },
            { id: "dotted", name: "点线" },
          ],
        },
        {
          name: "standardLineWidth",
          label: "阈值线宽度",
          changeProp: 1,
          type: "number",
        },
        {
          name: "trendLineWidth",
          label: "线宽度",
          changeProp: 1,
          type: "number",
        },
        {
          name: "warningColor",
          label: "报警颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "symbol",
          label: "节点类型",
          type: "select",
          changeProp: 1,
          options: [
            { id: "emptyCircle", name: "空心圆" },
            { id: "circle", name: "圆形" },
            { id: "rect", name: "矩形" },
            { id: "roundRect", name: "圆角矩形" },
            { id: "triangle", name: "三角形" },
            { id: "diamond", name: "菱形" },
            { id: "pin", name: "大头针" },
            { id: "arrow", name: "箭头" },
            { id: "none", name: "无" },
          ],
        },
        {
          name: "symbolSize",
          label: "节点大小",
          changeProp: 1,
          type: "number",
          min: 1,
          step: 1,
        },
        {
          name: "currengFlightNodeColor",
          label: "当前航班高亮颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "currengFlightNodeSize",
          label: "当前航班节点大小",
          changeProp: 1,
          type: "number",
        },
        {
          name: "currengFlightLineWidth",
          label: "当前航班线宽",
          changeProp: 1,
          type: "number",
        },
        {
          name: "zoomHeight",
          label: "缩放区高度",
          changeProp: 1,
          type: "number",
        },
        {
          name: "zoomBottom",
          label: "缩放区边距(下)",
          changeProp: 1,
          type: "number",
        },
        {
          name: "zoomHandleColor",
          label: "手柄图形颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "zoomTextColor",
          label: "缩放区字体颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "zoomFillerColor",
          label: "选中范围填充色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "backgroundLineColor",
          label: "阴影线条颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "backgroundAreaColor",
          label: "阴影填充色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "zoomBackgroundColor",
          label: "缩放区背景颜色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "zoomBorderColor",
          label: "缩放区边框色",
          changeProp: 1,
          type: "color",
        },
        {
          name: "zoomStart",
          label: "放大镜开始(%)",
          changeProp: 1,
          type: "number",
        },
        {
          name: "zoomEnd",
          label: "放大镜结束(%)",
          changeProp: 1,
          type: "number",
        },
        {
          name: 'customDimessions',
          label: '自定义维度',
          changeProp: 1
        },
        {
          name: "tooltipHideDimessions",
          label: "提示框隐藏维度",
          changeProp: 1
        },
        {
          name: 'thresholdMaxKey',
          label: '阈值上限字段',
          changeProp: 1
        },
        {
          name: 'thresholdMinKey',
          label: '阈值下线字段',
          changeProp: 1
        },
        {
          name: 'markPointKey',
          label: '换件点字段',
          changeProp: 1
        },
        {
          name: 'dataListKey',
          label: '图表数据字段',
          changeProp: 1
        },
        {
          name: 'xKey',
          label: 'X维度字段',
          changeProp: 1
        },
        {
          name: 'scatterKey',
          label: 'Y维度(散点)字段',
          changeProp: 1
        },
        {
          name: 'regressionKey',
          label: 'Y维度(线)字段',
          changeProp: 1
        },
        {
          name: 'feijiIdKey',
          label: ' 航班id字段',
          changeProp: 1
        },{
          name: 'alertKey',
          label: '报警参数字段',
          changeProp: 1
        },
        {
          name: 'tailnumber',
          label: '飞机尾号参数字段',
          changeProp: 1
        },
        {
          name: 'engine',
          label: '发动机参数字段',
          changeProp: 1
        },
        {
          name: 'needEngine',
          label: '是否传发动机参数',
          changeProp: 1,
          type: 'checkbox'
        },
        {
          name: "engineValue",
          label: "发动机参数值",
          changeProp: 1,
          type: "number",
          min: 1,
          step: 1,
        },
        // {
        //   name: "setInterval",
        //   label: "开启定时",
        //   changeProp: 1,
        //   type: "checkbox",
        // },
      ],
      xAxisName: null,
      yAxisName: null,
      colors: '#00DDA2, #F18510, #27CAFF, #FFC20D',
      fontColor: '#9BBFEA',
      legendIcon: 'circle',
      xAxisColor: "rgba(0,169,254,1)",
      yAxisColor: "rgba(255,255,255,0)",
      xAxisWidth: 2,
      yAxisWidth: 1,
      xAxisTickWidth: 1,
      yAxisTickWidth: 1,
      axisLineType: "solid",
      standardLineType: "dotted",
      markPointerDataValue: 'M',
      markPointerFontSize: 12,
      markPointLabelPos: '10,6',
      markPointTagSize: '30,20',
      markPointTriangleSize: '12,10',
      markPointRectSize: '1,50',
      markPointTagOffset: '0,-50',
      markPointTriangleOffset: '0,-28',
      markPointRectOffset: '0,0',
      standardLineWidth: 2,
      trendLineWidth: 1,
      warningColor: "#FB1A2A",
      currengFlightNodeColor: "#ffff05",
      currengFlightLineWidth: 6,
      xAxisTick: true,
      yAxisTick: true,
      xAxisTickColor: '#00A9FE',
      yAxisTickColor: '#00A9FE',
      xAxisSplitLine: false,
      yAxisSplitLine: true,
      axisSplitLineColor: 'rgba(0,169,254,0.26)',
      axisSplitLineType: "dotted",
      gridPadding: "0,30,20,35",
      xLabelRotate: null,
      customDimessions: "时间, 左发低压转子, 分类",
      tooltipHideDimessions: '2',
      symbol: "circle",
      symbolSize: 4,
      zoomHeight: 25,
      currengFlightNodeSize: 10,
      zoomBottom: 0,
      zoomHandleColor: "#00A9FE",
      zoomTextColor: "#9BBFEA",
      zoomFillerColor: "rgba(0,169,254,0.4)",
      backgroundLineColor: "rgba(137,170,218,0.4)",
      backgroundAreaColor: "rgba(137,170,218,0)",
      zoomBackgroundColor: "rgba(137,170,218,0.23)",
      zoomBorderColor: "rgba(137,170,218,0.23)",
      zoomStart: 40,
      zoomEnd: 60,
      thresholdMinKey: '',
      thresholdMaxKey: '',
      markPointKey: '',
      dataListKey: '',
      xKey: '',
      scatterKey: '',
      regressionKey: '',
      feijiIdKey: '',
      alertKey:'',
      tailnumber: '',
      engine: '',
      needEngine: false,
      engineValue: ''
    };
  },

  onModelScript() {
    // const dataSource = "{[ dataSource ]}";
    const bgColor = "{[ bgColor ]}";
    const borderColor = "{[ borderColor ]}";
    const fontColor = "{[ fontColor ]}";
    let colors = "{[ colors ]}";
    let legendPosition = "{[ legendPosition ]}".toString();
    const legendIcon = ('{[ legendIcon ]}').toString();
    const legendOrient = "{[ legendOrient ]}".toString();
    const legendFontSize = Number('{[ legendFontSize ]}');
    const legendFontFamily = ('{[ legendFontFamily ]}').toString();
    const legendItemGap = Number('{[ legendItemGap ]}');
    const legendItemWidth = Number('{[ legendItemWidth ]}');
    const legendItemHeight = Number('{[ legendItemHeight ]}');
    const titleText = "{[ titleText ]}";
    const titleColor = "{[ titleColor ]}";
    const titlePosition = "{[ titlePosition ]}".toString();
    const xAxisName = "{[ xAxisName ]}";
    const yAxisName = "{[ yAxisName ]}";
    const xAxisColor = "{[ xAxisColor ]}";
    const yAxisColor = "{[ yAxisColor ]}";
    const xAxisWidth = "{[ xAxisWidth ]}";
    const yAxisWidth = "{[ yAxisWidth ]}";
    const xAxisTickWidth = "{[ xAxisTickWidth ]}";
    const yAxisTickWidth = "{[ yAxisTickWidth ]}";
    const axisLineType = "{[ axisLineType ]}";
    const standardLineType = "{[ standardLineType ]}";
    const markPointerDataValue = "{[ markPointerDataValue ]}";
    const markPointerFontSize = Number("{[ markPointerFontSize ]}");
    const markPointLabelPos = "{[ markPointLabelPos ]}";
    const markPointTagSize = "{[ markPointTagSize ]}";
    const markPointTriangleSize = "{[ markPointTriangleSize ]}";
    const markPointTagOffset = "{[ markPointTagOffset ]}";
    const markPointTriangleOffset = "{[ markPointTriangleOffset ]}";
    const markPointRectOffset = "{[ markPointRectOffset ]}";
    const markPointRectSize = "{[ markPointRectSize ]}";
    const standardLineWidth = "{[ standardLineWidth ]}";
    const trendLineWidth = "{[ trendLineWidth ]}";
    const warningColor = "{[ warningColor ]}";
    const currengFlightNodeColor = "{[ currengFlightNodeColor ]}";
    const currengFlightLineWidth = Number("{[ currengFlightLineWidth ]}");
    const currengFlightNodeSize = Number("{[ currengFlightNodeSize ]}");
    const xAxisTick = Boolean("{[ xAxisTick ]}");
    const yAxisTick = Boolean("{[ yAxisTick ]}");
    const xAxisTickColor = "{[ xAxisTickColor ]}";
    const yAxisTickColor = "{[ yAxisTickColor ]}";
    const xAxisSplitLine = Boolean("{[ xAxisSplitLine ]}");
    const yAxisSplitLine = Boolean("{[ yAxisSplitLine ]}");
    const axisSplitLineColor = "{[ axisSplitLineColor ]}";
    const axisSplitLineType = "{[ axisSplitLineType ]}";
    let gridPadding = "{[ gridPadding ]}";
    const xLabelRotate = "{[ xLabelRotate ]}";
    let customDimessions = "{[ customDimessions ]}";
    const tooltipHideDimessions = "{[ tooltipHideDimessions ]}";
    const symbol = "{[ symbol ]}".toString();
    const symbolSize = Number("{[ symbolSize ]}");
    const zoomHeight = Number("{[ zoomHeight ]}");
    const zoomBottom = Number("{[ zoomBottom ]}");
    const zoomHandleColor = "{[ zoomHandleColor ]}";
    const zoomTextColor = "{[ zoomTextColor ]}";
    const zoomFillerColor = "{[ zoomFillerColor ]}";
    const backgroundLineColor = "{[ backgroundLineColor ]}";
    const backgroundAreaColor = "{[ backgroundAreaColor ]}";
    const zoomBackgroundColor = "{[ zoomBackgroundColor ]}";
    const zoomBorderColor = "{[ zoomBorderColor ]}";
    const zoomStart = Number("{[ zoomStart ]}");
    const zoomEnd = Number("{[ zoomEnd ]}");
    const thresholdMinKey = "{[ thresholdMinKey ]}";
    const alertKey = "{[ alertKey ]}";
    const thresholdMaxKey = "{[ thresholdMaxKey ]}";
    const markPointKey = "{[ markPointKey ]}";
    const dataListKey = "{[ dataListKey ]}";
    const xKey = "{[ xKey ]}";
    const scatterKey = "{[ scatterKey ]}";
    const regressionKey = "{[ regressionKey ]}";
    const feijiIdKey = "{[ feijiIdKey ]}";
    const tailnumber = "{[ tailnumber ]}";
    const engine = "{[ engine ]}";
    const needEngine = Boolean("{[ needEngine ]}");
    const engineValue = Number("{[ engineValue ]}");
    let legendMap = "{[ legendMap ]}".toString();

    const defaultData = {
      thresholdMin: 0.1, // 阈值范围
      thresholdMax: 0.2,
      markPointData: ["2019-01-03 22:56:00"], // 换件点坐标
      scatterData: [ // 散点图数据
        ["2019-01-03 00:00:00", 0.37,'warning'],["2019-01-03 02:15:00", 0.15,'current'],["2019-01-03 07:18:00", 0.15,'current'],
        ["2019-01-03 09:09:00", 0.28,'warning'],["2019-01-03 22:56:00", 0.15,'normal'],["2019-01-04 01:07:00", 0.16,'normal'],
        ["2019-01-04 07:23:00", 0.21,'warning'],["2019-01-08 23:07:00", 0.28,'warning'],
      ],
      regressionData: [ // 回归数据（趋势线）
        ["2019-01-03 00:00:00", 0.22],["2019-01-03 02:15:00", 0.25],["2019-01-03 07:18:00", 0.23],
        ["2019-01-03 09:09:00", 0.21],["2019-01-03 22:56:00", 0.23],["2019-01-04 01:07:00", 0.21],
        ["2019-01-04 07:23:00", 0.20],["2019-01-08 23:07:00", 0.20]
      ],
      currFlightRegressionMarkData: [
        [
          {coord: ["2019-01-03 00:00:00", 0.22]},
          {coord: ["2019-01-03 02:15:00", 0.25]}
        ],
        [
          {coord: ["2019-01-03 02:15:00", 0.25]},
          {coord: ["2019-01-03 07:18:00", 0.23]}
        ]
      ],
      alert: '报警信息'
    };

    Boolean(bgColor)
      ? $(this).css({ backgroundColor: bgColor })
      : $(this).css({ backgroundColor: "transparent" });
    Boolean(borderColor)
      ? $(this).css({ borderColor: borderColor })
      : $(this).css({ borderColor: "transparent" });
    if (colors.indexOf(",") > -1) {
      colors = colors.split(",").map((item) => item.trim());
    } else if (Boolean(colors)) {
      colors = [colors];
    }

    colors = [ colors[0] || "#00DDA2",colors[1] || "#F18510",colors[2] || "#27CAFF",colors[3] || "#FFC20D" ]

    const grid = {
      containLabel: true,
    };
    if (gridPadding.indexOf(",") > -1) {
      gridPadding = gridPadding.split(",").map((item) => item.trim());
      grid.left = gridPadding[0];
      grid.top = gridPadding[1];
      grid.right = gridPadding[2] || gridPadding[0];
      grid.bottom = gridPadding[3] || gridPadding[1];
    } else if (Boolean(gridPadding)) {
      grid.left = gridPadding;
      grid.top = gridPadding;
      grid.right = gridPadding;
      grid.bottom = gridPadding;
    }

    const titlePositionArr = titlePosition.split(",");
    const title = {
      text: titleText,
      left: titlePositionArr[0],
      top:
        titlePosition.indexOf(",") > 0
          ? titlePositionArr[1]
          : titlePositionArr[0],
      textStyle: {
        fontSize: 16,
        color: titleColor || fontColor,
      },
    };

    const legendShow = legendOrient != "null";
    const legend = {
      show: legendShow,
      type: "scroll",
      itemGap: legendItemGap,
      itemWidth: legendItemWidth,
      itemHeight: legendItemHeight,
      textStyle: {
        fontFamily: legendFontFamily,
        fontSize: legendFontSize,
        color: fontColor,
      },

    };
    if (Boolean(legendPosition)) {
      legendPosition.split(',').forEach((item, i) => {
        if (item.indexOf(':') > 0) {
          const key = item.split(':')[0].trim();
          const value = item.split(':')[1].trim();
          legend[`${key}`] = value;
        } else {
          legend[`${i ? 'top' : 'left'}`] = item.trim();
        }
      });
    }
    if (legendShow) {
      legend.orient = legendOrient;
    } else {
      legend.show = false;
    }

    const xAxis = {
      type: "category",
      name: xAxisName,
      boundaryGap: false,
      axisTick: { show: xAxisTick, lineStyle: {color: xAxisTickColor, width: xAxisTickWidth} },
      axisLine: {
        lineStyle: {
          type: axisLineType,
          color: xAxisColor,
          width: xAxisWidth
        },
      },
      axisLabel: {
        color: fontColor,
        rotate: xLabelRotate,
      },
      splitLine: {
        show: xAxisSplitLine,
        lineStyle: {
          color: axisSplitLineColor,
          type: axisSplitLineType
        },
      },
    };
    const yAxis = {
      type: "value",
      name: yAxisName,
      axisTick: { show: yAxisTick, lineStyle: {color: yAxisTickColor, width: yAxisTickWidth} },
      axisLine: {
        lineStyle: {
          type: axisLineType,
          color: yAxisColor,
          width: yAxisWidth
        },
      },
      axisLabel: {
        color: fontColor,
      },
      splitLine: {
        show: yAxisSplitLine,
        lineStyle: {
          color: axisSplitLineColor,
          type: axisSplitLineType
        },
      },
    };

    const tooltip = {
      // trigger: 'axis',
      axisPointer: {
        type: "line",
        lineStyle: {
          color: xAxisColor,
          opacity: 0.6,
        },
      },
      formatter: function (obj) {
        if(obj.componentSubType !== 'scatter') {
          return "";
        }
        const hideDimessions = tooltipHideDimessions.split(',');
        const list = obj.value.map(function (item, i) {
          if(hideDimessions.includes(i.toString())) {
            return '';
          }
          return (
            "<br /><span style='display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:" +
            obj.color +
            "'></span>" +
            obj.dimensionNames[i] +
            ": " +
            item
          );
        });
        return obj.seriesName + list.join(" ");
      },
    };

    const dataZoom = [
      { // 滑动条型数据区域缩放组件
        show: true,
        type: "slider",
        height: zoomHeight, // 缩放区高度
        xAxisIndex: 0,
        start: zoomStart, // 放大镜开始
        end: zoomEnd, // 放大镜结束
        bottom: zoomBottom, // 缩放区边距(下侧)
        handleSize: '100%',
        handleStyle: {
          color: zoomHandleColor, //手柄图形颜色
        },
        textStyle: {
          color: zoomTextColor, // 缩放区字体颜色
        },
        fillerColor: zoomFillerColor, // 选中范围填充色
        borderColor: zoomBorderColor, // 缩放区边框色
        backgroundColor: zoomBackgroundColor, // 缩放区背景颜色
        dataBackground: {
          lineStyle: {
            color: backgroundLineColor, // 阴影线条颜色
            width: 1
          },
          areaStyle: {
            color: backgroundAreaColor // 阴影填充颜色
          }
        }
      },
      {
        type: "inside",
        start: zoomStart, // 放大镜开始
        end: zoomEnd, // 放大镜结束
      },
    ];
    if (zoomStart < 0 || zoomEnd < 100) {
      dataZoom[1].disabled = true;
    } else {
      dataZoom[1].disabled = false;
    }

    if (legendMap.indexOf(",") > 0) { // 图例映射
      legendMap = legendMap.split(",").map(function (leg) {
        return leg.trim();
      });
    } else if (Boolean(legendMap)) {
      legendMap = [legendMap];
    }

    function getMarkPoint(data) {
      const points = data.map(x => {return [x,0]});
      const markPoints = [];
      points.map(p => {
        const tag = {
          name: 'tag',
          coord: p,
          value: markPointerDataValue, // 标注值
          symbol: 'path://M51,547.3l-22.2-38.4H8c-3.6,0-6.5-2.9-6.5-6.5v-490c0-3.6,2.9-6.5,6.5-6.5h86c3.6,0,6.5,2.9,6.5,6.5v490 c0,3.6-2.9,6.5-6.5,6.5H73.2L51,547.3z M8,8.9c-1.9,0-3.5,1.6-3.5,3.5v490c0,1.9,1.6,3.5,3.5,3.5h22.6L51,541.3l20.4-35.4H94 c1.9,0,3.5-1.6,3.5-3.5v-490c0-1.9-1.6-3.5-3.5-3.5H8z',
          itemStyle: {
            color: 'rgba(241,133,16,0)',
            borderColor: colors[1]
          },
          symbolSize: markPointTagSize.split(',').map(function(item) { return item.trim(); }), // 标注宽高
          symbolOffset: markPointTagOffset.split(',').map(function(item) { return item.trim(); }), // 标注偏移
        };
        const triangle = {
          name: 'triangle',
          coord: p,
          symbol: 'path://M3188.56,837.967l-10.91-18.037,21.08-.432Z',
          symbolSize: markPointTriangleSize.split(',').map(function(item) { return item.trim(); }), // 标注三角形宽度
          itemStyle: {
            color: colors[1]
          },
          symbolOffset: markPointTriangleOffset.split(',').map(function(item) { return item.trim(); })
        };
        const rect = {
          name: 'rect',
          coord: p,
          symbol: "path:M3189,833V983",
          symbolSize: markPointRectSize.split(',').map(function(item) { return item.trim(); }), // 标注矩形宽度
          itemStyle: {
            color: colors[1]
          },
          symbolOffset: markPointRectOffset.split(',').map(function(item) { return item.trim(); })
        };
        markPoints.push(tag);
        markPoints.push(triangle);
        markPoints.push(rect);
      });
      return { // 换件点图
        type: "scatter",
        name: legendMap[1] ? legendMap[1] : "换件点", // 图例名称
        datasetIndex: 0,
        data: [],
        markPoint: { // 标记
          label: {
            color: colors[1],
            position: markPointLabelPos.split(',').map(function(item) { return item.trim(); }), // 标签位置(左,上)
            fontSize: markPointerFontSize // 标注字体大小
          },
          data: markPoints
        },
      };
    }

    const serieThreshold = { // 阈值
      type: "line",
      name: legendMap[2] ? legendMap[2] : "阈值",
      showSymbol: false,
      smooth: false,
      data: [],
      markLine: {
        symbol: "none", //去掉警戒线最后面的箭头
        label: {
          position: "end", //将警示值放在哪个位置，三个值“start”,"middle","end"  开始  中点 结束
          formatter: "",
        },
        data: [
          {
            lineStyle: { // 警戒线的样式  ，虚实  颜色
              type: standardLineType, // 标准线类型
              color: colors[2],
              width: standardLineWidth, // 标准线宽度
            },
            name: "",
            yAxis: 0,
          },
          {
            lineStyle: { //警戒线的样式  ，虚实  颜色
              type: standardLineType, // 标准线类型
              color: colors[2],
              width: standardLineWidth, // 标准线宽度
            },
            name: "",
            yAxis: 0,
          },
        ],
      }
    };

    // 视觉映射: 超过阈值上限、当前航、其他
    const visualMap = [
      {
        show: false,
        type: 'piecewise',
        categories: ['warning', 'current'],
        inRange: {
          color: [warningColor,currengFlightNodeColor],
          symbolSize: [symbolSize, currengFlightNodeSize]
        },
        outOfRange: {
          color: [colors[3]]
        },
        seriesIndex: [0]
      }
    ];

    const serieScatter = { // 散点图
      type: "scatter",
      name: legendMap[0] ? legendMap[0] : "左发低压转子",
      datasetIndex: 0,
      symbol: symbol,
      symbolSize: symbolSize,
    };

    if (customDimessions.indexOf(",") > 0) { // 自定义维度
      customDimessions = customDimessions.split(",").map(function (item) {
        return item.trim();
      });
    } else {
      customDimessions = null;
    }

    const serieRegression = { // 趋势线
      name: legendMap[3] ? legendMap[3] : "趋势线",
      type: "line",
      showSymbol: false,
      smooth: false,
      data: [],
      lineStyle: {
        width: trendLineWidth, // 趋势线宽度
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 0.5, [
          {
            offset: 0,
            color: colors[3],
          },
          {
            offset: 1,
            color: "rgba(255,255,255,0)",
          },
        ]),
      }
    };

    const myChart = window.echarts.init(this);
    const self = this;

    function initChart(source) {
      const thresholdMin = source.thresholdMin;
      const thresholdMax = source.thresholdMax;
      const markPointData = source.markPointData;
      const regressionData = source.regressionData;
      const currFlightRegressionMarkData = source.currFlightRegressionMarkData;
      const scatterData = source.scatterData;
      const alert = source.alert;

      // 散点数据
      serieScatter.data = scatterData;
      serieScatter.dimensions = customDimessions;

      // 换件点数据
      const markPoint = getMarkPoint(markPointData);

      // 阈值数据
      serieThreshold.markLine.data[0].yAxis = thresholdMax;
      serieThreshold.markLine.data[1].yAxis = thresholdMin;

      // 趋势线数据
      serieRegression.data = regressionData;
      serieRegression.markLine = {
        symbol: "none",
        lineStyle: {
          color: currengFlightNodeColor,
          type: 'solid',
          width: currengFlightLineWidth, // 当前航班线宽
        },
        data: currFlightRegressionMarkData
      }

      const series = [serieScatter, markPoint, serieThreshold, serieRegression];
      let newYAxis = JSON.parse(JSON.stringify(yAxis));
      if(!alert) {
        newYAxis.max = thresholdMax;
      }
      const option = {
        title: title,
        tooltip: tooltip,
        legend: legend,
        icon: legendIcon,
        grid: grid,
        xAxis: xAxis,
        yAxis: newYAxis,
        visualMap: visualMap,
        dataZoom: dataZoom,
        series: series,
      };

      if (Boolean(colors)) option.color = colors;

      myChart.setOption(option);
      myChart.resize();
    }

    initChart(defaultData);

    const loader = $(
      '<div class="loader"><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span><span class="dot"></span></div>'
    );

    window.addEventListener(
      "resize",
      function () {
        myChart.resize();
      },
      false
    );

    let pmAirInfo = {}; // 架次信息
    const eventName = `call-` + self.getAttribute("id");
    let alert = '';
    
    function send(pmAirInfo) { // 请求数据
      let params = `?${tailnumber}=${pmAirInfo.tailnumber}`
      if(needEngine) {
        params = `${params}&${engine}=${engineValue}`
      }
      window.spSocket.send({
        eventName: eventName,
        data: {
          success :true,
          out1: params
        }
      });
    }

    // 数据格式转换
    function get(data) {
      const thresholdMax = data[thresholdMaxKey];
      const currFlightRegressionMarkData = [];
      const dataList = JSON.parse(JSON.stringify(data[dataListKey]));
      const scatterData = data[dataListKey] ? data[dataListKey].map((d, index) => {
        let type = 'normal';
        let markLine = [];
        if(d[feijiIdKey] === pmAirInfo.flightid) { // 当前航班的数据
          type = 'current';
          const nextIndex = index + 1 > dataList.length - 1 ? index : index + 1;
          markLine = [
            {coord: [d[xKey],d[regressionKey]]},
            {coord: [dataList[nextIndex][xKey],dataList[nextIndex][regressionKey]]}
          ]
        }
        if(d[scatterKey] > thresholdMax) { // 超过阈值上限的数据
          type = 'warning';
          markLine = [];
        }
        if(markLine.length > 0) {currFlightRegressionMarkData.push(markLine)};
        return [d[xKey],d[scatterKey],type];
      }) : [];
      
      const regressionData = data[dataListKey] ? data[dataListKey].map(d => {
        return [d[xKey],d[regressionKey]];
      }) : [];
      const source = {
        thresholdMin: data[thresholdMinKey],
        thresholdMax: thresholdMax,
        alert: data[alertKey],
        markPointData: data[markPointKey] || [],
        regressionData: regressionData,
        scatterData: scatterData,
        currFlightRegressionMarkData: currFlightRegressionMarkData
      }
      return source;
    }

    let hasTransfer = false;
    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          if (_data.data.in1) {
            const result = JSON.parse(_data.data.in1);
            const source = get(result.data);
            if (!hasTransfer) {
              $(self).find('.loader').remove();
              initChart(source);
              hasTransfer = true;
            }
            // 显示报警
            window.spSocket.send({
              eventName: eventName,
              data: {
                success :true,
                out2: JSON.stringify({status: result.data.alert ? true : false, message: result.data.alert})
              }
            });
          }
          if (_data.data.in2) {
            // 架次切换刷新图表数据
            pmAirInfo = JSON.parse(_data.data.in2);
            myChart.clear();
            hasTransfer = false;
            $(self).append(loader);
            send(pmAirInfo);
          }
        },
      });
    }
  },

  onViewInit() {
    this.updateScript();
    const evn =
      echartsBasicListen + "change:axisLineType change:xAxisTick change:yAxisTick change:xAxisTickColor change:xAxisTick change:yAxisTickColor change:yAxisName change:xAxisColor change:yAxisColor change:xAxisSplitLine change:yAxisSplitLine change:axisSplitLineColor change:axisSplitLineType change:gridPadding change:xLabelRotate change:multiSeries change:customDimessions change:symbol change:symbolSize change:visualPosition change:rangeSymbolSize change:zoomHeight change:zoomTextColor change:zoomFillerColor change:zoomBackgroundColor change:zoomBorderColor change:zoomStart change:zoomEnd change:standardLineType change:standardLineWidth change:trendLineWidth change:warningColor  change:zoomHandleColor change:markPointerDataValue change:markPointerFontSize change:markPointLabelPos change:markPointTagSize change:markPointTriangleSize change:markPointRectSize change:markPointTagOffset change:markPointTriangleOffset change:markPointRectOffset change:xAxisWidth change:yAxisWidth change:xAxisTickWidth change:yAxisTickWidth change:zoomBottom change:backgroundLineColor change:backgroundAreaColor change:yAxisTickWidth change:thresholdMinKey change:thresholdMaxKey change:markPointKey change:dataListKey change:xKey change:scatterKey change:regressionKey change:feijiIdKey change:tailnumber change:engine change:needEngine change:engineValue change:alertKey change:currengFlightNodeColor change:currengFlightNodeSize change:tooltipHideDimessions change:currengFlightLineWidth";
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
    this.listenTo(
      this.em,
      "update:component:style:height update:component:style:width",
      throttle.bind(this, this.updateScript.bind(this))
    );
  },
};
