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

// 定位组件
export default {
  // 组件名称
  name: geolocation,

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

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

  // 编辑器右侧管理器中显示属性配置
  blockOptions() {
    return {
      label: '开启定位',
      attributes: { class: 'fa fa-map-marker' }
    }
  },

  // 后面板显示属性配置
  spOptions() {
    // 输入数据为: { mode: 'accurate' | 'fuzzy' }, 选择不同模式
    return {
      label: '开启定位',
      icon: 'globe',
      docUrl: 'https://xuelangyun.yuque.com/docs/share/f5ffc80a-93ae-4b37-ae88-b74d0cdc9d14?# 《开启定位》',
      inPorts: [{
        uuid: 'in1',
        subType: 'json',
        description: {
          zh_CN: '输入配置',
        }
      }],
      // 输出数据根据不同模式进行不同输出
      outPorts: [{
        uuid: 'out1',
        subType: 'json',
        description: {
          zh_CN: '输出定位',
        }
      }]
    }
  },

  componentOptions() {
    return {
      name: geolocation,
      resizable: true,
      dmode: 'absolute',
      droppable: false,
      traits: [{
        name: 'mode',
        label: '定位模式',
        type: 'select',
        options: ['accurate', 'fuzzy'],
        changeProp: 1,
      }],
      mode: 'accurate'
    }
  },

  onModelScript() {
    const self = this
    self.mode = ('{[ mode ]}').toString()
    const geolocationButton = self.querySelector('.btn-geolocation')
    // 加入高德地图 api
    const amapURL = 'https://webapi.amap.com/maps?v=1.4.15&key=74433b3634087a24acd80fb30a682da5'
    const amapScript = document.createElement('script');
    amapScript.charset = 'utf-8';
    amapScript.src = amapURL;
    document.head.appendChild(amapScript);

    // 设置无法进行内部元素拖动
    self.querySelectorAll('*').forEach(descendant => descendant.setAttribute('draggable', 'false'))

    // 发送 socket 数据
    const sendOutputWithSocket = output => {
      if (window.spSocket) {
        const eventName = `call-` + self.getAttribute('id');
        window.spSocket.send({
          eventName,
          data: {
            success: true,
            out1: typeof output === 'string' ? output : JSON.stringify(output)
          }
        });
      }
    }
    // 使用原生浏览器 api 获取数据
    const getPositionWithNative = () => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          const latitude = position.coords.latitude
          const longitude = position.coords.longitude
          return {
            latitude,
            longitude
          }
        }, (error) => {
          return error
        })
      } else {
        return {
          code: 'NOT_SUPPORT',
          message: 'Geolocation is not supported by this browser'
        }
      }
    }

    // event handler
    if (!self.handleClick) {

      self.handleClick = function(e) {
        // 高德地图
        // https://lbs.amap.com/api/javascript-api/guide/services/geolocation
        AMap.plugin('AMap.Geolocation', function() {
          const _geolocation = new AMap.Geolocation({
            // 10 秒后停止请求
            timeout: 10000,
          })
          // 判断配置使用哪种模式
          const options = {
            accurate: _geolocation.getCurrentPosition.bind(_geolocation),
            fuzzy: _geolocation.getCityInfo.bind(_geolocation),
          }
          Object.keys(options).forEach(key => {
            if (self.mode === key) {
              options[key]((status, result) => {
                if (status === 'complete') {
                  sendOutputWithSocket(result)
                } else {
                  // 使用原生 geolocation api 获取
                  const currentPosition = getPositionWithNative()
                  sendOutputWithSocket(currentPosition)
                }
              })
            }
          })
        });
      }
    }
    // 监听 socket
    if (window.spSocket) {
      const eventName = `call-` + self.getAttribute('id');

      window.spSocket.subscribe({
        eventName,
        callback: function(res) {
          if (res.data.in1) {
            // 数据格式为 { mode: 'accurate' | 'fuzzy' }
            // 修改 mode 引用
            const data = JSON.parse(res.data.in1)
            self.mode = data['mode'] || 'accurate'
            // 保证只绑定一个 event handler
            geolocationButton.removeEventListener('click', self.handleClick)
            geolocationButton.addEventListener('click', self.handleClick)

          }
        }
      })
    }
    // 保证只绑定一个 event handler
    geolocationButton.removeEventListener('click', self.handleClick)
    geolocationButton.addEventListener('click', self.handleClick)
  },

  onViewInit() {
    const comps = this.model.get('components');
    if (!comps.length) {
      comps.reset();
      comps.add(`
        <button class="btn-${geolocation}">获取当前定位</button>
      `)
    }
    const evn = "change:mode"
    this.listenTo(this.model, evn, this.updateScript)
    this.listenTo(this.model, evn, this.em.handleUpdates.bind(this.em));
  },

}