import { RFormTypes } from '@/types/r-form/model'
import { ProColumns } from '@ant-design/pro-components'
import Switch from '@/components/switch'
import { Checkbox, DatePicker, Input, Radio, Select, TreeSelect } from 'antd'
import request from '@/request'
import { convertToBool } from '@/utils'
import { has, get } from 'lodash'
import { mapTree } from '@/utils/tree.ts'


const getValueType = (column: ProColumns) => {

  return column.valueType
}

//根据type返回对应的组件
const getComponent = (column: ProColumns) => {
  const type = getValueType(column) as any
  switch (type) {
    case 'input':
      return Input
    case 'select':
      return Select
    case 'date':
      return DatePicker
    case 'switch':
      return Switch
    case 'radio':
      return Radio
    case 'checkbox':
      return Checkbox
    case 'textarea':
      return Input.TextArea
    case 'tree':
    case 'treeSelect':
      return TreeSelect
    default:
      return Input
  }
}


export const transformAntdTableProColumns = (columns: ProColumns[], overwriteColumns?: ProColumns[]) => {

  const overwriteKeys = [] as string[]

  return (columns || []).map(item => {


    const type = getValueType(item)

    const overwrite = overwriteColumns?.find(i => i.dataIndex === item.dataIndex)
    if (overwrite) {
      overwriteKeys.push(item.dataIndex)
    }

    return {
      ...item,
      request: item.request ? async (params) => {
        const { url: _url, method, params: p, fieldNames, resultPath } = item.request as unknown as RFormTypes.IRequest
        const { value, label, disabled: disabledKey, children = 'children' } = fieldNames || {}
        const url = (_url.startsWith('/') || _url.startsWith('http')) ? _url : `/${_url}`
        return request[method?.toLowerCase() || 'get'](url, {
          ...params,
          ...p,
        }).then(res => {
          try {
            const data = resultPath && has(res.data, resultPath) ? get(res.data, resultPath) : res.data

            return mapTree(data || [], (i: any) => {
              const disabled = disabledKey && has(i, disabledKey) ? get(i, disabledKey) : ('status' in i ? !convertToBool(i.status) : false)
              return {
                title: i.label || i[label || 'name'],
                label: i.label || i[label || 'name'],
                value: i.value ?? i[value || 'id'],
                disabled,
                data: i
              }

            }, { children })

          } catch (e) {
            console.log(`${url}请求异常：`, e)
            return []
          }
        })
      } : undefined,
      // renderFormItem: (_scheam, config, dom) => {
      //
      // },
      render: (text: any, _record: any) => {

        return text
      },
      ...overwrite
    } as ProColumns
  }).concat(overwriteColumns?.filter(i => !overwriteKeys.includes(i.dataIndex)) || [])

}