import axios from '@/common/services/axios-instance'
import { idText } from 'typescript'
function extendNode(item, options = {}) {
  // 按穿梭组件的要求添加属性
  const type = item.props?.type?.startsWith('G') ? 'Group' : 'User'
  let code = item.id
  if (item.props.type === 'U') {
    code = item.props.account
  }
  item.title = item.text
  item.isLeaf = item.leaf
  item.code = code
  item.name = options.levPath && item.props?.levPath ? item.props.levPath : item.text
  item.type = type
  return item
}
class KpiService {
  // 查询是否已存在时间维度
  hasJobFrequency(params) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpijobinfo/hasJobFrequency',
      method: 'post',
      data: params,
    }).then((res) => {
      return res.data
    })
  }

  // 获取所有因子指标
  getIndisByAttr(params) {
    return axios.post('api/xcoa-mobile/v1/kpi-indi-def/getIndisByAttr', params).then(function(res) {
      return res.data
    })
  }

  // 手动下发报送任务
  sendTask(params) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-indi-task/sendTask',
      method: 'post',
      data: params,
    }).then((res) => {
      return res.data
    })
  }

  // 业务类型分类树
  getCategoryTree(parentId, treeparams, params) {
    return axios({
      url: `api/xcoa-mobile/v1/iam-tree/findTreeNodeById/${treeparams.configId}/${parentId}`,
      method: 'post',
      params,
    }).then((res) => {
      res.data.forEach((item) => (item.isLeaf = item.leaf))
      return res
    })
  }

  // 获取数据字典
  getDictionary(id) {
    return axios({
      url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=' + id,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 指标定义-校验SQL
  validateSQL(params) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-indi-def/validateSQL',
      method: 'post',
      data: params,
    }).then((res) => {
      return res.data
    })
  }

  // 指标定义-校验编号
  hasIndiNo(id, indiNo) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-indi-def/hasIndiNo?id=' + id + '&indiNo=' + indiNo,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 获取报送人信息
  getSubmitterInfo(id, account) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-indi-org/submitter-info?id=' + id + '&account=' + account,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 阈值参考单位选择
  getOrgsByIndiId(id) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-indi-org/getOrgsByIndiId?id=' + id,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 校验监测单位是否本单位
  sameCompany(deptId, monitorDeptIds) {
    return axios({
      url:
        'api/xcoa-mobile/v1/kpi-indi-org/sameCompany?deptId=' +
        deptId +
        '&monitorDeptIds=' +
        monitorDeptIds,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 获取指标报送任务明细
  findTaskDetailList(taskId) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-inditaskdetail/list?taskId=' + taskId,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 指标报送任务-重新计算系统参考值
  getResetGuideVal(taskId) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-inditaskdetail/getResetGuideVal?taskId=' + taskId,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 指标报送任务-计算指标结果值变更预警状态
  getIndiResult(redata) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpi-inditaskdetail/getResetIndiResult',
      data: redata,
      method: 'post',
    }).then((res) => {
      return res.data
    })
  }

  // 指标监测图标数据
  getKpiMonitorlist(Id) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpiindimonitor/getSevenIndiVal?indiId=' + Id,
      method: 'post',
    }).then((res) => {
      return res.data
    })
  }

  // 指标监测表格数据
  getKpiMonitortblist(Id) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpiindimonitor/getIndiVal?indiId=' + Id,
      method: 'post',
    }).then((res) => {
      return res.data
    })
  }

  // 计算更新指标监控数据
  getResetIndiResult(indiIds) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpiindimonitor/getResetIndiResult?indiIds=' + indiIds,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }

  // 机构选择器相关-增加过滤公司级定制
  getRootNode(params) {
    return axios // 获取部门下用户
      .get(`api/framework/v1/group-manager/group/root-node`, { params })
      .then((res) => [extendNode(res.data)])
  }

  getChildNodes(id, options = {}) {
    let type, isContainSub, hierarchical, levPath, secretLevel
    // 8.0.16后参数放到object里了，并且兼容之前的方式
    if (typeof arguments[1] === 'object') {
      ;({ type = 'GU', isContainSub = false, hierarchical, levPath, secretLevel } = options)
    } else {
      ;[id, type = 'GU', isContainSub = false, hierarchical, levPath] = arguments
    }
    const paramsU = {}
    const paramsD = {}
    paramsU.isContainSub = isContainSub
    paramsD.parent = id
    paramsD.lev = '1' // 过滤机构层级，1：是；0：否
    if (hierarchical === undefined) {
      hierarchical = ''
    } else if (hierarchical) {
      hierarchical = '1'
    } else {
      hierarchical = '0'
    }
    if (secretLevel) {
      paramsU.securityLevel = secretLevel
    }
    if (type === 'U') {
      return axios // 获取部门下用户
        .get(
          `api/framework/v1/user-manager/users/${id}/users?orderBy=${encodeURIComponent(
            'weight asc,id asc'
          )}`,
          { params: { ...paramsU, hierarchical } }
        )
        .then((res) => res.data.map((item) => extendNode(item, { levPath })))
    } else {
      return axios // 获取部门下的部门
        .get(`api/xcoa-mobile/v1/kpi-indi-org/group/getChildren`, {
          params: { ...paramsD, hierarchical },
        })
        .then((res) => res.data.map((item) => extendNode(item, { levPath })))
    }
  }

  getFullPath(id) {
    return axios
      .get(`api/framework/v1/group-manager/groups/${id}/fullpath`)
      .then((res) => res.data.map((item) => extendNode(item)))
  }

  getGroupTree({ expandedKey, rootNode, hierarchical, levPath }) {
    if (rootNode && rootNode.code && rootNode.name) {
      rootNode = Promise.resolve([
        { text: rootNode.name, checkable: true, type: 'Group', isLeaf: false, ...rootNode },
      ])
    } else {
      rootNode = this.getRootNode({
        hierarchical: hierarchical === undefined ? '' : hierarchical ? '1' : '0',
      })
    }
    return rootNode.then((data) => {
      let p = Promise.resolve()
      if (expandedKey && expandedKey[0]) {
        // 设置了默认展开节点，获取每层树节点
        p = this.getFullPath(expandedKey[0]).then((items) => {
          if (!items.length) return
          const index = items.findIndex((item) => item.code === data[0].code)
          if (index !== -1) {
            // 根节点在fullpath路径里,从fullpath截取
            items.splice(index + 1, 99)
          } else {
            // 如果不是分级授权，路径信息里没有绝对根节点，这种情况下自己拼上根节点
            items = [...items, ...data]
          }
          const pArray = items.map((item) =>
            this.getChildNodes(item.code, {
              type: 'G',
              isContainSub: false,
              hierarchical,
              levPath,
            })
          )
          return Promise.all(pArray).then((items) => {
            const tree = items.reduce((a, b) => {
              // 通过fullpathId找到父节点
              if (a.length !== 0) {
                const node = b.find((item) => a[0].props.fullpathId.endsWith(item.code))
                if (node) node.children = a
              }
              return b
            })
            return tree
          })
        })
      }
      return p.then((tree) => {
        data[0].children = tree
        return data
      })
    })
  }

  // 获取预警指标数据
  getIndiMonitorsByIds(id) {
    return axios({
      url: 'api/xcoa-mobile/v1/kpiindimonitor/getIndiMonitorsByIds?ids=' + id,
      method: 'get',
    }).then((res) => {
      return res.data
    })
  }
}

export default new KpiService()
