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

export default {

  // 组件名称
  name: animatePieChart,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${animatePieChart}" class="${animatePieChart}">
        <div class="chart"></div>
        <div class="legendList"></div>
      </div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${animatePieChart} {
          border-radius: 5px;
          border-style: solid;
          border-width: 1px;
          border-color: transparent;
          padding: 10px;
          display: flex;
          align-items: center;
        }
        .${animatePieChart} .legendList {
          margin-left: 50px;
          width: 500px;
          height: 500px;
          display: flex;
          flex-direction: column;
          font-size: 25px;
          align-items: flex-end;
        }
        .${animatePieChart} .legend {
          flex: 1;
          display: flex;
          align-items: center;
          width: 90%;
          border-radius: 50px 0 0 50px;
        }
        .${animatePieChart} .legend .circle-inner {
          width: 25px;
          height: 25px;
          border-radius: 50%;
        }
        .${animatePieChart} .legend-active {
          width: 100%;
          background: linear-gradient(90deg, rgba(41, 139, 254, 0.2) 0%, rgba(41, 139, 254, 0) 100%);
          border-radius: 50px 0 0 50px;
        }
        .${animatePieChart} .legend .circle {
          margin-left: 32px;
        }
        .${animatePieChart} .legend-active .circle {
          padding: 8px;
          margin-left: 24px;
        }
        .${animatePieChart} .legend .name {
          flex: 1;
          text-overflow: ellipsis;
          overflow: hidden;
          margin-left: 50px;
        }
        .${animatePieChart} .legend-active .name {
          color: #fff;
          margin-left: 35px;
        }
        .${animatePieChart} .legend .value {
          flex: 1;
          text-align: right;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      category: CATEGORIES.ECHARTS,
      label: `动态饼图`,
      attributes: { class: 'fa fa-pie-chart' }
    };
  },

  // 后面板显示属性配置
  spOptions() {
    return {
      label: '数据动态切换饼图',
      icon: 'globe',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'json',
          description: {
            zh_CN: '输入1'
          }
        }],
      // outPorts: [{
      //     uuid: 'out1',
      //     subType: 'json',
      //     description: {
      //       zh_CN: '输出1'
      //     }
      //   }
      // ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: animatePieChart,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      highlightable: false,
      disableChildEdit: false,
      traits: [
        {
          name: 'pieColor',
          label: '环图颜色',
          changeProp: 1,
          type: 'color',
        },{
          name: 'pieSelectedColor',
          label: '环图选中颜色',
          changeProp: 1,
          type: 'color',
        },
        {
          name: 'center',
          label: '中心点(h,v)',
          changeProp: 1,
        },
        {
          name: 'pieWidth',
          label: '饼图大小(px)',
          changeProp: 1,
          type: 'number'
        },
        {
          name: 'innerRadius',
          label: '内半径(%)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'showShadow',
          label: '显示内阴影',
          changeProp: 1,
          type: 'checkbox'
        }, {
          name: 'shadowInnerRadius',
          label: '阴影内半径(%)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'outRadius',
          label: '外半径(%)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'legendBg',
          label: '图例背景色',
          changeProp: 1,
        }, {
          name: 'legendSelectedBg',
          label: '图例选中背景色',
          changeProp: 1,
        }, {
          name: 'legendMargin',
          label: '图例间距(px)',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'legendColor',
          label: '图例字体颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'legendSelectedColor',
          label: '图例选中字体颜色',
          changeProp: 1,
          type: 'color'
        }, {
          name: 'timeout',
          label: '动态切换间隔',
          changeProp: 1,
          type: 'number'
        }, {
          name: 'unit',
          label: '显示值单位',
          changeProp: 1,
        }, {
          name: 'csv',
          label: '示例数据',
          changeProp: 1,
          type: 'csvDownload',
          preFileName: '动态饼图',
          datas: [
            ['name', 'DEMO'], 
            ['类别1', 100], 
            ['类别2', 500], 
            ['类别3', 400], 
            ['类别4', 400], 
            ['类别5', 300],
            ['其它', 300],
          ],
        }, {
          name: 'defaultData',
          changeProp: 1,
          type: 'hide'
        }
      ],
      defaultData:JSON.stringify([
        ['name', 'DEMO'], 
        ['类别1', 100], 
        ['类别2', 500], 
        ['类别3', 400], 
        ['类别4', 400], 
        ['类别5', 300],
        ['其它', 300],
      ]).replace(/\"/g, "\\\""),
      pieWidth: 500,
      legendBg: 'rgba(255,255,255,0.15)|rgba(255,255,255,0.01)',
      legendSelectedBg: 'rgba(41, 139, 254, 0.2)|rgba(41, 139, 254, 0)',
      legendMargin: 10,
      center: '50%,50%',
      innerRadius: 80,
      showShadow: false,
      shadowInnerRadius: 70,
      outRadius: 90,
      pieColor: 'rgba(0,0,0,0.3)',
      pieSelectedColor: '#1fcbff',
      timeout: 1000,
      legendColor: '#333',
      legendSelectedColor: '#1fcbff',
      unit: '个'
    }
  },

  onModelScript() {
    let center = '{[ center ]}';
    const pieColor = '{[ pieColor ]}';
    const pieSelectedColor = '{[ pieSelectedColor ]}';
    const legendColor = '{[ legendColor ]}';
    const legendSelectedColor = '{[ legendSelectedColor ]}';
    const legendBg = stringToArray('{[ legendBg ]}');
    const legendSelectedBg = stringToArray('{[ legendSelectedBg ]}');
    const legendMargin = Number('{[ legendMargin ]}');
    const pieWidth = Number('{[ pieWidth ]}');
    const innerRadius = Boolean('{[ innerRadius ]}') ? ('{[ innerRadius ]}').toString() + '%' : 0;
    const shadowInnerRadius = Boolean('{[ shadowInnerRadius ]}') ? ('{[ shadowInnerRadius ]}').toString() + '%' : 0;
    const outRadius = ('{[ outRadius ]}').toString() + '%';
    const defaultData = JSON.parse('{[ defaultData ]}'.replace(/\\\"/g, "\""));
    const timeout = '{[ timeout ]}';
    const showShadow = Boolean('{[ showShadow ]}');
    const unit = '{[ unit ]}';
    let colors = new Array();
    function stringToArray(value) {
      if (value.indexOf('|') > -1) {
        value = value.split('|').map(item => item.trim());
      } else if (Boolean(value)) {
        value = [value, value]
      } else {
        return null;
      }
      return value;
    }

    if (center.indexOf(',') > -1) {
      center = center.split(',').map(item => item.trim())
    } else if (Boolean(center)) {
      center = [center, center]
    } else {
      center = ['50%', '50%'];
    }

    const self = this;
    const _id = self.getAttribute('id');
    const timer = `timer-${_id}`;
    const eventName = `call-${_id}`;
    const myChart = window.echarts.init($(self).find('.chart')[0]);

    $(self).find('.chart').width(pieWidth || 0);
    $(self).find('.chart').height(pieWidth || 0);

    if (window[timer]) {
      clearInterval(window[timer]);
    }
    
    window[timer] = null;

    function initChart(_source) {
      myChart.clear();
      $(self).find('.legendList').html('');
      let categories = new Array();
      let values = new Array();
      let list = new Array();
      _source.map((value, index) => {
        if (index !== 0) {
          categories.push(value[0]);
          values.push(value[1]);
          colors.push(pieColor);
        }
      });
      values.map((value, index) => {
        const el = `<div class="legend" style="background: ${legendBg ? `linear-gradient(90deg, ${legendBg[0]} 0%, ${legendBg[1]} 100%)` : 'none'};margin-bottom:${legendMargin}px;color:${legendColor};"><div class="name">${categories[index]}</div><div class="value">${value}<span>${unit}</span></div></div>`
        
        $(self).find('.legendList').append(el);

        list.push({
          value,
          name: categories[index]
        }, {
            value: 9,
            name: '',
            itemStyle: {
              normal: {
                label: {
                  show: false
                },
                labelLine: {
                  show: false
                },
                color: 'rgba(0, 0, 0, 0)',
                borderColor: 'rgba(0, 0, 0, 0)',
                borderWidth: 0
              }
            }
        });
      });
      let option = {
        color: colors,
        legend: {
          show: false,
          data: categories,
        },
        series: [
          {
            center,
            encode: { itemName: 0, value: 1 },
            label: {
              show: false,
              position: 'center',
            },
            emphasis: {
              label: {
                show: false,
                formatter: '{name|{b}}\n{value|{@[1]}}',
                rich:{
                  'name': {
                    color: legendColor,
                  },
                  'value': {
                    color: legendColor,
                  }
                }
              },
            },
            labelLine: { show: false },
            radius: [innerRadius, outRadius],
            roseType: false,
            selectedMode: false,
            type: "pie",
            data: list,
          }
        ],
        tooltip: { show: false },
      };

      if (showShadow) {
        option.series.push({
          center,
          encode: { itemName: 0, value: 1 },
          label: {
            show: false,
          },
          labelLine: { show: false },
          radius: [shadowInnerRadius, outRadius],
          roseType: false,
          selectedMode: false,
          itemStyle: {
            opacity: 0.1
          },
          type: "pie",
          data: list,
        });
      }
      myChart.setOption(option, true);
      myChart.resize();

      let currentIndex = -1;
      let dataLength= categories.length;
      window[timer] = setInterval(function() {
        if (currentIndex !== -1) {
          $(self).find('.legendList').find('.legend').eq(currentIndex).css({
            background: legendBg ? `linear-gradient(90deg, ${legendBg[0]} 0%, ${legendBg[1]} 100%)` : 'none',
            color: legendColor,
          });
          $(self).find('.legendList').find('.legend').eq(currentIndex).removeClass('legend-active');
        }

        currentIndex = (currentIndex + 1) % dataLength;

        
        // 高亮当前图形
        if (currentIndex !== -1) {
          let currentColors = [...colors];
          currentColors[currentIndex] = pieSelectedColor;
          option.color = currentColors;
          myChart.setOption(option, true);
          $(self).find('.legendList').find('.legend').eq(currentIndex).addClass('legend-active');
          $('.legend-active').css({
            background: legendSelectedBg ? `linear-gradient(90deg, ${legendSelectedBg[0]} 0%, ${legendSelectedBg[1]} 100%)` : 'none',
            color: legendSelectedColor,
          });
        }
      }, timeout);
      if (window.prevEventType && window.prevEventType[eventName]) {
        myChart.off(window.prevEventType[eventName]);
      }
    }

    initChart(defaultData);

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

    // 有 dashboardHost 说明是运行模式
    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          if(_data.data.in1) {
            const data = JSON.parse(_data.data.in1);
            initChart(data);
          }
        }
      });
    }
  },

  onViewInit() {
    this.updateScript();
    const evn = `
      change:legendColor
      change:legendSelectedColor
      change:legendBg
      change:legendSelectedBg
      change:pieWidth
      change:showShadow
      change:innerRadius
      change:pieColor
      change:outRadius
      change:center
      change:defaultData
      change:timeout
      change:shadowInnerRadius
      change:unit
      change:pieSelectedColor
    `;
    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)));
  }
}