import { cascadeAddress, CATEGORIES } from '../../configuration/constants'
import pcaCode from '../../assets/pca-code.txt'

// 三级级联地址 城-乡-城
export default {
  // 组件名称
  name: cascadeAddress,

  // 前面板 html 模板
  viewTemplate() {
    return `
      <div
        class="${cascadeAddress}-wrap"
        data-gjs-type="${cascadeAddress}"
      ></div>
    `
  },

  // 前面板 html 样式
  viewStyle() {
    return `
      <style>
        .${cascadeAddress}-wrap {
          width: 500px;
          padding: 10px;
        }

        .scrollable-menu {
          height: auto;
          max-height: 150px;
          overflow-x: hidden;
        }
      </style>
    `
  },

  // 编辑器右侧块管理器中显示属性配置
  blockOptions() {
    return {
      label: '级联地址<br>选择',
      attributes: { class: 'fa fa-address-card' }
    }
  },

  // 后面板显示属性配置
  spOptions() {
    /**
     * 输出数据为
     * {
     *   province: {
     *     code: 43,
     *     name: 湖南省
     *   },
     *   city: {
     *     code: 4301,
     *     name: 长沙市
     *   },
     *   area: {
     *     code: 430102,
     *     name: 芙蓉区
     *   },
     *   detailedAddress: xxx
     * }
    */
    return {
      label: '级联地址选择',
      icon: 'globe',
      docUrl: 'https://www.yuque.com/docs/share/78b63db2-f642-4f48-99b7-1614e8accf71?#',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入地址'
        }
      }],
      outPorts: [{
        uuid: 'out1',
        subType: 'json',
        description: {
          zh_CN: '输出地址'
        }
      }]
    }
  },

  componentOptions() {
    return {
      name: cascadeAddress,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      // 暂时没有任何配置
      traits: [],
      // 将省市区数据映射到 props 上
      pcaCode,
    }
  },

  onModelScript() {
    const self = this
    const addressForm = self.querySelector('form')
    const provinceButton = self.querySelector('.cascade-address-province > button')
    const cityButton = self.querySelector('.cascade-address-city > button')
    const areaButton = self.querySelector('.cascade-address-area > button')
    const provinceMenu = self.querySelector('.cascade-address-province > .dropdown-menu')
    const cityMenu = self.querySelector('.cascade-address-city > .dropdown-menu')
    const areaMenu = self.querySelector('.cascade-address-area > .dropdown-menu')
    const detailedAddressTextarea = self.querySelector('.cascade-address-detailed > textarea')
    // pcaCode 为数据, 用户可以通过输入数据自定义
    let pcaCode = JSON.parse(('{[ pcaCode ]}').toString())
    // 设置子元素不可移动
    self.querySelectorAll('*').forEach(el => el.setAttribute('draggable', 'false'))

    const resetAll = () => {
      // 重置所有数据
      provinceButton.dataset.code = '00'
      provinceButton.innerHTML = '省'
      cityButton.innerHTML = '市'
      cityButton.dataset.code = '0000'
      areaButton.innerHTML = '区'
      areaButton.dataset.code = '000000'

      provinceMenu.innerHTML = '<span class="dropdown-item" data-code="00">请选择</span>'
      cityMenu.innerHTML = '<span class="dropdown-item" data-code="0000">请选择</span>'
      areaMenu.innerHTML = '<span class="dropdown-item" data-code="000000">请选择</span>'
    }

    const insertDropdownItems = (data, target) => {
      // 根据数据和 button 动态插入到 dropdown menu 里
      // target 为 button
      // data 为完整的省市区 JSON 数据
      if (target.parentNode.matches('.cascade-address-province')) {
        const provinceDropdownMenu = target.nextSibling
        // 插入 html
        const provinceItems = data.reduce((result, { code, name }) => {
          return result + `<span class="dropdown-item" data-code="${code}">${name}</span>`
        }, '')
        if (provinceDropdownMenu.children.length <= 1) {
          // 判断 province 数据是否大于 1, 大于 1 不用添加数据, 否则添加
          provinceDropdownMenu.insertAdjacentHTML('beforeend', provinceItems)
        }
      } else if (target.parentNode.matches('.cascade-address-city')) {
        const cityDropdownMenu = target.nextSibling
        const provinceButton = target.parentNode.previousSibling.querySelector('button')
        const provinceCode = provinceButton.dataset.code
        if (provinceCode !== '00') {
          // 只有在 province 被选中的情况下才进行插入
          const cityData = data.filter(province => province['code'] === provinceCode)[0].children
          const cityItems = cityData.reduce((result, { code, name }) => {
            return result + `<span class="dropdown-item" data-code="${code}">${name}</span>`
          }, '')
          cityDropdownMenu.innerHTML = '<span class="dropdown-item" data-code="0000">请选择</span>'
          // rest 并插入新数据
          cityDropdownMenu.insertAdjacentHTML('beforeend', cityItems)
        }
      } else if (target.parentNode.matches('.cascade-address-area')) {
        const areaDropdownMenu = target.nextSibling
        const cityButton = target.parentNode.previousSibling.querySelector('button')
        const cityCode = cityButton.dataset.code
        const provinceCode = cityCode.slice(0, 2)
        if (cityCode !== '0000' && provinceCode !== '00' && areaDropdownMenu.children.length <= 1) {
          // 只有在 city 被选中的情况下才进行插入
          const cityData = data.filter(province => province['code'] === provinceCode)[0].children
          const areaData = cityData.filter(city => city['code'] == cityCode)[0].children
          const areaItems = areaData.reduce((result, { code, name }) => {
            return result + `<span class="dropdown-item" data-code="${code}">${name}</span>`
          }, '')

          // rest 并插入新数据
          areaDropdownMenu.innerHTML = '<span class="dropdown-item" data-code="000000">请选择</span>'
          areaDropdownMenu.insertAdjacentHTML('beforeend', areaItems)
        }

      }
    }

    addressForm.addEventListener('submit', e => {
      // 发送数据
      e.preventDefault()
      const output = {
        province: {
          code: provinceButton.dataset.code || '00',
          name: provinceButton.innerHTML === '省' ? '未选择' : provinceButton.innerHTML
        },
        city: {
          code: cityButton.dataset.code || '0000',
          name: cityButton.innerHTML === '市' ? '未选择' : cityButton.innerHTML
        },
        area: {
          code: areaButton.dataset.code || '000000',
          name: areaButton.innerHTML === '区' ? '未选择' : areaButton.innerHTML
        },
        detailedAddress: detailedAddressTextarea.value.trim()
      }

      if (window.spSocket) {
        const eventName = `call-` + self.getAttribute('id');
        // 将数据作为输出发送
        window.spSocket.send({
          eventName,
          data: {
            success: true,
            out1: JSON.stringify(output)
          }
        });
      }
    })

    self.querySelectorAll('.dropdown-menu').forEach(el => {
      // 选中 dropdown menu 里的选项触发的逻辑
      el.addEventListener('click', e => {
        const target = e.target
        if (target.matches('.dropdown-item')) {
          // 点击 dropdown item 选中显示到 dropdown button 上
          const selectedItem = target.innerHTML
          const dropdownIso = target.parentNode.parentNode
          const dropdownButton = target.parentNode.previousSibling
          if (selectedItem !== '请选择') {
            // 将选中的值填入 button 里
            dropdownButton.innerHTML = selectedItem
            // 选中一个新的选项之后要重新 reset
            if (dropdownIso.matches('.cascade-address-province')) {
              // city 和 area 里的数据要清除
              cityMenu.innerHTML = '<span class="dropdown-item" data-code="0000">请选择</span>'
              areaMenu.innerHTML = '<span class="dropdown-item" data-code="000000">请选择</span>'
              // 同时清除 button 里面的值
              cityButton.innerHTML = '市'
              cityButton.dataset.code = '0000'
              areaButton.innerHTML = '区'
              areaButton.dataset.code = '000000'
            } else if (dropdownIso.matches('.cascade-address-city')) {
              // area 里的数据要清除
              areaMenu.innerHTML = '<span class="dropdown-item" data-code="000000">请选择</span>'
              // 同时清除 button 里面的值
              areaButton.innerHTML = '区'
              areaButton.dataset.code = '000000'
            }
          } else {
            // 使用默认值
            if (dropdownIso.matches('.cascade-address-province')) {
              dropdownButton.dataset.code = '00'
              dropdownButton.innerHTML = '省'
              // city 和 area 里的数据要清除
              cityMenu.innerHTML = '<span class="dropdown-item" data-code="0000">请选择</span>'
              areaMenu.innerHTML = '<span class="dropdown-item" data-code="000000">请选择</span>'
              // 同时清除 button 里面的值
              cityButton.innerHTML = '市'
              cityButton.dataset.code = '0000'
              areaButton.innerHTML = '区'
              areaButton.dataset.code = '000000'
            } else if (dropdownIso.matches('.cascade-address-city')) {
              dropdownButton.dataset.code = '0000'
              dropdownButton.innerHTML = '市'
              // area 里的数据要清除
              areaMenu.innerHTML = '<span class="dropdown-item" data-code="000000">请选择</span>'
              // 同时清除 button 里面的值
              areaButton.innerHTML = '区'
              areaButton.dataset.code = '000000'
            } else if (dropdownIso.matches('.cascade-address-area')) {
              dropdownButton.dataset.code = '000000'
              dropdownButton.innerHTML = '区'
            }
          }
          // 设置 code
          dropdownButton.dataset.code = target.dataset.code || 0
        }
      })
    })

    self.querySelectorAll('button').forEach(btn => {
      // 点击 省/市/区触发的逻辑
      btn.addEventListener('click', e => {
        const target = e.target

        // 不管是否存在 socket, 点击都要触发 insertDropdownItems 方法
        try {
          insertDropdownItems(pcaCode, target)
        } catch (error) {
          // 重置所有数据
          resetAll()
          // 使用原有数据
          pcaCode = JSON.parse(('{[ pcaCode ]}').toString())
          insertDropdownItems(pcaCode, target)

          // 插入提示信息
          const alertHTML = `
            <div class="alert alert-pca alert-warning alert-dismissible fade show" role="alert">
              <span>提供数据有误, 使用自带的<strong>省-市-区</strong>数据</span>
              <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
          `
          addressForm.insertAdjacentHTML('beforebegin', alertHTML)
        }
      })
    })

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

      window.spSocket.subscribe({
        eventName,
        callback: function(res) {
          if (res.data.in1) {
            // 插入用户数据
            pcaCode = JSON.parse(res.data.in1)
          }
        }
      })
    }
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <form>
          <div class="btn-group d-flex justify-content-between ${cascadeAddress}-all">
            <div class="dropdown ${cascadeAddress}-iso ${cascadeAddress}-province">
              <button
                class="btn btn-light dropdown-toggle"
                type="button"
                data-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"
                data-code="00"
              >省</button>
              <div class="dropdown-menu scrollable-menu" aria-labelledby="dropdownMenuButton">
                <span class="dropdown-item" data-code="00">请选择</span>
              </div>
            </div>
            <div class="dropdown ${cascadeAddress}-iso ${cascadeAddress}-city">
              <button
                class="btn btn-light dropdown-toggle"
                type="button"
                data-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"
                data-code="0000"
              >市</button>
              <div class="dropdown-menu scrollable-menu" aria-labelledby="dropdownMenuButton">
                <span class="dropdown-item" data-code="0000">请选择</span>
              </div>
            </div>
            <div class="dropdown ${cascadeAddress}-iso ${cascadeAddress}-area">
              <button
                class="btn btn-light dropdown-toggle"
                type="button" data-toggle="dropdown"
                aria-haspopup="true"
                aria-expanded="false"
                data-code="000000"
              >区</button>
              <div class="dropdown-menu scrollable-menu" aria-labelledby="dropdownMenuButton">
                <span class="dropdown-item" data-code="000000">请选择</span>
              </div>
            </div>
          </div>

          <div class="form-group ${cascadeAddress}-detailed mt-3">
            <textarea class="form-control" placeholder="详细地址"></textarea>
          </div>

          <button type="submit" class="btn btn-primary">提交</button>
        </form>
      `)
    }
    const evn = ""
    this.listenTo(this.model, evn, this.updateScript);
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  }
}
