/**
 * @author  daya
 * @createDate  2021/10/29 18:47
 * 备注:用于图表的公共方法
 **/
// import { mapTheme } from './components/map/map.js'
// eslint-disable-next-line no-unused-vars
import {optStyle} from './components/line/ts-vue-line-style-1'
import {setDataZoom} from './charts'
// let BMap = null
let common = {
  // 深拷贝
  async deepCopy (target) {
    if (typeof target !== 'object') { return {} }
    // 判断目标类型，来创建返回值
    const newObj = target instanceof Array ? [] : {}

    for (const item in target) {
      // 只复制元素自身的属性，不复制原型链上的
      if (target.hasOwnProperty(item) && target[item] !== {}) {
        newObj[item] = typeof target[item] === 'object' ? await this.deepCopy(target[item]) : target[item]
      }
    }
    return newObj
  },
  // 修改图表配置 option:图标配置 commonConfig:父组件传的修改配置 data:图表数据 config：图表预设可选项
  async changeChartOpt (option, commonConfig, data, config) {
    // 目前常用可配置为这7个，title待定
    let xAxisName = commonConfig.xAxisName
    let yAxisName = commonConfig.yAxisName
    let tooltipName = commonConfig.tooltipName
    let legendName = commonConfig.legendName
    let colorName = commonConfig.colorName
    let seriesName = commonConfig.seriesName
    let dataZoomLen = commonConfig.dataZoomLen
    // let styleName = commonConfig.styleName
    if (!commonConfig.open) {
      return option
    }
    // if (styleName) {
    //   let styleNameStyle = await common.letterFrist2UpperCase(styleName)
    //   option = await common.deepCopy(optStyle['option' + styleNameStyle])
    // }
    if (xAxisName) {
      let xAxisNameStyle = await common.letterFrist2UpperCase(xAxisName)
      option.xAxis = await common.deepCopy(config['xAxis' + xAxisNameStyle])
    }
    if (yAxisName) {
      let yAxisNameStyle = await common.letterFrist2UpperCase(yAxisName)
      option.yAxis = await common.deepCopy(config['yAxis' + yAxisNameStyle])
      // 区分横轴
      let yAxis = await common.deepCopy(option.yAxis)
      let xAxis = await common.deepCopy(option.xAxis)
      if ((Array.isArray(yAxis) &&
        yAxis[0].type === 'value') ||
        yAxis.type === 'value') {
        // 纵向
        if (Array.isArray(xAxis)) {
          option.xAxis[0].data = data.axisList ? await common.deepCopy(data.axisList) || [] : []
        } else {
          option.xAxis.data = data.axisList ? await common.deepCopy(data.axisList) || [] : []
        }
        // console.log('纵向1', self.seriesName)
      } else {
        // 横向
        if (Array.isArray(yAxis)) {
          option.yAxis[0].data = data.axisList ? await common.deepCopy(data.axisList) || [] : []
        } else {
          option.yAxis.data = data.axisList ? await common.deepCopy(data.axisList) || [] : []
        }
        // console.log('横向')
      }
    }
    if (legendName) {
      let legendNameStyle = await common.letterFrist2UpperCase(legendName)
      option.legend = await common.deepCopy(config['legend' + legendNameStyle])
    }
    if (colorName) {
      let colorNameStyle = await common.letterFrist2UpperCase(colorName)
      option.color = await common.deepCopy(config['color' + colorNameStyle])
    }
    if (seriesName) {
      let dataList = data.dataList ? await common.deepCopy(data.dataList) || [] : []
      if (dataList.length) {
        let seriesList = []
        let seriesData = {}
        let seriesNameStyle = await common.letterFrist2UpperCase(seriesName)
        seriesData = await common.deepCopy(config['series' + seriesNameStyle])
        // 循环修改series的值
        data.dataList.forEach((item, index) => {
          let seriesItem = {
            ...seriesData,
            name: item.name,
            data: item.data || item.ratio || [],
            ratio: item.ratio || []
          }
          seriesList.push(seriesItem)
        })
        option.series = seriesList
      }
    }
    if (tooltipName) {
      let tooltipNameStyle = await common.letterFrist2UpperCase(tooltipName)
      option.tooltip = await common.deepCopy(config['tooltip' + tooltipNameStyle])
    }
    if (dataZoomLen && data.axisList.length) {
      setDataZoom(option, data.axisList.length, dataZoomLen)
    }
    return option
  },
  // 修改图标配置通过自定义样式
  async changeChartOptByCustomConfig (option, customConfig) {
    if (customConfig === {}) {
      return option
    }
    for (let customKey in customConfig) {
      if (customKey === 'bmap') {
        option[customKey] = customConfig[customKey]
        return option
      }
      if (customKey !== 'open') {
        // 如果是对象
        let customStr = option[customKey]
        if (typeof customStr === 'object') {
          // 如果被赋值的是对象
          if (Array.isArray(option[customKey])) {
            // 是数组
            if (customStr.length === 0) {
              option[customKey] = customConfig[customKey]
              break
            }
            // 某些字段跳过拷贝，直接赋值，如series里面的'center', 'radius', 'data'
            let breakKeyList = ['center', 'radius', 'data']
            if (breakKeyList.indexOf(customKey) !== -1) {
              option[customKey] = customConfig[customKey]
              break
            }
            for (var i = 0; i < customStr.length; i++) {
              option[customKey][i] = await this.changeChartOptByCustomConfig(option[customKey][i], customConfig[customKey][i])
              break
            }
            option[customKey][0] = await this.changeChartOptByCustomConfig(option[customKey][0], customConfig[customKey])
          } else {
            option[customKey] = await this.changeChartOptByCustomConfig(option[customKey], customConfig[customKey])
          }
        } else {
          option[customKey] = customConfig[customKey]
          if (customKey === 'fontSize') {
            option['fontSize'] = (option['fontSizeFormatter'] && await option['fontSizeFormatter']()) || option['fontSize']
          }
          if (customKey === 'fontSizeFormatter') {
            option['fontSize'] = await option[customKey]()
          }
        }
      }
    }
    return option
  },
  // 将首字母变大写
  async letterFrist2UpperCase (value) {
    if (!value) {
      return 'null'
    }
    let result = value.slice(0, 1).toUpperCase()
    result = value.slice(1) ? result + value.slice(1) : result
    return result
  },
  uuid (hasHyphen) {
    return (hasHyphen ? 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' : 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx').replace(/[xy]/g, function (c) {
      const r = Math.random() * 16 | 0
      const v = c === 'x' ? r : (r & 0x3 | 0x8)
      return v.toString(16)
    })
  },
  // 添加监听事件listenResizeFn
  async addResizeEvent (fn) {
    window.addEventListener('resize', fn)
  },
  // 移除绑定的listenResizeFn事件监听
  async removeResizeEvent (fn) {
    window.removeEventListener('resize', fn)
  },
  // 图标常用的设置文字长度
  sentFontLenByNumber (number, params) {
    var newParamsName = ''
    var paramsNameNumber = params.length
    var provideNumber = number + 1
    if (paramsNameNumber > provideNumber) {
      newParamsName += params.substring(0, number) + '..'
      return newParamsName
    }
    return params
  },
  // 设置离线瓦片图请求路径
  // async setMapType (map, theme) {
  //   if (window['XSILI']) {
  //     const tileUrl = window['XSILI']['config']['baiduApiConfig']['IMGPATH'] + window['XSILI']['config']['baiduApiConfig']['APIPATH_Tang'] + window['XSILI']['config']['baiduApiConfig']['APIOVERLAYFILENAME']
  //     const tileExt = window['XSILI']['config']['baiduApiConfig']['APIOVERLATYIMAGETYPE']
  //     const tileLayer = new BMap.TileLayer()
  //     tileLayer.getTilesUrl = (tileCoord, zoom) => {
  //       const x = tileCoord.x
  //       const y = tileCoord.y
  //       const url = tileUrl + zoom + '/' + x + '/' + y + '.' + tileExt
  //       return url
  //     }
  //     const tileMapType = new BMap.MapType('tileMapType', tileLayer)
  //     map.setMapType(tileMapType)
  //   } else {
  //     if (theme.indexOf('theme') >= 0) {
  //       map.setMapStyle({styleJson: mapTheme[theme]})
  //     } else {
  //       map.setMapStyle({style: theme})
  //     }
  //   }
  // }
  // // 渲染 mapv 热力图
  // createMapvLayer(map,  mapvLayer, dataList: {lat: 0, lng: 0, count: 0}[], layerOptions: any = {}) {
  //   let arrCount = [], maxCount = 0
  //   console.log('打点列表：', dataList.map(item => item.count))
  //   let data = dataList.map((item:any) => {
  //     let count = item.data || item.count || item.complaintcount
  //     arrCount.push(count)
  //     return  {
  //       geometry: {
  //         type: 'Point',
  //         coordinates: [item.lng, item.lat]
  //       },
  //       count: count
  //     }
  //   })
  //   // maxCount = Math.max.apply([], arrCount)
  //   if (mapvLayer) {
  //     mapvLayer.destroy()
  //   }
  //   let options = {
  //     ...layerOptions,
  //     size: layerOptions.size || 1000,
  //     unit: layerOptions.unit || 'm',
  //     globalAlpha: layerOptions.globalAlpha || 0.6,
  //     // max: maxCount * 1.1,
  //     max: 3000,
  //     zIndex: layerOptions.zIndex || 2,
  //     // lineWidth: 12, // 描边宽度
  //     // shadowBlur: 30,
  //     // globalCompositeOperation: 'lighter',
  //     minOpacity: 0.6,
  //     maxOpacity: 0.8,
  //     // shadowOffsetX: 10,
  //     // shadowOffsetY: 10,
  //     gradient: { // 热力图渐变色
  //       // 0.0001: "rgb(34,121,198)",
  //       0.0001: "#2E5AB0",
  //       // 0.001: "rgb(255,255,255)",
  //       0.33: "rgb(8,255,0)",
  //       0.66: "yellow",
  //       1.0: "rgb(255,0,0)"
  //     },
  //     draw: layerOptions.draw || 'heatmap',
  //   }
  //   let dataSet = new mapv.DataSet(data)
  //   mapvLayer = new mapv.baiduMapLayer(map, dataSet, options)
  //   return mapvLayer
  // },
  //
  // // 销毁 mapv 热力图
  // destroyMapvLayer(mapvLayer): void {
  //   mapvLayer.destroy()
  // }
}
export default common
