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

export default {

  // 组件名称
  name: groupLed,

  // 前面板html模板
  viewTemplate() {
    return `
      <div data-gjs-type="${groupLed}" class="${groupLed}"></div>
    `
  },
  // 前面板html样式
  viewStyle() {
    return `
      <style>
        .${groupLed} {
          padding: 10px;
        }
        .${groupLed} .${dynamicLed}  {
          position: relative;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: `
        <svg class="gjs-block-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
          <path class="gjs-block-svg-path" d="M402.186 138.976c64.351 0 122.15 26.063 164.096 68.33 42.004 41.739 68.24 99.919 68.24 164.358 0 64.087-26.236 122.032-68.24 163.948-41.945 42.121-99.745 67.979-164.096 67.979-64.116 0-122.324-25.857-164.504-67.979-41.945-41.916-67.802-99.861-67.802-163.948 0-64.438 25.856-122.619 67.802-164.358C279.861 165.039 338.069 138.976 402.186 138.976L402.186 138.976zM523.049 250.245 523.049 250.245c-30.83-30.976-73.419-49.755-120.863-49.755-47.385 0-90.208 18.779-120.862 49.755-31.24 31.328-50.429 73.652-50.429 121.419 0 47.035 19.189 90.091 50.429 120.863 30.654 30.975 73.477 49.755 120.862 49.755 47.444 0 90.033-18.78 120.863-49.755 31.269-30.772 50.369-73.828 50.369-120.863C573.418 323.897 554.317 281.573 523.049 250.245L523.049 250.245zM804.644 500.161 804.644 500.161c43.875 0 84.621 18.603 113.901 47.443 29.074 29.163 47.414 69.734 47.414 113.961 0 44.84-18.34 84.826-47.414 114.193-29.105 29.397-69.528 47.414-113.901 47.414-44.959 0-85.119-18.017-114.282-47.414l-1.286-1.522c-28.695-29.015-46.129-68.561-46.129-112.671 0-44.227 18.105-84.798 47.415-113.961l1.551-1.813C721.191 517.8 760.563 500.161 804.644 500.161L804.644 500.161zM875.049 590.896 875.049 590.896c-17.813-18.252-42.793-29.426-70.405-29.426-27.32 0-52.096 10.384-69.938 27.817l-1.376 1.608c-17.725 18.019-29.074 43.291-29.074 70.67 0 27.056 10.471 51.949 28.313 70.113l0.761 0.819c18.34 18.019 43.495 29.191 71.313 29.191 27.231 0 52.593-11.173 70.405-29.191l0.205 0c18.105-18.048 29.367-43.525 29.367-70.933C904.621 634.187 893.359 608.914 875.049 590.896l0.205 0L875.049 590.896 875.049 590.896zM476.073 657.266 476.073 657.266c37.617 0 72.191 15.678 96.936 40.716l0.409 0.235 0.469 0.584c24.307 24.891 39.575 58.939 39.575 96.76 0 37.617-15.473 72.072-40.044 96.966l-0.409 0-0.468 0.79c-24.805 24.688-59.086 39.721-96.468 39.721-38.201 0-72.599-15.472-97.58-40.511l0 0-0.644-0.584c-24.512-24.688-39.78-58.971-39.78-96.382 0-37.82 15.444-72.453 40.424-97.344l0-0.235 0.703-0.351C403.999 672.708 438.281 657.266 476.073 657.266L476.073 657.266zM530.01 741.271 530.01 741.271c-13.98-13.484-33.111-22.491-53.937-22.491-21.294 0-40.658 9.007-54.347 22.491-13.807 13.924-22.348 33.316-22.348 54.289 0 20.943 8.541 40.336 22.348 54.057 13.688 13.688 33.052 21.966 54.347 21.966 20.826 0 39.957-8.277 53.937-21.966 13.924-13.721 22.144-33.113 22.144-54.057C552.153 774.236 543.934 755.195 530.01 741.271L530.01 741.271z"></path>
        </svg>
        <div class="gjs-block-label">组合灯</div>
      `
    };
  },

  spOptions() {
    return {
      label: '组合灯',
      icon: 'globe',
      docUrl: '',
      author: '宗介',
      email: 'zongjie.wxt@xuelangyun.com',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入Json'
        }
      }],
    }
  },

  // 组件属性
  componentOptions() {
    return {
      droppable: true,
      resizable: true,
      dmode: 'absolute',
      highlightable: true,
      traits: [
        {
          name: 'statusType',
          label: '状态类型',
          changeProp: 1
        },
        {
          label: '灯宽度',
          changeProp: 1,
          name: 'width',
          type: 'number'
        },
        {
          label: '灯高度',
          changeProp: 1,
          name: 'height',
          type: 'number'
        },
        {
          name: 'imageStatusPath',
          label: '灯状态图片路径',
          changeProp: 1
        },
        {
          type: 'button',
          text: '添加状态图片',
          full: true, // Full width button
          command: (editor, model) => editor.trigger(`add-img-${model.target.cid}`)
        },
        {
          name: 'imageOffPath',
          label: '灯熄灭图片路径',
          changeProp: 1
        },
        {
          type: 'button',
          text: '更换图片',
          full: true, // Full width button
          command: (editor, model) => editor.trigger(`reselect-${model.target.cid}`)
        }
      ],
      offColor: '#888',
      statusType: "normal,warning,error",
      width: 40,
      height: 40,
      imageStatusPath: '',
      imageOffPath: '',
    }
  },

  onModelScript() {
    const statusType = ('{[ statusType ]}').toString();
    const width = Boolean('{[ width ]}') ? Number('{[ width ]}') : 40;
    const height = Boolean('{[ height ]}') ? Number('{[ height ]}') : 40;
    let imageStatusPath = ('{[ imageStatusPath ]}').toString();
    const imageOffPath = ('{[ imageOffPath ]}').toString();

    if (imageStatusPath.indexOf('&&') > 0) {
      imageStatusPath = imageStatusPath.split('&&').map(item => item.trim())
    } else if (Boolean(imageStatusPath)) {
      imageStatusPath = [imageStatusPath.trim()]
    } else {
      imageStatusPath = []
    }

    const getStatusMap = function (list) {
      const statusMap = {};
      if (statusType.indexOf(',') > 0) {
        statusType.split(',').map((item, index) => {
          const _i = index % list.length;
          statusMap[item.trim()] = list[_i];
        })
      } else if (Boolean(statusType)) {
        statusMap[statusType] = list[0]
      }
      return statusMap;
    }

    let statusMap;
    let svgDomOff;

    statusMap = getStatusMap(imageStatusPath);
    let imageDom;
    if (imageOffPath !== '') {
      imageDom = `<image width="100%" height="100%" href="${imageOffPath}" />`
    } else {
      imageDom = `<text width="100%"  height="100%" text-anchor="middle" dominant-baseline="middle" x=20 y=20 >灯</text>`
    }
    svgDomOff = "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' width='100%' height='100%'>" + imageDom + "</svg>";
    
    
    const self = this;
    let ledDom = $(self).find('.dynamic-led');
    $(ledDom).attr('style', 'width:' + width + 'px; height:' + height + 'px;');
    $(ledDom).html(svgDomOff);

    const childNodes = self.childNodes;
    if (window.spSocket) {
      var eventName = `call-` + self.getAttribute('id');

      function get(object, path, defaultValue) {
        const paths = path.split('.');

        var result = paths.reduce(function(obj, key) {
          if (!obj) {
            return;
          }
          return obj[key]
        }, object);

        return result === undefined ? defaultValue : result;
      }

      window.spSocket.subscribe({
        eventName: eventName,
        callback: function (_data) {
          let dataObj = JSON.parse(_data.data.in1);
          if (dataObj instanceof Array) {
            dataObj = dataObj[0];
          }
          childNodes.forEach(function(node) {
            if (node.getAttribute) {
              const key = node.getAttribute('data-source');
              const value = get(dataObj, key);
              if (value) {
                const statusValue = statusMap[value];
                if(statusValue) {
                  const imageDom = `<image width="100%" height="100%" href="${statusValue}" alt="${statusValue}"/>`
                  const svgDom = "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' width='100%' height='100%'>" + imageDom + "</svg>";
                  $(node).html(svgDom);
                }
              }
            }
          })
        }
      });
    }
  },

  onViewInit({editor}) {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="${dynamicLed}" data-gjs-type="${dynamicLed}">灯</div>
        <div class="${dynamicLed}" data-gjs-type="${dynamicLed}">灯</div>
        <div class="${dynamicLed}" data-gjs-type="${dynamicLed}">灯</div>
      `)
    }

    this.updateScript();
    const evn = `
      change:statusType
      change:imageStatusPath
      change:imageOffPath
      change:width
      change:height
    `;
    this.listenTo(this.em, 'component:create', throttle.bind(this, this.updateScript.bind(this)));
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));

    var openAssetsModal = 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('imageOffPath', src);
                  self.model.trigger('change:imageOffPath', self.model, src);
                }
                editor.Modal.close();
                editor.AssetManager.setTarget(null);
              }
          });
      }
    }
    
    editor.on(`reselect-${this.model.cid}`, () => {
      openAssetsModal.call(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');
                  const pre = self.model.get('imageStatusPath');
                  let newPath;
                  if(pre.trim() !== "") {
                    newPath = `${pre} && ${src}`;
                  } else {
                    newPath = src;
                  }

                  self.model.set('imageStatusPath', newPath);
                  self.model.trigger('change:imageStatusPath', self.model, src);
                }
                editor.Modal.close();
                editor.AssetManager.setTarget(null);
              }
          });
      }
    }

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