import { drillingData2 } from '@/api'
import { combinationDetail } from '@/api/dataBook'

export function getDrillingData (type = 1, { fieldInfo = null, XYList = [] }) {
  if (!fieldInfo) return
  if (type === 1) {
    // 1->需要查数据域下的元数据再用表头查钻取详情,参数: fieldInfo.fieldId:数据域id
    return getCombinationItems(fieldInfo) // 调用第一个Promise
      .then(drillingFun) // 钻取 //  调用第二个Promise，钻取数据域下的数据
      .then(obj => { return obj })
      .catch(error => {
        console.error('An error occurred:', error)
      })
  } else {
    // 2->已有数据域及元数据，更新钻取详情（更改过滤或排序）
    return drillingFun({ fieldInfo, XYList }) // 钻取
      .then(obj => { return obj })
      .catch(error => {
        console.error('An error occurred:', error)
      })
  }
}

// 根据数据域id拿元数据列表
function getCombinationItems (fieldInfo) { // 参数：obj.fieldId:数据域id
  return new Promise((resolve, reject) => {
    combinationDetail({ metaDataCombinationId: fieldInfo.fieldId, publicSystem: 1 })
      .then(res => {
        const metaData = res.data.metaDataCombinationItems // 元数据成员
        const XYList = []; fieldInfo.metaItemEngNames = []
        metaData.forEach(e => {
          fieldInfo.metaItemEngNames.push(e.dbColumn)
          XYList.push({ text: e.title, value: e.dbColumn })
        })
        resolve({ fieldInfo, XYList, metaData })
      })
      .catch(error => {
        reject(error)
      })
  })
}

// 数据域下的数据钻取
function drillingFun ({ fieldInfo, XYList, metaData = null }) {
  const params = {
    metaDataCombinationEngName: fieldInfo.fieldEngName, // 数据域英文名称
    metaDataCombinationItemEngName: fieldInfo.metaItemEngNames, // 元数据成员英文名称
    pageState: 0
  }
  if (!params.metaDataCombinationItemEngName?.length) return
  if (fieldInfo.filterObj) {
    Object.assign(params, {
      query: fieldInfo.filterObj.query,
      page: {
        size: 9999, // pageState: 1 不生效 返回数据还是10条
        current: 1,
        orders: fieldInfo.filterObj.orders
      }
    })
  }
  return new Promise((resolve, reject) => {
    drillingData2(params)
      .then(({ data }) => {
        let excelData = [[]]
        const header = []
        if (XYList?.length) {
          XYList = XYList.map(_s => ({ ..._s, data: [] })) // 重置data
          if (data?.records?.length) {
            data.records.forEach((_e, index1) => {
              XYList.forEach((_i, index2) => {
                // xy轴数据
                _i.data.push(_e[_i.value])
                _i.hasNum = /^(-)?\d+(\.\d+)?$/.test(_e[_i.value]) // 判断是否为纯数值，不包括.999数值类型
                // 表格数据
                if (!index1) header.push(_i.text)
                if (!excelData[index1]) excelData[index1] = []
                excelData[index1].push(_e[_i.value])
                // return _e[_i.value]
              })
            })
          }
        }
        excelData = [header, ...excelData]
        resolve({ excelData, fieldInfo, XYList, metaData })
      })
      .catch(error => {
        reject(error)
      })
  })
}
