import { TypeZ1dict } from '@/pages/Z_system/Z1dict/type'
import { treeLastIdFindFatherFu } from '@/pages/Z_system/Z6user/data'
import store from '@/store'
import { createHashHistory } from 'history'
import { getTokenInfo } from './storage'
import { TypeZ4Tree } from '@/pages/Z_system/Z4organization/type'
import { KuIsTreeType } from '@/pages/D_storeManage/D4impStor/type'
import { baseURL } from './http'
import { cascaderArr } from '@/pages/C_goodsManage/C1register/AddGoods/data'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
const history = createHashHistory()
export default history

// -------------------所有藏品详情 全部新页面打开-------------------
export const openGoodsInfoFu = (id: number, src?: string) => {
  window.open(src ? src : `/#/goodsLook/${id}`, '_blank')
}

// -------------------级联回显-------------------
let dictAll: TypeZ1dict[] = []
export const resJiLianFu = (idTemp: string, isNull?: string) => {
  if (idTemp) {
    if (dictAll && dictAll.length === 0) {
      dictAll = store.getState().Z1dict.dictAll
    }

    const idArr = idTemp.split(',')
    const id = idArr[idArr.length - 1]
    let arr = treeLastIdFindFatherFu(dictAll, id, 'name')

    if (arr.length >= 3) arr = arr.slice(2)

    if (arr && arr.length) return arr.join(' / ')
    else return isNull || '（空）'
  } else return isNull || '（空）'
}

// -------------------富文本回显-------------------
export const textFu = (val: string) => {
  let TxtRes = ''
  try {
    if (val) {
      let txt = JSON.parse(val)

      if (txt.txtArr && txt.txtArr.length) {
        let txt2: string = txt.txtArr[0].txt
        if (txt2) {
          const txt3 = txt2.replaceAll('<p></p>', '')
          if (txt3) TxtRes = txt2
        }
      }
    }
  } catch (error) {}

  return TxtRes
}

// -------------------树结构的搜索过滤-------------------
export const filterTreeByName = (tree: TypeZ1dict[], searchTemp: string): TypeZ1dict[] => {
  const searchKey = searchTemp.toUpperCase()

  const dfs = (node: TypeZ1dict): TypeZ1dict | null => {
    // 先递归处理子节点（深度优先）
    const filteredChildren = (node.children?.map(dfs).filter(Boolean) as TypeZ1dict[]) || []

    // 判断当前节点是否匹配或子节点有匹配项

    const txt = node.name.toUpperCase() + (node.num || '').toUpperCase()

    const isSelfMatch = txt.includes(searchKey)

    // console.log('pppppppp', isSelfMatch, searchKey, node.num)

    const hasChildMatch = filteredChildren.length > 0

    if (isSelfMatch || hasChildMatch) {
      return {
        ...node,
        children: hasChildMatch ? filteredChildren : undefined
      }
    }
    return null
  }

  return tree.map(dfs).filter(Boolean) as TypeZ1dict[]
}

// -------------------处理所属部门数据-------------------
let buMenTree: TypeZ4Tree[] = []
export const buMenRes = (list: any[]) => {
  if (buMenTree && buMenTree.length === 0) {
    buMenTree = store.getState().Z4organization.treeData
  }
  let arr = list.map((v: any) => ({
    ...v,
    deptNameRes: v.deptId
      ? treeLastIdFindFatherFu(buMenTree, v.deptId + '', 'name').join(' / ')
      : '-'
  }))
  return arr
}

// -------------------列表页面的按钮权限-------------------
export type btnFlagTxtType = '查看' | '编辑' | '删除' | '审批' | '盘点'
export const btnFlagFu = (item: FourTableType) => {
  //申请单状态     申请人id      当前节点审批人     历史审批人       抄送人
  const { status, creatorId, currentAuditUserIds, auditUserIds, copyUserIds } = item

  let flagObj: { [K in btnFlagTxtType]: boolean } = {
    查看: false,
    编辑: false,
    删除: false,
    审批: false,
    盘点: false
  }

  const myId = (getTokenInfo().user || { id: 0 }).id

  //  当前节点审批人
  const arr3 = (currentAuditUserIds || '').split(',').map(v => Number(v))
  // 历史审批人
  const arr4 = (auditUserIds || '').split(',').map(v => Number(v))
  // 抄送人
  const arr5 = (copyUserIds || '').split(',').map(v => Number(v))

  const obj = {
    1: () => {
      //草稿
      // 申请人是我自己 =》查看   编辑    删除
      if (myId === creatorId) flagObj['查看'] = flagObj['编辑'] = flagObj['删除'] = true
    },
    6: () => {
      //待提交
      // 申请人是我自己 =》查看   编辑
      if (myId === creatorId) flagObj['查看'] = flagObj['编辑'] = true
    },
    2: () => {
      //待审批
      // 申请人是我自己 =》查看
      if (myId === creatorId) flagObj['查看'] = true
      // 历史审批人有我 =》查看
      if (arr4.includes(myId)) flagObj['查看'] = true
      // 当前审批人有我 =》审批
      if (arr3.includes(myId)) flagObj['审批'] = true
      // 抄送人有我 =》查看
      if (arr5.includes(myId)) flagObj['查看'] = true
    },
    3: () => {
      //审批不通过
      // 申请人是我自己 =》查看
      if (myId === creatorId) flagObj['查看'] = true
      // 历史审批人有我 =》查看
      if (arr4.includes(myId)) flagObj['查看'] = true
      // 抄送人有我 =》查看
      if (arr5.includes(myId)) flagObj['查看'] = true
    },
    4: () => {
      //已完成
      // 申请人是我自己 =》查看
      if (myId === creatorId) flagObj['查看'] = true
      // 历史审批人有我 =》查看
      if (arr4.includes(myId)) flagObj['查看'] = true
      // 抄送人有我 =》查看
      if (arr5.includes(myId)) flagObj['查看'] = true
    },
    5: () => {
      //待盘点
      // 申请人是我自己 =》查看 编辑 盘点
      if (myId === creatorId) flagObj['查看'] = flagObj['编辑'] = flagObj['盘点'] = true
    }
  }
  if (Reflect.get(obj, status)) Reflect.get(obj, status)()

  return flagObj
  // return { 查看: true, 编辑: true, 删除: true, 审批: true, 盘点: true }
}

// -------------------详情页面的按钮权限-------------------
export type btnFlagTxtType2 =
  | '创建'
  | '提交'
  | '撤回'
  | '审批'
  | '编辑'
  | '重新提交'
  | '删除'
  | '盘点'
export const btnFlagFu2 = (item: FourTableType) => {
  //申请单状态     申请人id      当前节点审批人
  const { status, creatorId, currentAuditUserIds } = item

  let flagObj: { [K in btnFlagTxtType2]: boolean } = {
    创建: false,
    提交: false,
    撤回: false,
    审批: false,
    编辑: false,
    重新提交: false,
    删除: false,
    盘点: false
  }

  const myId = (getTokenInfo().user || { id: 0 }).id

  //  当前节点审批人
  const arr3 = (currentAuditUserIds || '').split(',').map(v => Number(v))

  const obj = {
    1: () => {
      //草稿
      // 我是申请人
      if (creatorId === myId) flagObj['创建'] = flagObj['编辑'] = flagObj['删除'] = true
    },
    6: () => {
      //待提交
      // 我是申请人
      if (creatorId === myId) flagObj['提交'] = flagObj['编辑'] = flagObj['删除'] = true
    },
    2: () => {
      //待审批
      // 我是申请人
      if (creatorId === myId) flagObj['撤回'] = true
      // 当前审批人有我 =》审批
      if (arr3.includes(myId)) flagObj['审批'] = true
    },
    3: () => {
      //审批不通过
      // 我是申请人
      if (creatorId === myId) flagObj['编辑'] = flagObj['重新提交'] = true
    },
    // 4: () => {
    //   //已完成
    //   // 我是申请人
    //   // if (creatorId === myId) flagObj['导出'] = true
    // },
    5: () => {
      //待盘点
      // 我是申请人
      if (creatorId === myId)
        flagObj['提交'] = flagObj['盘点'] = flagObj['编辑'] = flagObj['删除'] = true
    }
  }
  if (Reflect.get(obj, status)) Reflect.get(obj, status)()

  return flagObj
  // return {
  //   创建: true,
  //   提交: true,
  //   撤回: true,
  //   审批: true,
  //   编辑: true,
  //   重新提交: true,
  //   删除: true,
  //   盘点: true
  // }
}

// -------------------排架层数库位平铺转树结构-------------------

export function kuIsTreeChangeFu(arr: any[]): KuIsTreeType[] {
  // 第一层缓存：region维度（value用id，label用regionName）
  const regionMap = new Map<number, KuIsTreeType>()

  // 第二层缓存：layer1维度（value用layer1数值）
  const layer1Map = new Map<string, KuIsTreeType>()

  // 第三层缓存：layer2维度（value用layer2数值）
  const layer2Map = new Map<string, KuIsTreeType>()

  arr.forEach(item => {
    // 创建/获取区域节点
    let regionNode = regionMap.get(item.regionId)
    if (!regionNode) {
      regionNode = {
        // value: item.id, // 注意：此处使用元素id作为value
        value: item.regionName,
        label: item.regionName,
        children: []
      }
      regionMap.set(item.regionId, regionNode)
    }

    // 创建/获取layer1节点
    const layer1Key = `${item.regionId}-${item.layer1}`
    let layer1Node = layer1Map.get(layer1Key)
    if (!layer1Node) {
      layer1Node = {
        value: String(item.layer1),
        label: String(item.layer1),
        children: []
      }
      regionNode.children!.push(layer1Node)
      layer1Map.set(layer1Key, layer1Node)
    }

    // 创建/获取layer2节点
    const layer2Key = `${layer1Key}-${item.layer2}`
    let layer2Node = layer2Map.get(layer2Key)
    if (!layer2Node) {
      layer2Node = {
        value: String(item.layer2),
        label: String(item.layer2),
        children: []
      }
      layer1Node.children!.push(layer2Node)
      layer2Map.set(layer2Key, layer2Node)
    }

    // 创建layer3节点
    const layer3Node: KuIsTreeType = {
      value: String(item.layer3),
      label: String(item.layer3),
      lastId: item.id
    }
    layer2Node.children!.push(layer3Node)
  })

  return Array.from(regionMap.values())
}

// 入库-自动分配空置库位
export const ruTransformDataFu = (data: any[]): any[] => {
  // 用对象缓存区域基准ID
  // const regionBaseIdCache: Record<string, number> = {}

  // // 先遍历建立区域-基准ID映射
  // data.forEach(item => {
  //   if (!regionBaseIdCache[item.regionName]) {
  //     regionBaseIdCache[item.regionName] = item.id
  //   }
  // })

  // 转换数据结构
  return data.map(item => ({
    siteId: item.id,
    siteStr: `${item.regionName},${item.layer1},${item.layer2},${item.layer3}`
  }))
}

// ---------------所有级联的数据平铺-------------------
export const cascaderObjFu = (): any => {
  if (dictAll && dictAll.length === 0) {
    dictAll = store.getState().Z1dict.dictAll
  }

  let obj: any = {}
  if (dictAll && dictAll.length) {
    obj = cascaderArr(dictAll)
  }
  return obj
}

// --------------生成A标签下载--------------------
export const downFileFu = (url: string, back?: () => void) => {
  // 动态创建 a 标签
  const link = document.createElement('a')
  link.href = baseURL + url
  link.target = '_blank'
  link.style.display = 'none'
  // 插入 DOM 并触发点击
  document.body.appendChild(link)
  link.click()
  // 清理
  document.body.removeChild(link)
  if (back) back()
}
