import { hoopRef, CATEGORIES } from "../../configuration/constants";
import { throttle } from '../../utils';

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

  // 前面板html模板
  viewTemplate() {
    return `
      <div class="${hoopRef}" data-gjs-type="${hoopRef}">
        <svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
          <g class="circle-bg">
            <circle cx="150" cy="150" r="100" fill="none" stroke-width="8" stroke="#000" opacity="0.1"></circle>
          </g>
          <g class="circle-percent">
            <circle class="primary" style="display:none" cx="150" cy="150" r="100" fill="none" stroke-linecap="round" stroke-width="8" stroke-dasharray="20 20" stroke-dashoffset="20"></circle>
            <circle class="danger" cx="150" cy="150" r="100" fill="none" stroke-linecap="round" stroke-width="8" stroke-dasharray="20 20" stroke-dashoffset="20"></circle>
          </g>
        </svg>
        <div class="${hoopRef}-title">
          <p class="primary" style="display: none">
            <b></b>
            <span></span>
          </p>
          <p class="danger">
            <b></b>
            <span></span>
          </p>
        </div>
        <ul class="${hoopRef}-legend">
        </ul>
      </div>
    `;
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style> 
        .${hoopRef} {
          width: 300px;
          height: 300px;
          position: relative;
          color: #000;
        }
        .${hoopRef}.dark {
          color: #fff;
        }
        .${hoopRef}-title {
          position: absolute;
          top: 50%;
          left: 0;
          right: 0;
          margin-top: -40px;
          text-align: center;
          pointer-events: none;
        }
        .${hoopRef}-title b {
          display: block;
          font-size: 32px;
          line-height: 1;
        }
        .${hoopRef}-title span {
          display: block;
          font-size: 14px;
          opacity: 0.8;
        }
        .${hoopRef}-legend {
          padding: 0;
          margin: 0;
          position: absolute;
          left: 0;
          right: 0;
          bottom: 16px;
          font-size: 12px;
          text-align: center;
        }
        .${hoopRef}-legend > li {
          display: inline-block;
        }
        .${hoopRef}-legend > li:not(:last-child) {
          margin-right: 16px;
        }
        .${hoopRef}-legend > li > span {
          margin-right: 8px;
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
        }
      </style>
    `;
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
        <svg class="gjs-block-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" >
          <path d="M546.747 259.665c145.455 18.183 219.637 124.363 219.637 253.091 0 33.455-5.092 65.455-16.728 94.546L876.2 680.756c23.273-50.908 34.91-108.363 34.91-168 0-209.454-146.183-381.818-364.365-400v146.91z m0 0" p-id="58574"></path><path d="M474.02 765.847c-109.09-18.182-217.454-124.364-217.454-253.09 0-128.729 108.363-234.91 217.454-253.092V112.756c-181.818 18.182-362.182 190.546-362.182 400s180.364 381.82 362.182 400V765.847z m0 0" p-id="58575"></path><path d="M712.566 670.574c-40.001 50.908-93.091 85.091-165.819 95.273v146.91c109.091-10.91 224.728-74.91 290.183-168.728l-124.364-73.455z m0 0" ></path>
        </svg>
        <div class="gjs-block-label">比例环</div>
      `,
    };
  },

  spOptions() {
    return {
      label: "环形图",
      icon: "globe",
      author: "秋水",
      email: "qiushui.smy@xuelangyun.com",
      docUrl: "https://xuelangyun.yuque.com/docs/share/8755fda1-a2ca-484b-ac4e-05321cd7752f?# 《比例环》",
      inPorts: [
        {
          uuid: "in1",
          type: "data",
          ioType: "in",
          subType: "json",
          display: true,
          description: {
            zh_CN: "输入1",
          },
        },
      ],
    };
  },

  // 组件属性
  componentOptions() {
    return {
      name: hoopRef,
      resizable: true,
      dmode: "absolute",
      disableChildEdit: true,
      highlightable: false,
      droppable: false,
      traits: [
        {
          name: "authorInfo",
          label: "开发者",
          type: "authorInfo",
          author: "秋水",
          email: "qiushui.smy@xuelangyun.com",
        },
        {
          name: "docUrl",
          label: "文档",
          type: "link",
          href:
            "https://xuelangyun.yuque.com/docs/share/8755fda1-a2ca-484b-ac4e-05321cd7752f?# 《比例环》",
        },
        {
          type: "select",
          name: "styles",
          label: "环境",
          changeProp: 1,
          options: ["dark", "light"],
        },
        {
          name: "colors",
          label: "颜色",
          changeProp: 1,
        },
        {
          name: "strokeWidth",
          label: "描边",
          changeProp: 1,
          type: "number",
        },
        {
          name: "legend",
          label: "图例",
          changeProp: 1,
        },
      ],
      styles: "light",
      colors: "#0078f1,#ff4949",
      strokeWidth: 16,
      legend: "合格数,不合格数",
    };
  },

  onModelScript() {
    const getList = function (str) {
      return str.indexOf(",") > -1
        ? str.split(",").map(function (item) {
            return item.trim();
          })
        : [str];
    };
    const getAngle = function (used, total) {
      if (!total) {
        return -90;
      }
      return (used / total) * 360 - 90;
    };
    const getOffset = function (used, total) {
      let offset = circum - (used / total) * circum;
      if (!total) {
        offset = circum;
      } else if (used > total) {
        offset = 0;
      }
      return offset;
    };
    const onMouseoverLegend = function (i) {
      $(self)
        .find(".circle-percent")
        .children()
        .eq(i)
        .fadeIn()
        .siblings()
        .fadeOut();
      $(self)
        .find(".xly-hoop-title")
        .children()
        .eq(i)
        .css("display", "block")
        .siblings()
        .css("display", "none");
    };
    const self = this;
    const styles = "{[ styles ]}".toString();
    const style = styles == "dark" ? "#fff" : "#000";
    const colors = getList("{[ colors ]}");
    const legend = getList("{[ legend ]}");
    const strokeWidth = parseInt("{[ strokeWidth ]}");

    const width = this.offsetWidth;
    const height = this.offsetHeight;
    const r = width > height ? height / 4 : width / 4;
    const cx = r + strokeWidth / 2;
    const cy = r + strokeWidth / 2;
    const translateX = width / 2 - r - strokeWidth / 2;
    const translateY = height / 2 - r - strokeWidth / 2;
    const circum = r * 2 * Math.PI;

    const defaultUsed = 0;
    const defaultTotal = 0;

    const angle = getAngle(defaultUsed, defaultTotal);
    let offset = getOffset(defaultUsed, defaultTotal);
    const _offset = getOffset(defaultTotal - defaultUsed, defaultTotal);
    $(this).attr("class", "xly-hoop " + styles);
    $(this).find(".xly-hoop-legend").empty();
    $(this)
      .find(".circle-bg")
      .attr(
        "transform",
        "translate(" + translateX + "," + translateY + ")"
      )
      .children("circle")
      .first()
      .attr({
        cx: cx,
        cy: cy,
        r: r,
        "stroke-width": strokeWidth,
        stroke: style,
      });

    $(this)
      .find(".circle-percent")
      .attr(
        "transform",
        "translate(" + translateX + "," + translateY + ")"
      )
      .children("circle")
      .first()
      .attr({
        cx: cx,
        cy: cy,
        r: r,
        stroke: colors[0],
        "stroke-width": strokeWidth,
        "stroke-dasharray": circum + " " + circum,
        "stroke-dashoffset": _offset,
        transform: "rotate(" + angle + " " + cx + " " + cy + ")",
      })
      .next()
      .attr({
        cx: cx,
        cy: cy,
        r: r,
        stroke: colors[1],
        "stroke-width": strokeWidth,
        "stroke-dasharray": circum + " " + circum,
        "stroke-dashoffset": offset,
        transform: "rotate(-90 " + cx + " " + cy + ")",
      });
    if (legend.length) {
      const $legend = $(this).find(".xly-hoop-legend");
      const $title = $(this).find(".xly-hoop-title").children();
      for (let i = 0; i < legend.length; i++) {
        const num = !i ? defaultTotal - defaultUsed : defaultUsed;
        $legend.append(
          '<li><span style="background-color: ' +
            colors[i] +
            '"></span>' +
            legend[i] +
            "</li>"
        );
        $title
          .eq(i)
          .children("b")
          .text(num)
          .siblings("span")
          .text(legend[i]);
      }
      $legend
        .children()
        .eq(0)
        .mouseover(function () {
          onMouseoverLegend(0);
        });
      $legend
        .children()
        .eq(1)
        .mouseover(function () {
          onMouseoverLegend(1);
        });
    }
    $(this)
      .find(".circle-bg circle")
      .mouseover(function () {
        $(self)
          .find(".circle-percent")
          .children(":hidden")
          .fadeIn()
          .siblings()
          .fadeOut();
        $(self)
          .find(".xly-hoop-title")
          .children(":hidden")
          .css("display", "block")
          .siblings()
          .css("display", "none");
      });
    const eventName = `call-` + self.getAttribute("id");
    if (window.spSocket) {
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          const data = JSON.parse(_data.data.in1);
          const used = data.used;
          const total = data.total;
          let offset = getOffset(used, total);
          const _offset = getOffset(total - used, total);
          $(self)
            .find(".xly-hoop-title")
            .children()
            .eq(0)
            .children("b")
            .text(total - used)
            .end()
            .next()
            .children("b")
            .text(used);
          $(self)
            .find(".circle-percent circle")
            .last()
            .attr("stroke-dashoffset", offset)
            .prev()
            .attr("stroke-dashoffset", _offset);
        },
      });
    }
  },

  onViewInit(config) {
    const evn =
      "change:styles change:colors change:strokeWidth change:legend";
    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))
    );
  },
};
