import { circularProgress, CATEGORIES } from '../../configuration/constants'
import { throttle } from '../../utils'

export default {

  // 组件名称
  name: circularProgress,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${circularProgress}" class="${circularProgress}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${circularProgress} {
          position: relative;
        }
        .${circularProgress} .circularProgress {
          width: 400px;
          height: 346px;
          overflow: hidden;
          display: inline-block;
        }
        .${circularProgress} .main {
          width: 400px;
          height: 400px;
          position: relative;
        }
        .${circularProgress} .progress {
          width: 400px;
          height: 400px;
        }
        .${circularProgress} .circle{
          width: 55%;
          height: 55%;
          border: 1px solid #1e6ec2;
          border-radius: 50% 50% 50% 0;
          border-bottom: none;
          position: absolute;
          top: 22.45%;
          left: 22.45%;
          display: inline-block;
          border-left: none;
          transform: rotate(-45deg);
        }
        .${circularProgress} .circle2 { 
          width: 98%;
          height: 85%;
          overflow: hidden;
          top: 1%;
          left: 1%;
          position: absolute;
          display: inline-block;
        }
        .${circularProgress} .circle-shadow {
          border: 2px solid #5e99d2;
          border-radius: 50% 50% 50% 0;
          border-bottom: none;
          border-left: none;
          transform: rotate(-45deg);
          box-shadow: inset -6px 8px 17px -5px #308dd2;
          width: 99.4898%;
          height: 114.7059%;
        } 
        .${circularProgress} .bottom {
          position: absolute;
          top: 69%;
          left: 31%;
          width: 34.75%;
          height: 17.5%;
        }
      
        .${circularProgress} .trapezoid {
          width: 100%;
          height: 82.4286%;
          transform: skew(20deg, 0deg);
          background: linear-gradient(0deg, rgb(33,124,217), rgb(0, 0, 0, 0));
        }
        .${circularProgress} .trapezoid:before{
          position: absolute;
          content: '';
          top: 0;
          width: 27%;
          height: 100%;
          left: -12%;
          transform: skew(-35deg, 0deg);
        }
        .${circularProgress} .rect {
          position: absolute;
          width: 99.3%;
          height: 8px;
          background: linear-gradient(0deg, rgb(0, 0, 0, 0), rgb(33,124,217));
          left: 8.2%;
        }
        .${circularProgress} .line {
          width: 99%;
          height: 1px;
          left: 8.2%;
          background: linear-gradient(90deg,rgba(255,255,255,0) 0%,rgba(24,220,250,0.97) 48%,rgba(0,193,222,0) 100%);
          position: absolute;
          z-index: 9;
        }
        .${circularProgress} .value {
          position: absolute;
          top: 50%;
          color: #fff;
          left: 50%;
          font-size: 40px;
          transform: translateX(-50%) translateY(-50%);
        }
        .${circularProgress} .title {
          text-align: center;
          display: block;
        }
        .${circularProgress} .title_line {
          width: 100%;
          height: 5px;
          display: block;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
        <svg class="gjs-block-svg" viewBox="-4 -4 32 32" xmlns="http://www.w3.org/2000/svg">
          <path d="M10.1,15.9c-0.7,1.2-0.2,2.2,0.7,2.7c1,0.6,2,0.5,2.7-0.7c0.7-1.2,5-11.9,4.7-12.1C17.9,5.6,10.8,14.7,10.1,15.9z M12,8.3
          c0.4,0,0.9,0,1.3,0.1c0.4-0.5,0.9-1.2,1.4-1.7c-0.9-0.3-1.8-0.4-2.7-0.4C6.4,6.3,2,11,2,17.1c0,0.4,0,0.7,0,1.1c0,0.6,0.5,1,1.1,0.9
          C3.7,19,4.1,18.6,4,18c0-0.3,0-0.6,0-0.9C4,12.2,7.5,8.3,12,8.3z M19.2,9.6c-0.3,0.8-0.6,1.5-0.8,2.2c1,1.5,1.6,3.3,1.6,5.3
          c0,0.3,0,0.6,0,0.9c0,0.6,0.4,1,0.9,1c0.5,0,1-0.4,1-0.9c0-0.4,0.1-0.7,0.1-1.1C22,14.1,20.9,11.5,19.2,9.6L19.2,9.6z"/>
        </svg>
        <div class="gjs-block-label">环形进度条</div>
      `
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '环形进度条',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/c0e3b69a-9f17-4824-86d3-2014c5e125e1',
      author: '陈亚楠',
      email: '878493162@qq.com',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'json',
          description: {
            zh_CN: '输入1'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: circularProgress,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      disableChildEdit: true,
      traits: [
        {
          type: 'number',
          name: 'width',
          label: '环形宽高',
          changeProp: 1,
        },{
          type: 'color',
          name: 'bgColor',
          label: '背景色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'progressBorderColor',
          label: '进度条边框颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'progressShadowColor',
          label: '进度条边框阴影颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'pointerColor',
          label: '指针颜色',
          changeProp: 1,
        },
        {
          name: 'gradient',
          label: '进度条渐变',
          changeProp: 1,
          type: 'select',
          options: [{id: 'none', name: '无'}, {id: '0-1-0-0', name: '从下到上'}, {id: '0-0-1-0', name: '从左到右'}, {id: '0-0-1-1', name: '左上到右下'}, {id: '0-1-1-0', name: '左下到右上'}]
        },
        {
          name: 'progressColor',
          label: '进度条颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'inlineColor',
          label: '进度条内部环形阴影颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'bottomColor',
          label: '梯形底座颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'outerCircleBorderColor',
          label: '最外层圆弧边框颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'outerCircleShadow',
          label: '最外层圆弧阴影颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'innerCircleBorderColor',
          label: '最内层圆弧边框颜色',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'valueColor',
          label: '值字体颜色',
          changeProp: 1,
        },
        {
          name: 'valueFontFamily',
          label: '值字体',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'sans-serif', name: '默认' },
            { id: '庞门正道', name: '庞门正道' },
            { id: 'DS-Digital', name: 'DS-Digital' }
          ]
        },
        {
          type: 'number',
          name: 'valueSize',
          label: '值字体大小',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'titleColor',
          label: '标题字体颜色',
          changeProp: 1,
        },
        {
          name: 'titleFontFamily',
          label: '标题字体',
          changeProp: 1,
          type: 'select',
          options: [
            { id: 'sans-serif', name: '默认' },
            { id: '庞门正道', name: '庞门正道' },
            { id: 'DS-Digital', name: 'DS-Digital' }
          ]
        },
        {
          type: 'number',
          name: 'titleSize',
          label: '标题字体大小',
          changeProp: 1,
        },
        {
          type: 'number',
          name: 'topMargin',
          label: '标题上间距',
          changeProp: 1,
        },
        {
          type: 'color',
          name: 'titleBottomLine',
          label: '标题下划线颜色',
          changeProp: 1,
        },
        {
          name: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '环形进度条',
          datas: [['任务完成度', 60]]
        },
        {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        },
        {
          name: 'defaultDataSetting',
          changeProp: 1,
          type: 'hide'
        }
      ],
      'defaultData':JSON.stringify([['任务完成度', 60]]).replace(/\"/g, "\\\""),
      'defaultDataConfig': JSON.stringify({
        dataIncludeHeader: false,
        tableColumns: [
          {title: "标签"},
          {title: "值", type: "number"}
        ]
      }).replace(/\"/g, "\\\""),
      'width': 400,
      'bgColor': '#fff',
      'progressBorderColor': '#1e6ec2',
      'progressShadowColor': '#5defc2',
      'pointerColor': '#5defc2',
      'gradient': '0-1-0-0',
      'progressColor': '#164955|#4dc9a4',
      'inlineColor': '#062d5f',
      'bottomColor': '#217cd9',
      'outerCircleBorderColor': '#217cd9',
      'outerCircleShadow': '#217cd9',
      'innerCircleBorderColor': '#217cd9',
      'valueColor': '#11FF87',
      'valueFontFamily': 'sans-serif',
      'valueSize': 69,
      'titleColor': '#B2EFFF',
      'titleFontFamily': 'sans-serif',
      'titleSize': 43.2,
      'topMargin': 15,
      'titleBottomLine': '#21B3F0'
    }
  },

  onModelScript() {
    const bgColor = '{[ bgColor ]}';
    const width = Number('{[ width ]}');
    const progressBorderColor = '{[ progressBorderColor ]}';
    const progressShadowColor = '{[ progressShadowColor ]}';
    const pointerColor = '{[ pointerColor ]}';
    const gradient = ('{[ gradient ]}').toString();
    let progressColor = '{[ progressColor ]}';
    const inlineColor = '{[ inlineColor ]}';
    const bottomColor = '{[ bottomColor ]}';
    const outerCircleShadow = '{[ outerCircleShadow ]}';
    const outerCircleBorderColor = '{[ outerCircleBorderColor ]}';
    const innerCircleBorderColor = '{[ innerCircleBorderColor ]}';
    const valueColor = '{[ valueColor ]}';
    const valueSize = Number('{[ valueSize ]}');
    const valueFontFamily = ('{[ valueFontFamily ]}').toString();
    const titleColor = '{[ titleColor ]}';
    const titleSize = Number('{[ titleSize ]}');
    const titleFontFamily = ('{[ titleFontFamily ]}').toString();
    const topMargin = Number('{[ topMargin ]}');
    const titleBottomLine = '{[ titleBottomLine ]}';
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));

    const self = this;
    const _id = self.getAttribute('id');
    const $progressEl = $(self).find('.progress')[0];
    const myChart = window.echarts.init($progressEl);

    function transferColorToRgba(color, alpha=1) {
      if (typeof color !== 'string' && !(color instanceof String)) return console.error("请输入16进制字符串形式的颜色值");
      color = color.charAt(0) === '#' ? color.substring(1) : color;
      if (color.length !== 6 && color.length !== 3) return console.error("请输入正确的颜色值")
      if (color.length === 3) {
          color = color.replace(/(\w)(\w)(\w)/, '$1$1$2$2$3$3')
      }
      var reg = /\w{2}/g;
      var colors = color.match(reg);
      for (var i = 0; i < colors.length; i++) {
          colors[i] = parseInt(colors[i], 16).toString();
      }
      return `rgba( ${colors.join()}, ${alpha})`;
    }

    function initChart(data) {
      const valueEl = $(self).find('.value');
      const titleEl = $(self).find('.title');
      const trapezoidEl = $(self).find('.trapezoid');

      const times = width / 400;

      $(self).find('.circularProgress').css({ width: `${width}px`, height: `${width * 0.865}px`});
      $(self).find('.main').css({ width: `${width}px`, 'height': `${width}px`});
      $(self).find('.progress').css({ width: `${width}px`, 'height': `${width}px`});
      $(self).find('.rect').css('background', `linear-gradient(0deg, rgb(0, 0, 0, 0), ${bottomColor})`);
      $(self).find('.circle-shadow').css({ 'border-color': outerCircleBorderColor, 'box-shadow': `inset -6px 8px 17px -5px ${outerCircleShadow}`});
      $(self).find('.circle').css('border-color', innerCircleBorderColor);
      $(self).find('.line').css('background', `linear-gradient(90deg,rgba(255,255,255,0) 0%, ${outerCircleBorderColor} 48%,rgba(0,193,222,0) 100%)`);
      $(self).find('.title_line').css('background', `linear-gradient(90deg,rgba(255,255,255,0) 0%, ${titleBottomLine} 48%, rgba(255,255,255,0) 100%)`);

      trapezoidEl.css('background', `linear-gradient(0deg, ${bottomColor}, rgb(0, 0, 0, 0))`);
      trapezoidEl.append(`<style> .circular-progress#${_id} .trapezoid::before {background-color: ${bgColor};}</style>`);
      valueEl.css('color', valueColor);
      valueEl.css('font-size', `${valueSize}px`);
      valueEl.css('font-family', valueFontFamily);
      titleEl.css('color', titleColor);
      titleEl.css('font-size', `${titleSize}px`);
      titleEl.css('font-family', titleFontFamily);
      titleEl.css('margin-top', `${topMargin}px`);

      let _progressColor;
      if (gradient !== 'none' && progressColor) {
        let gaugeGradient = gradient.split('-');
        let _color = progressColor.split('|');
        _progressColor = new echarts.graphic.LinearGradient( gaugeGradient[0], gaugeGradient[1], gaugeGradient[2], gaugeGradient[3], [{
            offset: 0,
            color: _color[0]
          },
          {
            offset: 1,
            color: _color[1]
          }
        ]);
      } else if (gradient === 'none' && progressColor) {
        _progressColor = progressColor.split('|').length > 0 ?  progressColor.split('|')[0] : progressColor;
      } else {
        _progressColor = new echarts.graphic.LinearGradient( 0, 1, 0, 0, [{
            offset: 0,
            color: '#164955'
          },
          {
            offset: 1,
            color: '#4dc9a4'
          }
        ]);
      }
      // echarts
      const value = data && data.length > 0 && data[0].length > 1 ? data[0][1] : 0;
      const displayValue = data && data.length > 0 && data[0].length > 1 ? data[0][1] : '--';
      const title = data && data.length > 0 && data[0].length > 0 ? data[0][0] : '';
      valueEl.html(`${displayValue}%`);
      titleEl.html(title);
      let series = [
        {
          type: 'gauge',
          name: '斜边',
          radius: '85.5%',
          startAngle: '225.3',
          endAngle: '-45.5',
          pointer: {
            show: false
          },
          detail: {
            show: false,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: [
                [1, progressBorderColor]
              ],
              width: 52 * times,
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false,
          },
          axisLabel: {
            show: false
          }
        },
        {
          type: 'gauge',
          name: '底层进度条',
          radius: '85%',
          startAngle: '225',
          endAngle: '-45',
          pointer: {
            show: false
          },
          detail: {
            show: false,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: [
                [value / 100, pointerColor],
                [1, bgColor]
              ],
              width: 50 * times,
              shadowColor: progressShadowColor,
              shadowBlur: 5,
            }
          },
          axisTick: {
              show: false
          },
          splitLine: {
              show: false,
          },
          axisLabel: {
              show: false
          }
        },
        {
          type: 'gauge',
          name: '渐变进度条',
          radius: '85%',
          startAngle: '225',
          endAngle: '-45',
          pointer: {
            show: false
          },
          detail: {
            show: false,
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: [
                [value / 100 - 0.01, _progressColor],
                [1, 'rgba(0,0,0,0)']
              ],
              width: 50 * times,
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            show: false,
          },
          axisLabel: {
            show: false
          }
        },
        {
          name: "进度条内部阴影",
          type: "gauge",
          radius: '70%',
          z: 4,
          splitNumber: 10,
          axisLine: {
            lineStyle: {
              color: [
                [1, new echarts.graphic.LinearGradient( 0, 1, 0, 0, [{
                    offset: 0,
                    color: transferColorToRgba(inlineColor || '#fff', 0),
                  }, {
                    offset: 0.5,
                    color: transferColorToRgba(inlineColor || '#fff', 0.1),
                  },
                  {
                    offset: 1,
                    color: transferColorToRgba(inlineColor || '#fff', 0.3),
                  }
                ])],
              ],
              width: 20 * times,
            }
          },
          axisLabel: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: false,
          },
          itemStyle: {
            show: false,
          },
          detail: {
            show: false,
          },
          pointer: {
            show: false,
          },
        },
        {
          name: "指针",
          type: "gauge",
          radius: "72%",
          startAngle: 225,
          endAngle: -45,
          axisTick: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          axisLine: {
            lineStyle: {
              opacity: 0
            }
          },
          detail: {
            show: false
          },
          pointer: {
            show: true,
            width: '50%',
            length: "69%",
          },
          itemStyle: {
            color: pointerColor
          },
          data: [{
            value: value, //输入值
          }]
        },
        {
          name: '遮盖',
          type: "pie",
          radius: ["0", "45%"],
          hoverAnimation: false,
          animation: false,
          data: [{
            value: 0,
            itemStyle: {
              color: bgColor
            },
          }]
        },
      ];
      myChart.clear();
      const option = {
        series
      };

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

    initChart(defaultData);

    window.addEventListener('resize', function () {
      myChart.resize();
    }, false);
  
    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      var eventName = `call-` + _id;
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let _in1Str = _data.data.in1;
          if (_in1Str) {
            const source = JSON.parse(_in1Str);
            initChart(source);
          }
        }
      });
    }
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="circularProgress">
          <div class="main">
            <div class="progress"></div>
            <div class="circle"></div>
            <div class="circle2">
              <div class="circle-shadow"></div>
            </div>
            <div class="bottom">
              <div class="trapezoid"></div>
              <div class="line"></div>
              <div class="rect"></div>
            </div>
            <div class="value"></div>
          </div>
        </div>
        <div class="title"></div>
        <div class="title_line"></div>
      `)
    }
    this.updateScript();
    const evn = `
      change:defaultData
      change:width
      change:bgColor
      change:progressBorderColor
      change:progressShadowColor
      change:pointerColor
      change:gradient
      change:progressColor
      change:inlineColor
      change:bottomColor
      change:outerCircleShadow
      change:outerCircleBorderColor
      change:innerCircleBorderColor
      change:valueSize
      change:valueColor
      change:valueFontFamily
      change:titleColor
      change:titleSize
      change:titleFontFamily
      change:topMargin
      change:titleBottomLine
    `;

    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)));
  }
}
