import type { Page } from '@/types/page'
import type { Screen } from '@/types/screen'
import type { ScreenConfig } from '@/types/appMeta'
import type { Bin } from '@/types/bins'
import type { Resource } from '@/types/resource'
import type { IComponentModelConfig } from '@/lvgl-widgets/type'

import { v4 } from 'uuid'
import { klona } from 'klona'
import { BaseWidget } from '@/types/baseWidget'
import { getUUID } from '@/utils'
import { DEFAULT_THEME_KEY } from '@/constants'
import LvglWidgets from '@/lvgl-widgets'
import { bfsWalk } from 'simple-mind-map/src/utils'

const withDefaultTheme = (styles: any[] = []) => {
  return klona(styles).map((item: any) => ({
    ...item,
    theme: item?.theme || DEFAULT_THEME_KEY
  }))
}

/**
 * 创建屏幕
 * @param config 屏幕配置
 * @returns Screen
 */
export const createScreen = (config: ScreenConfig): Screen => {
  return {
    // ID
    id: v4(),
    // 名称
    name: 'screen',
    // 类型
    type: 'screen',
    // 屏幕宽
    width: config.width,
    // 屏幕高
    height: config.height,
    // 颜色格式
    colorFormat: config.colorFormat,
    // 颜色深度
    colorDepth: config.colorDepth,
    // 屏幕方向
    screenDirection: config.screenDirection,
    // 页面
    pages: [createPage()]
  }
}

/**
 * 创建页面
 */
export const createPage = (): Page => {
  return {
    // 页面ID
    id: v4(),
    // 页面名称
    name: 'new_page',
    // 类型
    type: 'page',
    // 隐藏
    hidden: false,
    // 锁定
    locked: false,
    // 参考线
    referenceLine: [],
    // 属性
    props: klona(LvglWidgets['page'].defaultSchema.props || {}),
    // 样式
    style: withDefaultTheme(LvglWidgets['page'].defaultSchema.styles || []),
    // 事件
    events: [],
    // 页面变量
    variables: [],
    // 子组件
    children: []
  }
}

/**
 * 创建BIN
 * @param index BIN索引
 */
export const createBin = (index: number): Bin => {
  return {
    // BIN索引
    id: v4(),
    // BIN名称
    name: `bin_${index}`,
    // BIN文件
    path: ''
  }
}

/**
 * 创建文件资源
 * @param path 文件路径
 * @param type 类型
 */
export const createFileResource = (path: string, type: 'image' | 'font' | 'other'): Resource => {
  const fileName = path.split('\\').pop() || ''

  switch (type) {
    // 图片资源
    case 'image': {
      return {
        id: v4(),
        fileName,
        fileType: fileName.split('.').pop() || '',
        path,
        compressFormat: 'none',
        colorFormat: 'RGB565A8',
        // alphaColor: '#FFFFFF00',
        // alpha: 255,
        bin: '',
        ditheringAlgorithm: 'None',
        storageMode: 'BIN'
      }
    }
    // 字体资源
    case 'font': {
      return {
        id: v4(),
        fileName,
        fileType: fileName.split('.').pop() || '',
        path,
        range: ['all'],
        codeRange: [],
        extText: '',
        bin: ''
      }
    }
    default: {
      // 其他资源
      return {
        id: v4(),
        fileName,
        fileType: fileName.split('.').pop() || '',
        path,
        bin: ''
      }
    }
  }
}

/**
 * 创建函数
 */
export const createMethod = () => {
  return {
    id: v4(),
    name: 'func_name' + '_' + getUUID(6, 'number'),
    action: ''
  }
}

/**
 * 创建控件数据
 * @param schema 组件模型
 */
export const createWidget = (
  schema: IComponentModelConfig | BaseWidget,
  index: number,
  isCustom?: boolean
): BaseWidget => {
  // 自定义组件
  if (isCustom) {
    const newComp = klona(schema as BaseWidget)
    bfsWalk(newComp, (child) => {
      child.id = v4()
    })
    // todo：处理关联性问题
    newComp.id = v4()
    return newComp as BaseWidget
  }
  const { defaultSchema, hasChildren, parts } = schema
  const componentSchema: BaseWidget = {
    id: v4(),
    name: defaultSchema?.name + '_' + index,
    type: schema.key,
    isCopy: false,
    copyFrom: '',
    hidden: false,
    locked: false,
    part: parts?.[0]?.name,
    state: parts?.[0]?.stateList?.[0],
    props: klona(defaultSchema.props || {}),
    style: withDefaultTheme(defaultSchema.styles || []),
    events: []
  }
  if (hasChildren) {
    componentSchema.children = []
  }

  if (defaultSchema?.children) {
    componentSchema.children = klona(defaultSchema.children)
  }

  return componentSchema
}
