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

// 手机组件
export default {
  // 组件名称

  name: phone,

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

        .${phone}-input-group {
          width: 300px;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: '输入号码',
      attributes: { class: 'fa fa-mobile' }
    };
  },
  
  // 后面板显示属性配置
  spOptions() {
    // 输出数据为 { phone: xxx, validation: { type: general | detailed, result: true | false } }
    return {
      label: '输入号码',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/d07f0f8f-0e4c-48f1-9721-4c5a21ee46ef?# 《输入号码》',
      outPorts: [{
        uuid: 'out1',
        subType: 'json',
        description: {
          zh_CN: '输出手机号码'
        }
      }]
    }
  },

  componentOptions() {
    return {
      name: phone,
      dmode: 'absolute',
      droppable: false,
      traits: [{
        name: 'validation',
        label: '验证',
        type: 'select',
        options: ['general', 'detailed'],
        changeProp: 1
      }],
      validation: 'detailed',
    }
  },

  onModelScript() {
    const self = this
    self.validationType = ('{[ validation ]}').toString()
    const phoneInput = self.querySelector('.phone-input')

    // 设置无法拖动
    self.querySelectorAll('*').forEach(descendant => descendant.setAttribute('draggable', 'false'))

    const validateInput = input => {
      if (self.validationType === 'general') {
        // 广泛测试仅测试长度为 11 位数
        return /^1\d{10}$/.test(input)
      } else if (self.validationType === 'detailed') {
        // 细节测试测试具体的手机格式
        // https://gist.github.com/JerryC8080/b4005ef5c4902b1ea7a0
        return /^1[3-9](\d{9})$/.test(input)
      }
    }

    if (!self.handleInput) {
      self.handleInput = e => {
        // 限制只允许输入数字
        e.target.value = e.target.value.replace(/[^\d]+/g,'')
      }
    }

    if (!self.handleFocus) {
      self.handleFocus = e => {
        // 删除提示
        const feedbacks = e.target.parentNode.querySelectorAll('.feedback')
        if (feedbacks.length > 0) {
          feedbacks.forEach(el => el.remove())
        }
        e.target.className = 'form-control phone-input'
      }
    }

    if (!self.handleBlur) {
      self.handleBlur = e => {
        const phoneInputValue = e.target.value
        const validationResult = validateInput(phoneInputValue)
        const phoneInputGroup = e.target.parentNode
        const output = {
          phone: phoneInputValue,
          validation: {
            type: self.validationType,
            result: validationResult
          }
        }
        // 根据结果改变 style
        if (validationResult) {
          phoneInput.className = 'form-control phone-input is-valid'
          phoneInputGroup.insertAdjacentHTML('beforeend', `
            <div class="valid-feedback feedback">
              Looks good!
            </div>
          `)
        } else {
          phoneInput.className = 'form-control phone-input is-invalid'
          phoneInputGroup.insertAdjacentHTML('beforeend', `
            <div class="invalid-feedback feedback">
              Please enter valid phone number
            </div>
          `)
        }

        if (window.spSocket) {
          const eventName = `call-` + self.getAttribute('id');
          window.spSocket.send({
            eventName: eventName,
            data: {
              success: true,
              out1: JSON.stringify(output)
            }
          });
        }
      }
    }

    // 注册事件
    phoneInput.removeEventListener('input', self.handleInput)
    phoneInput.addEventListener('input', self.handleInput)
    phoneInput.removeEventListener('blur', self.handleBlur)
    phoneInput.addEventListener('blur', self.handleBlur)
    phoneInput.removeEventListener('focus', self.handleFocus)
    phoneInput.addEventListener('focus', self.handleFocus)

  },

  onViewInit() {
    const comps = this.model.get('components');

    if (!comps.length) {
      comps.reset();
      comps.add(`
        <div class="input-group ${phone}-input-group">
          <div class="input-group-prepend">
            <span class="input-group-text">
              <i class="fas fa-mobile-alt"></i>
            </span>
          </div>
          <input 
            type="text"
            class="form-control ${phone}-input"
            placeholder="输入手机号"
            maxlength="11"
          >
        </div>
      `)
    }
    const evn = "change:validation"
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}