<template>
  <el-dialog
    v-model="showModal"
    :title="mode === 'add' ? $t('createProject') : $t('editProject')"
    width="1200px"
    body-class="h-500px overflow-y-auto overflow-x-hidden modal-body-scroll px-12px"
    :modal="false"
    :close-on-click-modal="false"
    :before-close="close"
    align-center
   append-to-body draggable>
    <div class="w-full h-full flex">
      <el-scrollbar wrap-class="pr-12px" class="flex-1">
        <el-form
          :model="formData"
          :rules="rules"
          ref="form"
          label-width="120px"
          style="display: flex; flex-direction: column"
          hide-required-asterisk
        >
          <el-form-item :label="$t('projectName')" prop="name">
            <el-input
              v-model="formData.name"
              :placeholder="$t('pleaseEnter')"
              spellcheck="false"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('projectPath')" prop="path">
            <el-input spellcheck="false" v-model="formData.path">
              <template #append>
                <el-button @click="selectPath('path')" :disabled="mode === 'edit'"
                  ><LuFolder :size="16" :disabled="mode === 'edit'"
                /></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('codePath')" prop="codePath">
            <el-input spellcheck="false" v-model="formData.codePath">
              <template #append>
                <el-button @click="selectPath('codePath')"
                  ><LuFolder :size="16" :disabled="mode === 'edit'"
                /></el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('projectType')" prop="type">
            <el-select v-model="formData.type" @change="handlChangeType">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-divider />
          <!-- 鑺墖閰嶇疆 -->
          <template v-if="formData.type === 'chip'">
            <el-row :gutter="12">
              <el-col :span="8">
                <el-form-item :label="$t('chipModel')" prop="chip.model">
                  <el-select v-model="formData.chip.model" @change="handleSelectChip">
                    <el-option
                      v-for="item in chipOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('flashSize')" prop="chip.flash_size.capacity">
                  <el-autocomplete
                    size="small"
                    style="width: 100%"
                    :fetch-suggestions="querySearchFlash"
                    v-model.number="formData.chip.flash_size.capacity"
                  >
                    <template #append>
                      <el-select v-model="formData.chip.flash_size.unit" style="width: 68px">
                        <el-option
                          v-for="item in selectedChipConfig?.flash_size?.unit_options || []"
                          :key="item"
                          :label="item"
                          :value="item"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('ramSize')" prop="chip.ram_size.capacity" required>
                  <el-autocomplete
                    size="small"
                    style="width: 100%"
                    :fetch-suggestions="querySearchRam"
                    v-model.number="formData.chip.ram_size.capacity"
                  >
                    <template #append>
                      <el-select v-model="formData.chip.ram_size.unit" style="width: 68px">
                        <el-option
                          v-for="item in selectedChipConfig?.ram_size?.unit_options || []"
                          :key="item"
                          :label="item"
                          :value="item"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="flex items-center justify-center gap-12px">
              <el-radio-group
                v-model="formData.screenType"
                size="small"
                fill="#6cf"
                @change="handleChangeScreenTypeByChip"
              >
                <el-radio-button :label="$t('singleScreen')" value="single" />
                <el-radio-button :label="$t('doubleScreen')" value="dual" />
              </el-radio-group>
            </div>
            <div v-for="(item, index) in formData.screens" :key="index">
              <el-divider border-style="dashed">{{ $t('screenIndex', [index + 1]) }}</el-divider>
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item :label="$t('resolution')">
                    <el-select
                      :model-value="`${item.width}x${item.height}`"
                      @change="(val) => handleSetResolution(val, index)"
                    >
                      <el-option :label="$t('custom')" value="custom" />
                      <el-option
                        v-for="item in getScreenOptions('resolutions')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('screenDirection')"
                    :prop="`screens.${index}.screenDirection`"
                  >
                    <el-select v-model="item.screenDirection">
                      <el-option
                        v-for="item in getScreenOptions('screen_direction')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('interfaceType')" :prop="`screens.${index}.interface`">
                    <el-select v-model="item.interface">
                      <el-option
                        v-for="item in getScreenOptions('interface')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('colorFormat')" :prop="`screens.${index}.colorFormat`">
                    <el-select v-model="item.colorFormat">
                      <el-option
                        v-for="item in getScreenOptions('color_format')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('colorDepth')" :prop="`screens.${index}.colorDepth`">
                    <el-select v-model="item.colorDepth">
                      <el-option
                        v-for="item in getScreenOptions('color_depth')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="PCLK" :prop="`screens.${index}.params.PCLK`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.PCLK"
                    >
                      <template #suffix>MHz</template>
                    </input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="HFP" :prop="`screens.${index}.params.HFP`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.HFP"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="HBP" :prop="`screens.${index}.params.HBP`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.HBP"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="HSW" :prop="`screens.${index}.params.HSW`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.HSW"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="HSPOL" :prop="`screens.${index}.params.HSPOL`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.HSPOL"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="VFP" :prop="`screens.${index}.params.VFP`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.VFP"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="VBP" :prop="`screens.${index}.params.VBP`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.VBP"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="VSW" :prop="`screens.${index}.params.VSW`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.VSW"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="VSPOL" :prop="`screens.${index}.params.VSPOL`">
                    <input-number
                      controls-position="right"
                      style="width: 100%"
                      v-model="item.params.VSPOL"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </template>
          <!-- 鏉垮崱閰嶇疆 -->
          <template v-if="formData.type === 'board'">
            <div class="flex items-center justify-end gap-12px mb-12px">
              <el-input
                style="width: 160px"
                :placeholder="$t('pleaseEnterModelQuery')"
                v-model="query"
              />
              <el-button @click="searchBoard">{{ $t('search') }}</el-button>
            </div>
            <div class="max-h-300px overflow-y-auto overflow-x-hidden">
              <el-row :gutter="12">
                <el-col v-for="item in boardOptions || []" :span="12">
                  <div
                    class="w-full h-100px bg-#fff relative cursor-pointer border1 border-transparent border-solid"
                    :class="formData.board.model === item.board_name ? 'border-#0ff!' : ''"
                    @click="handleSetBoard(item)"
                  >
                    <el-image class="w-full h-full" :src="item.pic_path">
                      <template #error>
                        <div class="text-center text-#fff">{{ $t('imageLoadError') }}</div>
                      </template>
                    </el-image>
                    <div class="absolute w-full h-40px left-0 bottom-0 bg-#ccc truncate text-#fff">
                      <div class="text-center">{{ item.board_name }}</div>
                      <div class="text-center">{{ item.description }}</div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="my-12px text-text-secondary">
              {{ $t('currentSelectModel', [formData.board.model]) }}
            </div>
            <el-row :gutter="12">
              <template v-for="(screen, index) in formData.screens">
                <el-col :span="8">
                  <el-form-item
                    :label="$t('screenIndexResolution', [index + 1])"
                    label-width="120px"
                  >
                    <el-input
                      spellcheck="false"
                      :model-value="`${screen.width}x${screen.height}`"
                      disabled
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('screenDirection')"
                    :prop="`screens.${index}.screenDirection`"
                  >
                    <el-select v-model="screen.screenDirection">
                      <el-option
                        v-for="item in getBoardOptions('screen_direction')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('screenIndexColorDepth', [index + 1])"
                    label-width="120px"
                  >
                    <el-select v-model="screen.colorDepth">
                      <el-option
                        v-for="item in colorDepthOptions[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </template>
          <!-- 铏氭嫙鏄剧ず -->
          <template v-if="formData.type === 'analog_display'">
            <div class="flex items-center justify-center gap-12px">
              <el-radio-group
                v-model="formData.screenType"
                size="small"
                fill="#6cf"
                @change="handleChangeScreenTypeByAnalog"
              >
                <el-radio-button :label="$t('singleScreen')" value="single" />
                <el-radio-button :label="$t('doubleScreen')" value="dual" />
              </el-radio-group>
            </div>
            <div v-for="(item, index) in formData.screens" :key="index">
              <el-divider border-style="dashed">{{ $t('screenIndex', [index + 1]) }}</el-divider>
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item :label="$t('resolution')">
                    <el-select
                      :model-value="`${item.width}x${item.height}`"
                      @change="(val) => handleSetResolution(val, index)"
                    >
                      <el-option :label="$t('custom')" value="custom" />
                      <el-option
                        v-for="item in getAnalogDisplayOptions('resolutions')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('screenDirection')"
                    :prop="`screens.${index}.screenDirection`"
                  >
                    <el-select v-model="item.screenDirection">
                      <el-option
                        v-for="item in getAnalogDisplayOptions('screen_direction')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('colorFormat')" :prop="`screens.${index}.colorFormat`">
                    <el-select v-model="item.colorFormat">
                      <el-option
                        v-for="item in getAnalogDisplayOptions('color_format')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('colorDepth')" :prop="`screens.${index}.colorDepth`">
                    <el-select v-model="item.colorDepth">
                      <el-option
                        v-for="item in getAnalogDisplayOptions('color_depth')?.[index] || []"
                        :label="item"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </template>
          <el-divider />
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item :label="$t('version')" prop="version">
                <el-input spellcheck="false" v-model="formData.version" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('packageType')">
                <el-select v-model="formData.resourcePackaging">
                  <el-option :label="$t('cCode')" value="c" />
                  <el-option :label="$t('cCodeBin')" value="c_bin" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                v-if="formData.resourcePackaging === 'c_bin'"
                :label="$t('binNumber')"
                prop="binNum"
              >
                <el-input spellcheck="false" v-model.number="formData.binNum" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item :label="$t('fontPackaging')">
                <el-select v-model="formData.fontPackaging">
                  <el-option :label="$t('cCode')" value="c" />
                  <el-option label="BIN" value="bin" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="$t('vectorFont')" prop="vectorFont">
                <el-switch v-model="formData.vectorFont" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('projectDesc')">
                <el-input spellcheck="false" type="textarea" v-model="formData.description" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-scrollbar>
      <div class="w-200px shrink-0 flex flex-col" v-if="mode === 'add'">
        <Recent @opened="close" />
      </div>
    </div>

    <template #footer>
      <el-button @click="close()">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="mode === 'add' ? handleSubmit() : handleEdit()">{{
        $t('create')
      }}</el-button>
    </template>

    <el-dialog
      :title="$t('customResolution')"
      v-model="showScreenModal"
      width="440px"
      :modal="false"
      align-center
     append-to-body draggable>
      <el-form ref="resolutionFormRef" :model="customScreen" hide-required-asterisk>
        <el-form-item
          :label="$t('width')"
          prop="width"
          :rules="[{ required: true, message: $t('widthRequired') }]"
        >
          <el-input spellcheck="false" v-model.number="customScreen.width" />
        </el-form-item>
        <el-form-item
          :label="$t('height')"
          prop="height"
          :rules="[{ required: true, message: $t('heightRequired') }]"
        >
          <el-input spellcheck="false" v-model.number="customScreen.height" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleSetScreen">{{ $t('confirm') }}</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import type { AppMeta } from '@/types/appMeta'
import { ElMessage, type FormInstance } from 'element-plus'
import { computed, reactive, ref, nextTick, watch } from 'vue'
import { LuFolder } from 'vue-icons-plus/lu'
import { useProjectStore } from '@/store/modules/project'
import { useRecentProject } from '@/store/modules/recentProject'
import { useAppStore } from '@/store/modules/app'
import { useLocalStorageState } from 'vue-hooks-plus'
import { useI18n } from 'vue-i18n'
import { klona } from 'klona'
import { getNextIndex } from '@/utils'

import Recent from './Recent.vue'

import chipConfig from '@/config/multi_chip_config.json'
import boardConfig from '@/config/board_card_config .json'
import displayConfig from '@/config/analog_display_config.json'

const props = defineProps<{
  initHide?: boolean
}>()

const [projectPath, setProjectPath] = useLocalStorageState('projectPath', {
  defaultValue: 'D:\\sunmicroDesignerProjects'
})
const [codePath, setCodePath] = useLocalStorageState('codePath', { defaultValue: '\\code' })
const { t } = useI18n()
const mode = ref<'add' | 'edit'>('add')
const projectStore = useProjectStore()
const appStore = useAppStore()
const recentProject = useRecentProject()

const formData = reactive<
  AppMeta & {
    path: string
  }
>({
  version: '1.0.0',
  description: '',
  name: '',
  path: projectPath.value || '',
  codePath: codePath.value || '',
  type: 'chip',
  chip: {
    model: '',
    flash_size: {
      capacity: '16',
      unit: 'M'
    },
    // 鍐呭瓨澶у皬
    ram_size: {
      capacity: '4',
      unit: 'M'
    }
  },
  screenType: 'single',
  screens: [
    {
      type: 1,
      interface: '',
      screenDirection: '',
      width: 800,
      height: 480,
      colorDepth: '16',
      colorFormat: 'BGR',
      params: {
        PCLK: undefined,
        HFP: undefined,
        HBP: undefined,
        HSW: undefined,
        HSPOL: undefined,
        VFP: undefined,
        VBP: undefined,
        VSW: undefined,
        VSPOL: undefined
      }
    }
  ],
  board: {
    model: ''
  },
  resourcePackaging: 'c',
  binNum: 1,
  language: 'zh-cn',
  createTime: undefined,
  modifyTime: undefined,
  imageCompress: [],
  videoFormats: [],
  fontPackaging: 'c',
  vectorFont: false
})

/**
 * 璁剧疆榛樿椤圭洰鍚?
 */
const setProjectDefaultName = () => {
  const index = getNextIndex(recentProject.recentProjects || [], 'projectName')

  formData.name = `projectName_${index}`
}

watch(() => recentProject.recentProjects, setProjectDefaultName, { immediate: true })

const form = ref<FormInstance>()
const resolutionFormRef = ref<FormInstance>()
// 鏄剧ず妯℃€佹
const showModal = ref(!props.initHide)
// 鏄剧ず鑷畾涔夊睆骞曟ā鎬佹
const showScreenModal = ref(false)
// 鑷畾涔夊睆骞?
const customScreen = ref({
  width: 0,
  height: 0,
  index: 0
})
// 椤圭洰绫诲瀷閫夐」
const typeOptions = computed(() => {
  return (
    appStore.lang && [
      { label: t('chip'), value: 'chip' },
      { label: t('board'), value: 'board' },
      { label: t('analogDisplay'), value: 'analog_display' }
    ]
  )
})

const rules = computed(() => {
  return {
    name: [
      { required: true, message: t('nameRequired'), trigger: 'blur' },
      {
        trigger: 'blur',
        validator: (_rule, val, callback) => {
          const names = recentProject.recentProjects?.map((item) => item.projectName) || []
          if (names.includes(val) && mode.value === 'add') {
            callback(new Error(t('nameRepeat')))
          } else {
            callback()
          }
        }
      }
    ],
    codePath: [{ required: true, message: t('codePathRequired'), trigger: 'blur' }],
    path: [{ required: true, message: t('pathRequired'), trigger: 'blur' }],
    version: [{ required: true, message: t('versionRequired'), trigger: 'blur' }],
    'chip.model': [{ required: true, message: t('chipIsRequired'), trigger: 'blur' }],
    'chip.flash_size.capacity': [
      { required: true, message: t('flashIsRequired'), trigger: 'blur' }
    ],
    'chip.ram_size.capacity': [{ required: true, message: t('ramIsRequired'), trigger: 'blur' }],
    'screens.0.params.PCLK': [{ required: true, message: t('pclkRequired'), trigger: 'change' }],
    'screens.0.params.HFP': [{ required: true, message: t('HFPRequired'), trigger: 'change' }],
    'screens.0.params.HBP': [{ required: true, message: t('HBPRequired'), trigger: 'change' }],
    'screens.0.params.HSW': [{ required: true, message: t('HSWRequired'), trigger: 'change' }],
    'screens.0.params.HSPOL': [{ required: true, message: t('HSPOLRequired'), trigger: 'change' }],
    'screens.0.params.VFP': [{ required: true, message: t('VFPRequired'), trigger: 'change' }],
    'screens.0.params.VBP': [{ required: true, message: t('VBPRequired'), trigger: 'change' }],
    'screens.0.params.VSW': [{ required: true, message: t('VSWRequired'), trigger: 'change' }],
    'screens.0.params.VSPOL': [{ required: true, message: t('VSPOLRequired'), trigger: 'change' }],

    'screens.1.params.PCLK': [{ required: true, message: t('pclkRequired'), trigger: 'change' }],
    'screens.1.params.HFP': [{ required: true, message: t('HFPRequired'), trigger: 'change' }],
    'screens.1.params.HBP': [{ required: true, message: t('HBPRequired'), trigger: 'change' }],
    'screens.1.params.HSW': [{ required: true, message: t('HSWRequired'), trigger: 'change' }],
    'screens.1.params.HSPOL': [{ required: true, message: t('HSPOLRequired'), trigger: 'change' }],
    'screens.1.params.VFP': [{ required: true, message: t('VFPRequired'), trigger: 'change' }],
    'screens.1.params.VBP': [{ required: true, message: t('VBPRequired'), trigger: 'change' }],
    'screens.1.params.VSW': [{ required: true, message: t('VSWRequired'), trigger: 'change' }],
    'screens.1.params.VSPOL': [{ required: true, message: t('VSPOLRequired'), trigger: 'change' }]
  }
})

// 鍒囨崲椤圭洰绫诲瀷
const handlChangeType = (type: string) => {
  if (type === 'analog_display') {
    formData.imageCompress = getImageCompress(displayConfig.simulation_display.image_compression)
    formData.videoFormats = displayConfig.simulation_display.video_formats
  }
  if (type === 'board') {
    formData.screens = []
  }
  handleChangeScreenTypeByAnalog(formData.screenType)
}

// 閫夋嫨鏂囦欢澶硅矾寰?
const selectPath = async (key: string) => {
  const path = await window.electron.ipcRenderer.invoke('get-directory')

  if (path) {
    formData[key] = path
  }
}

// 閫夋嫨鍒嗚鲸鐜?
const handleSetResolution = (str: string, index: number) => {
  const arr = str.split('x')
  if (arr.length === 2) {
    formData.screens[index].width = Number(arr[0])
    formData.screens[index].height = Number(arr[1])
    handleSetScreenParams(index)
  }

  if (str === 'custom') {
    showScreenModal.value = true
    customScreen.value.index = index
    customScreen.value.width = formData.screens[index].width
    customScreen.value.height = formData.screens[index].height
  }
}

// 璁剧疆鑷畾涔夊垎杈ㄧ巼
const handleSetScreen = () => {
  resolutionFormRef.value?.validate()
  if (!customScreen.value.width || !customScreen.value.height) return

  formData.screens[customScreen.value.index].width = customScreen.value.width
  formData.screens[customScreen.value.index].height = customScreen.value.height
  showScreenModal.value = false
  handleSetScreenParams(customScreen.value.index)
}

// 鑾峰彇鍥剧墖鍘嬬缉鏂瑰紡
const getImageCompress = (params: Record<string, boolean>) => {
  return Object.keys(params || {}).filter((key) => params[key])
}
/******************************鑺墖鐩稿叧*******************************/
// 鑺墖閫夐」
const chipOptions = Object.keys(chipConfig?.chips || {})
// 宸查€夎姱鐗囬厤缃?
const selectedChipConfig = computed(() => chipConfig?.chips?.[formData.chip.model])
// 灞忓箷鎺ュ彛閫夐」
const getScreenOptions = (type: string) => {
  if (formData.screenType === 'single') {
    return [selectedChipConfig.value?.single_screen?.[type].options]
  } else {
    const options1 = selectedChipConfig.value?.dual_screen?.screen0?.[type].options
    const options2 = selectedChipConfig.value?.dual_screen?.screen1?.[type].options

    return [options1, options2]
  }
}

// 閫夋嫨鑺墖
const handleSelectChip = () => {
  // 璁剧疆榛樿鍊?

  // 鍥剧墖鍘嬬缉鏂瑰紡
  formData.imageCompress = getImageCompress(selectedChipConfig.value?.image_compression)
  formData.videoFormats = selectedChipConfig.value?.video_formats

  formData.chip.flash_size.capacity = selectedChipConfig.value?.flash_size?.capacity_default
  formData.chip.flash_size.unit = selectedChipConfig.value?.flash_size?.unit_default
  formData.chip.ram_size.capacity = selectedChipConfig.value?.ram_size?.capacity_default
  formData.chip.ram_size.unit = selectedChipConfig.value?.ram_size?.unit_default
  formData.screenType = selectedChipConfig.value?.screen_mode?.default || 'single'
  handleChangeScreenTypeByChip(formData.screenType)
}

// 闂瓨閫夐」
const querySearchFlash = (_query: string, cb: (data: any) => void) => {
  const list = selectedChipConfig.value?.flash_size?.capacity_options || []
  cb(list.map((item) => ({ value: item })))
}

// 鍐呭瓨閫夐」
const querySearchRam = (_query: string, cb: (data: any) => void) => {
  const list = selectedChipConfig.value?.ram_size?.capacity_options || []
  cb(list.map((item) => ({ value: item })))
}
// 璁剧疆灞忓箷鍙傛暟
const handleSetScreenParams = (index: number) => {
  const params =
    selectedChipConfig.value?.resolution_presets?.[
      `${formData.screens[index].width}x${formData.screens[index].height}`
    ]

  if (params) {
    Object.keys(formData.screens[index].params).forEach((key) => {
      ;(formData.screens[index].params as any)[key] = params[key]
    })
  }
}

// 閫夋嫨鑺墖灞忓箷绫诲瀷
const handleChangeScreenTypeByChip = (type: any) => {
  let screens =
    type === 'single'
      ? selectedChipConfig.value?.single_screen
      : selectedChipConfig.value?.dual_screen
  // 鏋勫缓鏁扮粍
  if (screens && type === 'single') {
    screens = [screens]
  }
  if (screens?.screen0) {
    screens = [screens.screen0, screens.screen1]
  }
  if (screens.length) {
    formData.screens = []
  }
  screens?.forEach((screen, index) => {
    const resolution = selectedChipConfig.value?.resolution_presets[screen?.resolutions.default]
    formData.screens.push({
      // 灞忓箷绫诲瀷
      type: index + 1,
      // 鎺ュ彛绫诲瀷
      interface: screen?.interface?.default,
      // 灞忓箷鏂瑰悜
      screenDirection: screen?.screen_direction?.default,
      // 灞忓箷瀹?
      width: resolution?.width,
      // 灞忓箷楂?
      height: resolution?.height,
      // 棰滆壊娣卞害
      colorDepth: screen?.color_depth?.default,
      // 棰滆壊鏍煎紡
      colorFormat: screen?.color_format?.default,
      // 灞忓箷鍙傛暟
      params: {
        PCLK: resolution?.PCLK,
        HFP: resolution?.HFP,
        HBP: resolution?.HBP,
        HSW: resolution?.HSW,
        HSPOL: resolution?.HSPOL,
        VFP: resolution?.VFP,
        VBP: resolution?.VBP,
        VSW: resolution?.VSW,
        VSPOL: resolution?.VSPOL
      }
    })
  })
}

/******************************鏉垮崱鐩稿叧*******************************/
// 鏌ヨ
const query = ref('')
// 鏉垮崱鍒楄〃
const boardOptions = ref(boardConfig.boards || [])
// 棰滆壊娣卞害閫夐」
const colorDepthOptions = ref<string[][]>([])
// 鎼滅储鏉垮崱
const searchBoard = () => {
  boardOptions.value = boardConfig.boards.filter((item) => item.board_name.includes(query.value))
}
// 鑾峰彇鏉垮崱灞忓箷閫夐」
const getBoardOptions = (type: string) => {
  if (formData.screenType === 'single') {
    return [
      boardConfig.boards.find((board) => board.board_name === formData.board.model)?.[type]
        .options || []
    ]
  } else {
    const options1 =
      boardConfig.boards.find((board) => board.board_name === formData.board.model)?.screen0?.[type]
        .options || []
    const options2 =
      boardConfig.boards.find((board) => board.board_name === formData.board.model)?.screen1?.[type]
        .options || []
    return [options1, options2]
  }
}
// 閫夋嫨鏉垮崱
const handleSetBoard = (board: any) => {
  formData.board.model = board.board_name
  formData.imageCompress = getImageCompress(board.image_compression)
  formData.videoFormats = board.video_formats
  formData.screenType = board.screen_mode
  handleChangeScreenTypeByBoard(board)
}
// 璁剧疆鏉垮崱鏄剧ず灞忓箷绫诲瀷
const handleChangeScreenTypeByBoard = (board: any) => {
  const screens =
    board.screen_mode === 'single'
      ? [
          {
            resolutions: board.resolutions,
            color_format: board.color_format,
            color_depth: board.color_depth,
            screen_direction: board?.screen_direction
          }
        ]
      : [board.screen0, board.screen1]

  if (screens) {
    formData.screens = []
    colorDepthOptions.value = []
  }
  screens.forEach((screen, index) => {
    const resolutions = screen.resolutions
    const arr = resolutions.split('x')
    colorDepthOptions.value.push(screen.color_depth.options)
    formData.screens.push({
      type: index + 1,
      width: Number(arr[0]),
      height: Number(arr[1]),
      colorDepth: screen?.color_depth?.default,
      colorFormat: screen?.color_format,
      interface: '',
      screenDirection: screen?.screen_direction?.default,
      params: {
        PCLK: undefined,
        HFP: undefined,
        HBP: undefined,
        HSW: undefined,
        HSPOL: undefined,
        VFP: undefined,
        VBP: undefined,
        VSW: undefined,
        VSPOL: undefined
      }
    })
  })
}

/******************************铏氭嫙鏄剧ず鐩稿叧*******************************/
// 鑾峰彇铏氭嫙鏄剧ず灞忓箷閫夐」
const getAnalogDisplayOptions = (type: string) => {
  if (formData.screenType === 'single') {
    return [displayConfig.simulation_display.single_screen[type].options]
  } else {
    const options1 = displayConfig.simulation_display?.dual_screen?.screen0?.[type].options
    const options2 = displayConfig.simulation_display?.dual_screen?.screen1?.[type].options

    return [options1, options2]
  }
}

// 閫夋嫨铏氭嫙鏄剧ず灞忓箷绫诲瀷
const handleChangeScreenTypeByAnalog = (type: any) => {
  const screens =
    type === 'single'
      ? [displayConfig.simulation_display.single_screen]
      : [
          displayConfig.simulation_display.dual_screen.screen0,
          displayConfig.simulation_display.dual_screen.screen1
        ]

  if (screens) {
    formData.screens = []
  }
  screens.forEach((screen, index) => {
    const resolutions = screen.resolutions
    const arr = resolutions.default.split('x')
    formData.screens.push({
      type: index + 1,
      width: Number(arr[0]),
      height: Number(arr[1]),
      colorDepth: screen?.color_depth?.default,
      colorFormat: screen?.color_format?.default,
      interface: '',
      screenDirection: screen?.screen_direction?.default,
      params: {
        PCLK: undefined,
        HFP: undefined,
        HBP: undefined,
        HSW: undefined,
        HSPOL: undefined,
        VFP: undefined,
        VBP: undefined,
        VSW: undefined,
        VSPOL: undefined
      }
    })
  })
}

// 鍒涘缓椤圭洰
const handleSubmit = async () => {
  await form.value?.validate()
  if (formData.type === 'board' && !formData.board.model) {
    ElMessage.warning(t('selectBoard'))
    return
  }
  // 璁颁綇椤圭洰璺緞
  setProjectPath(formData.path)
  setCodePath(formData.codePath)

  projectStore.createApp(formData)
  form.value?.resetFields()
  showModal.value = false
}

// 缂栬緫椤圭洰
const handleEdit = async () => {
  await form.value?.validate()
}

// 鍏抽棴寮圭獥
const close = (done?: () => void) => {
  // if (!projectStore.project) {
  //   ElMessage.warning(t('createProjectFirst'))
  //   return
  // }

  done?.()
  form.value?.resetFields()
  showModal.value = false
}

// expose
defineExpose({
  create: async () => {
    mode.value = 'add'
    showModal.value = true
    form.value?.resetFields()
    await nextTick()
    formData.path = projectPath.value || ''
    formData.codePath = codePath.value || ''
    setProjectDefaultName()
  },
  edit: () => {
    const data = klona(projectStore.project?.meta || {})
    Object.entries(data).forEach(([key, value]) => {
      formData[key] = value
    })
    mode.value = 'edit'
    showModal.value = true
  }
})
</script>

<style lang="less" scoped>
.modal-body-scroll {
  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
