import { Message } from 'element-ui'
import { dataapiDetail, openurl } from './report'
import { optionList, enumCheck } from '@/api/newbi/bigdata'
import { dictDetail } from '@/api/newbi/dict'
import { param } from './config'
import { deepClone, loopRelationTabelList } from '@/utils'
import { dataapicategoryList, dataapiList } from '@/api/systemData/dataInterface'
// 整理树结构
export const countTreeOptions = (originData) => {
  originData.forEach((i) => {
    i.children = []
    i.KEY = i.KEY || i.VALUE
  })
  let parents = [...originData]
  let res = [],
    childrens = []
  originData.forEach((i) => {
    if (i.PID == '0') {
      res.push(i)
    } else {
      childrens.push(i)
    }
  })
  childrens.forEach((i) => {
    let parent = parents.find((j) => j.ID == i.PID)
    if (parent) {
      parent.children.push(i)
    }
  })
  return res
}
// 去掉子项空数组
export const clearChildren = (node) => {
  if (!node.children) return
  if (!node.children.length) {
    delete node.children
  } else {
    node.children.forEach(clearChildren)
  }
}
//使用表单变量作为默认值
export const getdefaultAPIData = (item, componentList, type, scheme, cascaderData) =>
  new Promise((resolve, reject) => {
    let formAllVar = item.defaultVarType
    let leveType = item.cascaderType
    if (formAllVar && formAllVar.length && componentList && componentList.length) {
      if (formAllVar[0] === 3) {
        let varObbj = componentList.find((o) => o.__vModel__ && o.__vModel__ === formAllVar[1])
        if (type === 'search') {
          sessionStorage.setItem(`FORM_${item.__vModel__}`, varObbj.value)
          resolve(varObbj.value)
        } else {
          sessionStorage.setItem(`FORM_${item.__vModel__}`, varObbj.__config__.defaultValue)
          resolve(varObbj.__config__.defaultValue)
        }
      }
      if (formAllVar[0] === 4) {
        //级联
        if (cascaderData && cascaderData.length) {
          //获取数组最后一位元素  查找级联当前层次
          let lastValue
          !scheme.props.props.emitPath ? (lastValue = cascaderData) : (lastValue = cascaderData.at(-1))
          let newLeve = g.T.queryNodes(scheme.options, scheme.props.props.children, function (it) {
            if (it[scheme.__config__.apiProps.value] === lastValue) {
              return true
            }
          })
          if (leveType && leveType === 'son') {
            try {
              resolve(newLeve[0][formAllVar[1]])
            } catch {}
          } else {
            let topLeve = g.T.parent(scheme.options, scheme.props.props.children, newLeve[0]._ID)
            try {
              resolve(topLeve[formAllVar[1]])
            } catch {}
          }
        } else {
          //下拉
          let config = scheme.__config__
          // 查询当前绑定的api返回值key和value
          let obnj = config.ApiReturn.find((z) => z.varName === formAllVar[1])
          if (!obnj) return
          if (!config.defaultValue) return
          let matrix = scheme.__slot__.options
          //从当前配置API返回值变量组件的下拉选项中匹配到与选中值符合的对象
          let obj = matrix.find((x) => config.defaultValue === x.id)
          for (const cur of config.ApiReturn) {
            // 储存全局变量
            sessionStorage.setItem(`API_${cur.varName}`, obj[cur.keyName])
          }
          resolve(obj[obnj.keyName])
          // })
        }
      }
    }
  })
//被修改的下拉 apiID 全局变量list 表单list
export const getAPIData = (filter, enumId, formAllVar, componentList, type, apiProps, value = {}) =>
  new Promise((resolve, reject) => {
    dataapiDetail(enumId).then((res) => {
      let { apiKey } = res.data.data
      let formVarObj = {}
      let loopComponentList = loopRelationTabelList(componentList)
      //获取表单内关联的变量
      if (formAllVar && formAllVar.length && loopComponentList && loopComponentList.length) {
        formAllVar.forEach((i, k) => {
          if (i.varType && i.varType.length) {
            //默认值
            if (i.varType[0] === 1) {
              formVarObj[i.key] = i.def
            }
            //系统全局变量
            if (i.varType[0] === 2) {
              formVarObj[i.key] = i.varType[1]
            }
            //表单内全局变量
            if (i.varType[0] === 3) {
              let varObbj = loopComponentList.find((o) => o.__vModel__ && o.__vModel__ == i.varType[1])
              if (type === 'search') {
                formVarObj[i.key] = varObbj.value
              } else {
                formVarObj[i.key] = varObbj.__config__.defaultValue
              }
            }
            //api返回值变量
            if (i.varType[0] === 4) {
              const sessionValue = sessionStorage.getItem(`API_${i.varType[1]}`)
              if (sessionValue) formVarObj[i.key] = sessionValue
              // let obnj = {}
              // //查询当前表单配置API返回值变量的组件
              // let list = loopComponentList
              //   .map((item) => {
              //     if (item.__config__.ApiReturn && item.__config__.ApiReturn.length) {
              //       return item
              //     }
              //   })
              //   .flat()
              //   .filter((l) => l !== undefined)
              // list.forEach((o, l) => {
              //   let config = o.__config__
              //   // 查询当前绑定的api返回值key和value
              //   obnj = config.ApiReturn.find((z) => z.varName === i.varType[1])
              //   if (!obnj) return
              //   if (!o.__config__.defaultValue) return
              //   // console.log(o.__slot__.options)
              //   let matrix = o.__slot__.options
              //   //从当前配置API返回值变量组件的下拉选项中匹配到与选中值符合的对象
              //   let obj = matrix.find((x) => config.defaultValue === x.id)
              //   formVarObj[i.key] = obj[obnj.keyName]
              // })
            }
          }
        })
      }
      let list = []
      openurl(apiKey, { ...param, ...value, ...formVarObj })
        .then((res) => {
          let data = res.data.data
          let hasChild = data.find((i) => i.PID)
          if (hasChild) {
            let tree = countTreeOptions(data)
            tree.forEach(clearChildren)
            filter.options = tree
          } else {
            list = data.map((i) => {
              let labelSeparator = apiProps.labelSeparator || ' '
              let fitLabel = String(i[apiProps.label] || i[apiProps.value]) + labelSeparator + fitLabelFiltle(apiProps.fitLabel, i, labelSeparator)
              return {
                id: i[apiProps.value],
                fullName: fitLabel
              }
            })
            list.forEach((i, k) => {
              let obnj = data.find((o) => i.id === o[apiProps.value])
              Object.assign(i, obnj)
            })
          }
          resolve(list)
        })
        .catch((res) => {
          list = []
          resolve(list)
        })
    })
  })
//筛选器搜索
export const getCondAPIData = (enumId, apiProps, flag) =>
  new Promise((resolve, reject) => {
    dataapiDetail(enumId).then((res) => {
      let { apiKey } = res.data.data
      let list = []
      openurl(apiKey, param)
        .then((res) => {
          let data = res.data.data
          let hasChild = data.find((i) => i.PID)
          if (hasChild) {
            let tree = countTreeOptions(data)
            tree.forEach(clearChildren)
            list = tree
          } else {
            list = data.map((i) => {
              return {
                KEY: i[apiProps.value],
                VALUE: i[apiProps.label] || i[apiProps.value]
              }
            })
            if (flag) {
              list.forEach((i, k) => {
                let obnj = data.find((o) => i.KEY === o[apiProps.value])
                Object.assign(i, obnj)
              })
            }
          }
          resolve(list)
        })
        .catch((res) => {
          list = []
          resolve(list)
        })
    })
  })

/*
  列表设计，列表属性设置
 */
export const getAPIList = () =>
  new Promise((resolve, reject) => {
    dataapicategoryList().then((res) => {
      let category = res.data.data
      dataapiList({ apiFormal: 1, apiTypes: '1,2' }).then((res) => {
        let list = res.data.data
        list = category
          .map((i) => ({
            label: i.categoryName,
            value: 'c' + i.id,
            children: list.filter((j) => j.categoryId === i.id).map((k) => ({ label: k.apiName, value: k.id, key: k.apiKey }))
          }))
          .filter((i) => i.children.length)
        resolve(list)
      })
    })
  })
/*
  列表页左侧树形导航
 */
export const getTreeAPIData = (enumId, apiProps, flag) =>
  new Promise((resolve, reject) => {
    dataapiDetail(enumId).then((res) => {
      let { apiKey } = res.data.data
      let list = []
      openurl(apiKey, param)
        .then((res) => {
          let data = res.data.data
          list = g.T.toTree(data, 'children', apiProps.treePropsValue, apiProps.treePropsChildren)
          resolve(list)
        })
        .catch((res) => {
          list = []
          resolve(list)
        })
    })
  })
export const fitLabelFiltle = (labeList, data, labelSeparator) => {
  let str = ''
  if (labeList && labeList.length && data) {
    let arr = labeList.map((item) => {
      return data[item]
    })
    str = arr.join(labelSeparator)
  }
  return str
}
// 获取枚举可选值
export const getEnumData = (filter, cubeDataId, visualId, componentId, isEdit) => {
  let { enumSource, enumId } = filter
  if (enumSource == '1') {
    filter.loading = true
    let { tableName, columnName } = filter
    if (!tableName || !columnName) {
      tableName = filter.column.tableName
      columnName = filter.column.columnName
    }
    if (isEdit) {
      enumCheck({
        tableName,
        columnName,
        cubeDataId
      })
        .then(() => {
          optionList({
            tableName,
            columnName,
            cubeDataId,
            visualId,
            componentId
          }).then((res) => {
            filter.options = res.data.data.map((i) => ({
              KEY: i[columnName],
              VALUE: i[columnName]
            }))
            filter.loading = false
          })
        })
        .catch(() => {
          Message.warning('此数据集不支持原始数据聚合')
          filter.loading = false
        })
    } else {
      optionList({
        tableName,
        columnName,
        cubeDataId,
        visualId,
        componentId
      }).then((res) => {
        filter.options = res.data.data.map((i) => ({
          KEY: i[columnName],
          VALUE: i[columnName]
        }))
        filter.loading = false
      })
    }
  } else if (enumSource == '2') {
    if (!enumId) {
      return Message.warning('请选择api')
    }
    filter.loading = true
    dataapiDetail(enumId).then((res) => {
      let { apiKey } = res.data.data
      openurl(apiKey, param).then((res) => {
        filter.loading = false
        let data = res.data.data
        if (!data.length) {
          filter.options = data
        }
        if (data[0].ID) {
          let tree = countTreeOptions(data)
          tree.forEach(clearChildren)
          filter.options = tree
        } else {
          filter.options = data.map((i) => ({
            KEY: i.KEY || i.VALUE,
            VALUE: i.VALUE
          }))
        }
      })
    })
  } else {
    if (!enumId) {
      return Message.warning('请选择字典')
    }
    dictDetail({
      id: enumId
    }).then((res) => {
      let content = JSON.parse(res.data.data.content || '[]')
      filter.options = content.map((i) => ({
        KEY: i.key,
        VALUE: i.value
      }))
    })
  }
}
export const onEnumSelectAll = (filter) => {
  let options = filter.options
  let arr = []
  options.forEach((i) => getOptionValue(arr, i))
  filter.conditions[0].values = arr
}
export const getOptionValue = (arr, item) => {
  if (item.children) {
    item.children.forEach((i) => {
      getOptionValue(arr, i)
    })
  } else {
    arr.push(item.KEY)
  }
}
//被修改的下拉 apiID 全局变量list 表单list
export const getTabelAPIData = (filter, enumId, formAllVar, componentList, type, apiProps, value = {}) =>
  new Promise((resolve, reject) => {
    dataapiDetail(enumId).then((res) => {
      let { apiKey } = res.data.data
      let formVarObj = {}
      //获取表单内关联的变量
      if (formAllVar && formAllVar.length && componentList && componentList.length) {
        formAllVar.forEach((i, k) => {
          if (i.varType && i.varType.length) {
            //默认值
            if (i.varType[0] === 1) {
              formVarObj[i.key] = i.def
            }
            //系统全局变量
            if (i.varType[0] === 2) {
              formVarObj[i.key] = i.varType[1]
            }
            //表单内全局变量
            if (i.varType[0] === 3) {
              let varObbj = componentList.find((o) => o.__vModel__ && o.__vModel__ == i.varType[1])
              if (varObbj) {
                formVarObj[i.key] = varObbj.value
              }
            }
            //api返回值变量
            if (i.varType[0] === 4) {
              let obnj = {}
              //查询当前表单配置API返回值变量的组件
              let list = componentList
                .map((item) => {
                  if (item.ApiReturn && item.ApiReturn.length) {
                    return item
                  }
                })
                .flat()
                .filter((l) => l !== undefined)
              list.forEach((o, l) => {
                let config = o
                // 查询当前绑定的api返回值key和value
                obnj = config.ApiReturn.find((z) => z.varName === i.varType[1])
                if (!obnj) return
                if (!o.value) return
                // console.log(o.__slot__.options)
                let matrix = o.options
                //从当前配置API返回值变量组件的下拉选项中匹配到与选中值符合的对象
                let obj = matrix.find((x) => config.value === x.id)
                formVarObj[i.key] = obj[obnj.keyName]
              })
            }
          }
        })
      }
      let list = []
      openurl(apiKey, { ...param, ...value, ...formVarObj })
        .then((res) => {
          let data = res.data.data
          let hasChild = data.find((i) => i.PID)
          if (hasChild) {
            let tree = countTreeOptions(data)
            tree.forEach(clearChildren)
            filter.options = tree
          } else {
            list = data.map((i) => {
              let labelSeparator = apiProps.labelSeparator || ' '
              let fitLabel = String(i[apiProps.label] || i[apiProps.value]) + labelSeparator + fitLabelFiltle(apiProps.fitLabel, i, labelSeparator)
              return {
                id: i[apiProps.value],
                fullName: fitLabel
              }
            })
            list.forEach((i, k) => {
              let obnj = data.find((o) => i.id === o[apiProps.value])
              Object.assign(i, obnj)
            })
          }
          resolve(list)
        })
        .catch((res) => {
          list = []
          resolve(list)
        })
    })
  })
