<template>
  <popup
    v-model="showDialog"
    title="配置选项"
    width="600px"
    :align-center="false"
    :close-on-click-modal="false"
    style="max-width: 100%"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="90px">
      <el-form-item label="下拉类型">
        <el-radio-group v-model="formData.optionsType">
          <el-radio label="normal">普通选项</el-radio>
          <el-radio label="remote">远程下拉</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="formData.optionsType === 'normal'">
        <div class="mt-[-4px] mb-4 pl-[90px]">
          <el-button type="primary" icon="Plus" @click="handleAddOption">添加Label值对</el-button>
        </div>
        <el-scrollbar max-height="320px" class="pl-[90px]">
          <div class="flex flex-col gap-3">
            <div class="flex items-center gap-3" v-for="(item, index) in formData.optionsList" :key="index">
              <el-input class="w-[180px]" v-model="item.label" placeholder="Label (展示)" />
              <el-input class="w-[180px]" v-model="item.value" placeholder="Value (值)" />
              <el-button type="danger" icon="Delete" circle size="small" @click="handleRemoveOption(index)" />
            </div>
          </div>
        </el-scrollbar>
        <div class="mt-4 border-t border-br pt-4 pl-[90px]">
          <div class="text-base mb-3">数据预览</div>
          <div class="border border-br text-sm rounded px-3 py-1.5">
            {{ previewOptionsStr || '暂无数据' }}
          </div>
        </div>
      </div>
      <div v-else>
        <el-form-item label="关联模型" prop="remoteOptions.model">
          <el-select
            class="w-full"
            v-model="formData.remoteOptions.model"
            filterable
            placeholder="请选择关联模型"
            @change="handleChangeModel"
          >
            <el-option
              v-for="item in modelList"
              :key="item.value"
              :label="item.name + ' (' + item.value + ')'"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="Label字段" prop="remoteOptions.label_field">
          <el-select
            class="w-full"
            v-model="formData.remoteOptions.label_field"
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入Label字段"
          >
            <el-option
              v-for="field in modelFields"
              :key="field.name"
              :label="(field.desc || field.name) + ' (' + field.name + ')'"
              :value="field.name"
            />
          </el-select>
          <div class="text-sm text-info leading-normal mt-1">下拉框显示的文字字段，可手动输入</div>
        </el-form-item>
        <el-form-item label="Value字段" prop="remoteOptions.value_field">
          <el-select
            class="w-full"
            v-model="formData.remoteOptions.value_field"
            filterable
            placeholder="请选择Value字段"
          >
            <el-option
              v-for="field in modelFields"
              :key="field.name"
              :label="field.name + (field.desc ? ' (' + field.desc + ')' : '')"
              :value="field.name"
            />
          </el-select>
          <div class="text-sm text-info leading-normal mt-1">下拉框选中的值字段</div>
        </el-form-item>
      </div>
    </el-form>
  </popup>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { generatorModels, generatorColumns } from '@/api/tool/generator'

// 定义组件事件
const emit = defineEmits<{
  (event: 'success', index: number, data: any): void
}>()

// 表单引用
const formRef = shallowRef<FormInstance>()
// 是否显示弹窗
const showDialog = ref(false)
// 关联模型字段列表
const modelFields = ref<any[]>([])
// 关联模型列表
const modelList = ref<any[]>([])
// 当前选中行索引
const currentIndex = ref(-1)
// 表单数据
const formData = reactive({
  optionsType: 'normal',
  optionsList: [] as any[],
  remoteOptions: {
    model: '',
    label_field: '',
    value_field: ''
  }
})
// 表单验证规则
const formRules = {
  ['remoteOptions.model']: [{ required: true, message: '请选择关联模型', trigger: ['blur', 'change'] }],
  ['remoteOptions.label_field']: [{ required: true, message: '请选择或输入Label字段', trigger: ['blur', 'change'] }],
  ['remoteOptions.value_field']: [{ required: true, message: '请选择或输入Value字段', trigger: ['blur', 'change'] }]
}
// 预览选项字符串
const previewOptionsStr = computed(() => {
  if (formData.optionsType === 'remote') {
    const modelName =
      modelList.value.find((item) => item.value === formData.remoteOptions.model)?.name || formData.remoteOptions.model
    return `远程下拉: ${modelName} (Label: ${formData.remoteOptions.label_field}, Value: ${formData.remoteOptions.value_field})`
  }
  return formData.optionsList
    .filter((item) => item.value !== '')
    .map((item) => `${item.value}:${item.label || item.value}`)
    .join(',')
})

// 打开弹窗
const open = (index: number) => {
  currentIndex.value = index
  getModelLists()
  showDialog.value = true
}
// 设置选项数据
const setFormData = async (data?: any) => {
  resetOptions()
  if (data) {
    let isJson = false
    try {
      const jsonObj = JSON.parse(data)
      if (jsonObj && typeof jsonObj === 'object') {
        if (jsonObj.type === 'remote') {
          formData.optionsType = 'remote'
          formData.optionsList = []
          formData.remoteOptions = {
            model: jsonObj.model || '',
            label_field: jsonObj.label_field || '',
            value_field: jsonObj.value_field || ''
          }
          isJson = true
          if (formData.remoteOptions.model) {
            handleChangeModel(formData.remoteOptions.model)
          }
        }
      }
    } catch (e) {
      isJson = false
    }
    if (!isJson && formData.optionsType === 'normal') {
      const pairs = data.split(',')
      pairs.forEach((p: string) => {
        const parts = p.split(':')
        const val = parts[0]
        const lab = parts[1] !== undefined ? parts[1] : val
        if (val !== '') {
          formData.optionsList.push({
            label: lab,
            value: val
          })
        }
      })
    }
  }
}
// 添加选项
const handleAddOption = () => {
  formData.optionsList.push({ label: '', value: '' })
}
// 删除选项
const handleRemoveOption = (index: number) => {
  formData.optionsList.splice(index, 1)
}
// 关联模型改变
const handleChangeModel = async (val: string) => {
  const model = modelList.value.find((item: any) => item.value === val)
  if (model && model.table_name) {
    try {
      const res = await generatorColumns({ table: model.table_name })
      if (res.fields) {
        modelFields.value = res.fields
      } else {
        modelFields.value = res
      }
      formData.remoteOptions.label_field = ''
      formData.remoteOptions.value_field = ''
    } catch (e) {
      console.error(e)
      modelFields.value = []
      formData.remoteOptions.label_field = ''
      formData.remoteOptions.value_field = ''
    }
  } else {
    modelFields.value = []
  }
}
// 选项重置
const resetOptions = () => {
  formData.optionsType = 'normal'
  formData.optionsList = []
  formData.remoteOptions = {
    model: '',
    label_field: '',
    value_field: ''
  }
  modelFields.value = []
}
// 获取关联模型列表
const getModelLists = () => {
  generatorModels().then((res: any) => {
    modelList.value = res
  })
}
// 提交表单
const handleSubmit = () => {
  if (formData.optionsType === 'remote') {
    formRef.value?.validate((valid) => {
      if (valid) {
        const config = {
          type: 'remote',
          ...formData.remoteOptions
        }
        emit('success', currentIndex.value, JSON.stringify(config))
        showDialog.value = false
      }
    })
  } else {
    const validOptions = formData.optionsList.filter((item) => {
      return item.label.trim() !== '' || item.value.trim() !== ''
    })
    if (validOptions.length === 0) {
      ElMessage.warning('请至少添加一项选项')
      return
    }
    const invalidItem = formData.optionsList.find((item) => {
      return (
        (item.label.trim() === '' && item.value.trim() !== '') || (item.label.trim() !== '' && item.value.trim() === '')
      )
    })
    if (invalidItem) {
      ElMessage.warning('请确保所有选项的Label和Value都已填写')
      return
    }
    const config = validOptions.map((item) => `${item.value}:${item.label}`).join(',')
    emit('success', currentIndex.value, config)
    showDialog.value = false
  }
}

defineExpose({
  open,
  setFormData
})
</script>
