import { Message, Loading } from 'element-ui'
import { saveAs } from 'file-saver'
import errorCode from '@/views/als/utils/errorCode'
import axios from 'axios'
import { getItem } from '@/utils/index'

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  var childrenListMap = {}
  var nodeIds = {}
  var tree = []

  for (let d of data) {
    let parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (let d of data) {
    let parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

// 树 扁平化的方法
export function flattenTree(treeNodes) {
  let result = []

  //递归函数 traverse，用于处理单个节点
  function traverse(node) {
    const newNode = { ...node }
    delete newNode.children
    // 将没有子节点的新节点添加到结果数组中
    result.push(newNode)

    // 如果当前节点包含 children 属性（即有子节点）
    if (node.children) {
      node.children.forEach(traverse)
    }
  }
  treeNodes.forEach(traverse)
  return result
}

// 通用下载方法
let downloadLoadingInstance
const service = axios.create({
  baseURL: '/api/als',
  // 超时
  timeout: 100000
})

/**
 * @description 接收数据流生成 blob，创建链接，下载文件
 * @param {Function} api 导出表格的api方法 (必传)
 * @param {String} tempName 导出的文件名 (必传)
 * @param {Object} params 导出的参数 (默认{})
 * @param {String} fileType 导出的文件格式 (默认为.xlsx)
 * */
export const useDownload = async (api, tempName, params, fileType, fileName) => {
  try {
    const res = await api(params)
    const isBlob = blobValidate(res.data)
    if (isBlob) {
      const blob = fileType == 'zip' ? new Blob([res.data], { type: 'application/zip' }) : new Blob([res.data])
      const name = fileType == 'zip' ? fileName : `${tempName}_${new Date().getTime()}${fileType}`
      saveAs(blob, name)
    } else {
      printErrMsg(res)
    }
  } catch (error) {
    console.log(error)
    Message.error('下载文件出现错误，请联系管理员！')
  }
}

async function printErrMsg(data) {
  const resText = await data.text()
  const rspObj = JSON.parse(resText)
  const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
  Message.error(errMsg)
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  console.log('params', params)
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURI(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
            let params = propName + '[' + key + ']'
            var subPart = encodeURI(params) + '='
            result += subPart + encodeURI(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURI(value) + '&'
      }
    }
  }
  console.log('result', result)
  return result
}

// 验证是否为blob格式
export function blobValidate(data) {
  return data.type !== 'application/json'
}

export function localResource(resource) {
  let url = '/common/download/resource?resource=' + encodeURI(resource)
  service({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { Authorization: getItem('token') }
  }).then((res) => {
    const isBlob = blobValidate(res.data)
    if (isBlob) {
      const blob = new Blob([res.data])
      saveAs(blob, decodeURI(res.headers['download-filename']))
    } else {
      printErrMsg(res.data)
    }
  })
}
