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

export default {

  // 组件名称
  name: cardList,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${cardList}" class="${cardList}">
      </div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${cardList} {
          height: 800px;
          width: 1230px;
          overflow: hidden;
        }
        .${cardList} .scroll-body {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          flex-shrink: 0;
          justify-content: flex-start;
          align-items: flex-start;
          align-content: flex-start;
        }
        .${cardList} .scroll {
          animation: roll 30s linear 3s infinite;
        }
        .${cardList}:hover > .scroll {
          animation-play-state: paused;
        }
        @keyframes roll {
          0% {
            transform: translateY(0);
          }
          100% {
            transform: translateY(-100%);
          }
        }
        .${cardList} .scroll-body > .card {
          position:relative;
          height: 150px;
          width: calc((100% - 20px) / 3);
          margin-right: 10px;
          margin-bottom: 25px;
          padding: 10px 15px;
          background: rgba(48,159,237,0.05);
        }
        .${cardList} .scroll-body > .card:nth-child(3n + 3) {
          margin-right: 0;
        }
        .${cardList} .scroll-body > .card > .device-img {
          position: absolute;
          top: 50%;
          left: 25%;
          transform: translate(-50%, -50%);
        }
        .${cardList} .scroll-body > .card > .device-free,
        .${cardList} .scroll-body > .card > .device-empty {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          background: #0D3554;
        }
        .${cardList} .scroll-body > .card > .device-free > span {
          font-size: 16px;
          line-height: 30px;
          color: #20BAF6;
        }
        .${cardList} .scroll-body > .card > .device-msg {
          position: absolute;
          top: 15px;
          right: 15px;
          width: calc(50% - 15px);
        }
        .${cardList} .scroll-body > .card > .device-msg > .title {
          width: 100%;
          height: 30px;
          padding-left: 10px;
          font-size: 14px;
          font-weight: bold;
          line-height: 30px;
          color: #FFFFFF;
          background: rgba(32,186,246,0.2);
        }
        .${cardList} .scroll-body > .card > .device-msg > .normal {
          width: 100%;
          padding-left: 10px;
          font-size: 12px;
          font-weight: 400;
          line-height: 30px;
          color: #FFFFFF;
        }
        .${cardList} .scroll-body > .card > .device-msg > .normal > .label {
          color: #20BAF6;
        }
        .${cardList} .scroll-body > .card > .device-msg > .normal > .value {
          color: #FFFFFF;
        }
        .${cardList} .scroll-body > .card > .device-msg > .high-light,
        .${cardList} .scroll-body > .card > .device-msg > .high-light > span {
          color: #FFE41F !important;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      // label: "卡片列表",
      // attributes: { class: 'fa fa-table' },
      label: `
      <svg class="gjs-block-svg" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" ><path d="M426.666667 427.52h213.333333V896h-213.333333V427.52zM725.333333 896h128c46.933333 0 85.333333-38.4 85.333334-85.333333v-384h-213.333334v469.333333z m128-768H213.333333c-46.933333 0-85.333333 38.4-85.333333 85.333333v128h810.666667V213.333333c0-46.933333-38.4-85.333333-85.333334-85.333333zM128 810.666667c0 46.933333 38.4 85.333333 85.333333 85.333333h128V426.666667H128v384z"></path></svg>
        <div class="gjs-block-label">卡片列表</div>
      `,
    };
  },

  spOptions() {
    return {
      label: '卡片列表',
      icon: 'globe',
      docUrl: '',
      inPorts: [
        {
          uuid: 'in1',
          subType: 'json',
          description: {
            zh_CN: '输入Json'
          }
        }
      ]
    }
  },

  // 组件属性
  componentOptions() {
    return {
      name: cardList,
      droppable: false,
      resizable: true,
      dmode: 'absolute',
      highlightable: false,
      disableChildEdit: true,
      traits: [{
        name: 'cardImage',
        label: '卡片图片',
        changeProp: 1
      },
      {
        type: 'button',
        text: '添加图片',
        full: true, // Full width button
        command: (editor, model) => editor.trigger(`add-img-${model.target.cid}`)
      },{
        name: 'cardHeight',
        label: '卡片高度',
        changeProp: 1,
        type: 'number',
      },{
        name: 'imgHeight',
        label: '图片高度',
        changeProp: 1,
        type: 'number'
      },{
        name: 'imgWidth',
        label: '图片宽度',
        changeProp: 1,
        type: 'number'
      },{
        name: 'titleFontSize',
        label: '标题字号',
        changeProp: 1,
        type: 'number'
      },{
        name: 'titleHeight',
        label: '标题高度',
        changeProp: 1,
        type: 'number'
      },{
        name: 'contentFontSize',
        label: '内容字号',
        changeProp: 1,
        type: 'number'
      },{
        name: 'contentLineHeight',
        label: '内容行高',
        changeProp: 1,
        type: 'number'
      },{
        name: 'scrollUp',
        label: '向上滚动',
        changeProp: 1,
        type: 'checkbox'
      }],
      cardImage: '',
      cardHeight: 150,
      imgHeight: 120,
      imgWidth: 120,
      titleFontSize: 14,
      titleHeight: 30,
      contentFontSize: 12,
      contentLineHeight: 30,
      scrollUp: true
    }
  },

  onModelScript() {
    const cardImage = ('{[ cardImage ]}').toString();
    const cardHeight = parseInt('{[ cardHeight ]}');
    const imgHeight = parseInt('{[ imgHeight ]}');
    const imgWidth = parseInt('{[ imgWidth ]}');
    const titleFontSize = parseInt('{[ titleFontSize ]}');
    const titleHeight = parseInt('{[ titleHeight ]}');
    const contentFontSize = parseInt('{[ contentFontSize ]}');
    const contentLineHeight = parseInt('{[ contentLineHeight ]}');
    const scrollUp = Boolean('{[ scrollUp ]}');

    const defaultData = [
      ["工位名称", "设备工号", "设备类型", "客户名称", "运行状态"],
      ["工位1", "202019112", "某某某设备", "铁建重工", true],
      ["工位2", "", "", "", false],
      ["工位3", "202019112", "某某某设备", "铁建重工", true],
      ["工位4", "202019112", "某某某设备", "铁建重工", true],
      ["工位5", "202019112", "某某某设备", "铁建重工", true],
      ["工位6", "202019112", "某某某设备", "铁建重工", true],
      ["工位7", "202019112", "某某某设备", "铁建重工", true],
      ["工位8", "202019112", "某某某设备", "铁建重工", true],
      ["工位9", "202019112", "某某某设备", "铁建重工", true],
      ["工位10", "202019112", "某某某设备", "铁建重工", true],
      ["工位11", "202019112", "某某某设备", "铁建重工", true],
      ["工位12", "202019112", "某某某设备", "铁建重工", true],
      ["工位13", "202019112", "某某某设备", "铁建重工", true],
      ["工位14", "202019112", "某某某设备", "铁建重工", true],
      ["工位15", "202019112", "某某某设备", "铁建重工", true],
      ["工位16", "202019112", "某某某设备", "铁建重工", true],
      ["工位17", "202019112", "某某某设备", "铁建重工", true],
    ];

    const self = this;
    $(self).children('div.scroll-body').empty();

    if (scrollUp) {
      $(self).children('div.scroll-body').addClass('scroll');
    } else {
      $(self).children('div.scroll-body').removeClass('scroll');
    }

    const renderCard = function (labelList, cardData) {
      let htmlStr = '';
      // card container
      htmlStr += `<div class="card" style="height: ${cardHeight + 'px;'};">`;
      // card image
      const freeImg = 'data:img/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEgAAAA5CAYAAACVk20jAAAD+0lEQVR4nO2baYhNYRjHf8O1NgbZG7KLbPHBWGbKJMwHW8kHiQ8zFCmJspX4YBsfkGUUiYyEKEmhbGXNVkIku5CIbFmb0Ts9p96Oe+975pxzzzlznV9N03t7z3Oe93/f9Xnem9P5+AcixBKgsbizB3gWtmuJsB2woQRqLh+dj4JA9cJ2IOp4FagF0DvCbWwK9PNiwItA+cAF4CIw1IsTGUIN1ZPANaDE7SvcCtQQOCffTivgrBcnMkAH+fKKgCbAMWCIm9e4FegXMAf4ImXLiWlBKZCGHsAloL9WZQNw3Y0xL0PsDFAMvJdyA2AfMN+DTa8MBi4DXTU7C2R1rHZj2+skfRMYZluONwKrgRzPza0dxTLs28hTv4EZ4o9r/FjmHwEjgLvaZ8uAnUD9DAqiMxk4BeTJZ9+BiUClV8N+7YNeA4WyolmUAYdr+Y47wG35++rwmVLgkAxxhToajAJO1K4JyfFzJ/0JGAscAMYDVcBp+e+UIhfvVcP8HdAOeCU+3POrUZk4i6lhVSGT+CG/jaegO7AZmA289NNw1A6rkSM+ixmIBTIQC2SgNqtYayA3FC/9R028n51YdSpQnuxR2keokV64Kptb4xbE6RBblUXiIOGZMicVnSzzg4AbmpgPgSueXQyHcRKeUXwEemmH7aSYhpgSZbutp02XIFRdZBawQ/xuCZSbepJpiM0ECrRyZR0WR7FLznkWpTIXpSSdQCpssE4rfwOWZsz1YKhKEq+qSDeS0gm0XrqhxVo5DNZ1zkuUwWIAMC9Vm1JN0oUS07V4DvSROEs2oCKO94FG0pavkp35pwMk60EJmZh1FmeROIqntkhjbqrIYzKB5ttySaonHfTfx9BZA7zRnJgCjLE7ZReoE7BCK1eHHITPJF8kNKyzTbsbUINdoI2289Zu4FZdVcABeyUiaaFSRov0x/RJusQWx1UK9wTeRqMtGWO45NEsfgJ9gcdoPaixdC8dlbrJdnGQPNoBraxWtq1WwRJIbQC7aZWeAJuC8zF01Cr9Q3OiRFJJNQL1lAo6C6Wr/S+8kI2xjuoguUqgLdqGCclOHv2PxLEot20UOwLLE0murhS7zWMbULvxLj7YyZMcXBAUBBmTzpdrM17p6oMNxwQpkOqtI32wM9oHG44JOqsx1+PzCcmeBkbQAk2QvL1blkqaOWsFQi5ZDXTx3CRgZQb8SUsYAuXJNZmpDusnpOccCcPfsDKr6kC8X/JTasfaLEmdthJkfyChiVB8DfumfYGEP3+LEG/Ep46yww/6Gt8/ROWnCA3kVmp/B3UDJb68YCAWyEAskIFYIAOxQAZigQzEAhmIBTIQC2QgFshALJABdRbrHIVDYSSBP38BGb+g0qXbBaQAAAAASUVORK5CYII=';
      if (cardData[4]) {
        if (cardImage.length > 0) {
          htmlStr += `<img class="device-img" height="${imgHeight}" width="${imgWidth}" src="${cardImage}" alt="">`;
        } else {
          htmlStr += `<div class="device-img device-empty" style="height: ${imgHeight + 'px'}; width: ${imgWidth + 'px'};"></div>`
        }
      } else {
        htmlStr += `<div class="device-img device-free" style="height: ${imgHeight + 'px'}; width: ${imgWidth + 'px'};">`;
        htmlStr += `<img width="72" src="${freeImg}" alt="">`;
        htmlStr += `<span>空闲中...</span>`
        htmlStr += `</div>`;
      }
      // card content
      htmlStr += `<div class="device-msg">`;
      htmlStr += `<div class="title" style="height: ${titleHeight + 'px'}; font-size: ${titleFontSize + 'px'}; line-height: ${titleHeight + 'px'};">${cardData[0]}</div>`;
      htmlStr += `<div class="normal" style="font-size: ${contentFontSize + 'px'}; line-height: ${contentLineHeight + 'px'};">`;
      htmlStr += `<span class="label">${labelList[0] + '：'}</span>`;
      htmlStr += `<span class="value">${cardData[1]}</span>`;
      htmlStr += `</div>`;
      htmlStr += `<div class="normal" style="font-size: ${contentFontSize + 'px'}; line-height: ${contentLineHeight + 'px'};">`;
      htmlStr += `<span class="label">${labelList[1] + '：'}</span>`;
      htmlStr += `<span class="value">${cardData[2]}</span>`;
      htmlStr += `</div>`;
      htmlStr += `<div class="normal high-light" style="font-size: ${contentFontSize + 'px'}; line-height: ${contentLineHeight + 'px'};">`;
      htmlStr += `<span>${labelList[2] + '：'}</span>`;
      htmlStr += `<span>${cardData[3]}</span>`;
      htmlStr += `</div>`;
      htmlStr += `</div>`;
      // card end
      htmlStr += `</div>`;

      return htmlStr;
    }

    for (let i = 1; i < defaultData.length; i++) {
      const labelList = defaultData[0].slice(1, 4);
      const card = renderCard(labelList, defaultData[i]);
      $(self).children('div.scroll-body').append(card);
    }

    if (window.spSocket) {
      var eventName = `call-` + self.getAttribute('id');
      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let value = _data.data.in1;
          if (value) {
            const data = JSON.parse(value);
            $(self).children('div.scroll-body').empty();
            $(self).children('div.scroll-body.scroll').css({ 'animation-duration': data.length * 5 + 's' })
            for (let i = 1; i < data.length; i++) {
              const labelList = data[0].slice(1, 4);
              const card = renderCard(labelList, data[i]);
              $(self).children('div.scroll-body').append(card);
            }
          }
        }
      });
    }
  },

  onViewInit({editor}) {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="scroll-body"></div>
      `)
    }
    const evn = `
      change:cardImage
      change:fontSize
      change:cardHeight
      change:imgHeight
      change:imgWidth
      change:titleFontSize
      change:titleHeight
      change:contentFontSize
      change:contentLineHeight
      change:scrollUp
    `
    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)));

    var openAssetsModalAddStatus = function() {
      const self = this;
      if (editor) {
          editor.runCommand('open-assets', {
              target: this.model,
              types: ['image'],
              accept: 'image/*',
              onSelect(model) {
                if (model) {
                  const src = model.get('src');

                  // 设置卡片内图片
                  self.model.set('cardImage', src);
                  self.model.trigger('change:cardImage', self.model, src);
                }
                editor.Modal.close();
                editor.AssetManager.setTarget(null);
              }
          });
      }
    }

    editor.on(`add-img-${this.model.cid}`, () => {
      openAssetsModalAddStatus.call(this);
    })
  }
}
