import { checkboxGroup, CATEGORIES } from '../../configuration/constants'

// 复选框组, 低配版, 数据格式较为简单
export default {
  // 组件名称  
  name: checkboxGroup,

  viewTemplate() {
    return `
      <div 
        class="${checkboxGroup}-wrap" 
        data-gjs-type="${checkboxGroup}"
      ></div>
    `
  },

  viewStyle() {
    return `
      <style>
      .${checkboxGroup}-wrap {
        padding: 10px;
      }

      .${checkboxGroup}-title {
        font-weight: bold;
        padding: 5px;
        margin-top: 0;
        margin-bottom: 5px;
      }

      .${checkboxGroup}-body {
        display: flex;
      }

      .${checkboxGroup}-iso {
        padding: 5px;
      }

      .${checkboxGroup}-direction-x {
        flex-direction: row;
      }
      
      .${checkboxGroup}-direction-y {
        flex-direction: column;
      }

      </style>
    `
  },

  blockOptions() {
    return {
      category: CATEGORIES.FORM,
      label: '复选框',
      attributes: { class: 'fa fa-check-square' }
    };
  },

  spOptions() {
    // 输入输出数据类型均为 [{ name: xxx, checked: true }, {...}]
    return {
      label: '复选框',
      icon: 'globe',
      docUrl: 'https://www.yuque.com/docs/share/439217d0-c0d9-4a30-ba9b-a4876aa34dca?#',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入'
        }
      }],
      outPorts: [{
        uuid: 'out1',
        subType: 'json',
        description: {
          zh_CN: '输出'
        }
      }]
    }
  },

  componentOptions() {
    return {
      name: checkboxGroup,
      resizable: true,
      dmode: false,
      traits: [{
        name: 'arrangement',
        label: '排列方式',
        type: 'select',
        options: ['vertical', 'horizontal'],
        changeProp: 1
      }, {
        name: 'add',
        type: 'button',
        label: '增加',
        text: '添加选项',
        full: true,
        command: editor => {
          const comps = editor.getSelected().get('components')
          // 拿到子节点的 dom
          const checkboxsDOM = comps.models[1].get('components')
          const checkboxGroupWrapper = editor.getSelected().getEl()
          checkboxsDOM.add(`
            <div class="${checkboxGroup}-iso">
              <input type="checkbox" id="1">
              <span>选项</span>
            </div>
          `)
          // 重新子元素设置无法拖动
          checkboxGroupWrapper.querySelectorAll('*').forEach(descendant => descendant.setAttribute('draggable', 'false'))
        }
      }],
      arrangement: 'vertical',
    }
  },

  onModelScript() {
    const arrangement = ('{[ arrangement ]}').toString()
    const self = this
    const checkboxGroupBody = self.querySelector('.checkbox-group-body')

    // 设置排列方向
    const direction = arrangement === 'vertical'
      ? `checkbox-group-direction-y`
      : `checkbox-group-direction-x`
    checkboxGroupBody.className = `checkbox-group-body ${direction}`

    // 设置无法拖动
    // 通过 * 拿到所有子元素, 设置无法拖动
    self.querySelectorAll('*').forEach(descendant => descendant.setAttribute('draggable', 'false'))

    // 监听输入端数据
    if (window.spSocket) {
      const eventName = `call-` + self.getAttribute('id');
      window.spSocket.subscribe({
        eventName,
        callback: function (res) {
          if (res.data.in1) {
            // 数据格式为 [{ name: xxx, checked: true }, { ... }]
            const checkboxs = JSON.parse(res.data.in1)
            // 重新渲染 checkbox
            checkboxGroupBody.innerHTML = checkboxs.reduce((result, checkbox) => {
              const { name, checked } = checkbox
              return result + `
                <div class="checkbox-group-iso">
                  <input type="checkbox" ${checked ? 'checked' : ''}>
                  <span>${name}</span>
                </div>
              `
            }, '')
            // 将数据作为输出发送
            window.spSocket.send({
              eventName,
              data: {
                success: true,
                out1: res.data.in1
              }
            });
          }
        }
      })
    }

    // 监听是否被选上
    checkboxGroupBody.addEventListener('change', e => {
      const checkboxInput = e.target

      if (checkboxInput.matches('input[type=checkbox]')) {
        // 判断点击的是否是 input
        const output = Array.from(checkboxGroupBody.children).map((c, i) => {
          const name = c.querySelector('span').innerHTML
          const checked = c.querySelector('input').checked
          return {
            name,
            checked,
          }
        })

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

          window.spSocket.send({
            eventName: eventName,
            data: {
              success: true,
              out1: JSON.stringify(output)
            }
          });
        }

      }
    })
  },

  onViewInit() {
    const comps = this.model.get('components');
    const arrangement = this.model.get('arrangement')
    // 默认 3 个选项

    const direction = arrangement === 'vertical'
      ? `${checkboxGroup}-direction-y`
      : `${checkboxGroup}-direction-x`

    if (!comps.length) {
      comps.reset();
      comps.add(`
        <p class="${checkboxGroup}-title">复选框标题</p>
        <div class="${checkboxGroup}-body ${direction}">
          ${`<div class="${checkboxGroup}-iso">
            <input type="checkbox" id="1">
            <span>选项</span>
          </div>`.repeat(3)}
        </div>
      `)
    }
    const evn = "change:arrangement"
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}