<template>
  <ElDialog
    v-model="visible"
    :title="
      isEdit
        ? t('dictionary.labelOverride.editOverride')
        : t('dictionary.labelOverride.newOverride')
    "
    width="600px"
    :close-on-click-modal="false"
    @closed="handleClosed"
    @open="handleOpen"
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="top"
    >
      <!-- 1. 字典分组选择（新建时显示） -->
      <ElFormItem v-if="!isEdit" :label="t('dictionary.common.scope')" prop="groupId">
        <div class="group-selector">
          <ElSelect v-model="selectedScope" style="width: 120px" @change="handleScopeChange">
            <ElOption :label="t('dictionary.common.system')" :value="1" />
            <ElOption :label="t('dictionary.common.business')" :value="2" />
          </ElSelect>
          <ElSelect
            v-model="formData.groupId"
            :placeholder="t('dictionary.common.selectGroupFirst')"
            filterable
            style="flex: 1"
            @change="handleGroupChange"
          >
            <ElOption
              v-for="group in filteredGroups"
              :key="group.id"
              :label="`${group.name} (${group.code})`"
              :value="group.id"
            />
          </ElSelect>
        </div>
      </ElFormItem>

      <!-- 2. 字典项选择（新建时显示） -->
      <ElFormItem
        v-if="!isEdit"
        :label="t('dictionary.labelOverride.dictionaryItem')"
        prop="dictionaryItemId"
      >
        <ElSelect
          v-model="formData.dictionaryItemId"
          :placeholder="t('dictionary.labelOverride.selectDictionaryItem')"
          :disabled="!formData.groupId"
          filterable
          style="width: 100%"
          @change="handleItemSelect"
        >
          <ElOption
            v-for="item in groupItems"
            :key="item.id"
            :label="`${item.key} - ${getDisplayValue(item.value)}`"
            :value="item.id"
          />
        </ElSelect>
      </ElFormItem>

      <!-- 3. 显示原始值 -->
      <ElFormItem
        v-if="isEdit || selectedItem"
        :label="t('dictionary.labelOverride.originalValue')"
      >
        <div class="original-value-display">
          <div v-for="(val, lang) in selectedItem?.value || {}" :key="lang" class="i18n-row">
            <span class="lang-label">{{ getLangLabel(lang) }}:</span>
            <span class="lang-value">{{ val }}</span>
          </div>
        </div>
      </ElFormItem>

      <!-- 4. 覆盖值输入（多语言） -->
      <ElFormItem :label="t('dictionary.labelOverride.overrideValue')" prop="overrideValue">
        <I18nValueEditor v-model="formData.overrideValue" />
      </ElFormItem>

      <!-- 5. 覆盖原因 -->
      <ElFormItem :label="t('dictionary.labelOverride.reason')">
        <ElInput
          v-model="formData.reason"
          type="textarea"
          :rows="2"
          :placeholder="t('dictionary.labelOverride.reasonPlaceholder')"
        />
        <div class="form-hint">{{ t('dictionary.labelOverride.reasonHint') }}</div>
      </ElFormItem>
    </ElForm>

    <template #footer>
      <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="loading" @click="handleSubmit">
        {{ t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import type { FormInstance, FormRules } from 'element-plus'
  import { getGroups } from '@/api/dictionary/group'
  import { getItems } from '@/api/dictionary/item'
  import { DictionaryScope } from '@/enums/Dictionary'
  import I18nValueEditor from '@/views/system/dictionary/components/I18nValueEditor.vue'

  interface Props {
    modelValue: boolean
    editItem?: Api.Dictionary.LabelOverrideDto | null
    targetTenantId?: string | null
  }

  const props = withDefaults(defineProps<Props>(), {
    editItem: null,
    targetTenantId: null
  })

  const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    submit: [data: Api.Dictionary.UpsertLabelOverrideRequest]
  }>()

  const { t } = useI18n()

  // 1. 对话框状态
  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

  const formRef = ref<FormInstance>()
  const loading = ref(false)

  // 2. 分组和字典项数据
  const allGroups = ref<Api.Dictionary.DictionaryGroupDto[]>([])
  const groupItems = ref<Api.Dictionary.DictionaryItemDto[]>([])
  const selectedScope = ref<DictionaryScope>(DictionaryScope.System)

  // 3. 表单数据
  const formData = reactive<{
    groupId: string
    dictionaryItemId: string
    overrideValue: Record<string, string>
    reason: string
  }>({
    groupId: '',
    dictionaryItemId: '',
    overrideValue: {},
    reason: ''
  })

  // 4. 计算属性
  const isEdit = computed(() => !!props.editItem)

  const filteredGroups = computed(() => {
    return allGroups.value.filter((g) => g.scope === selectedScope.value)
  })

  const selectedItem = computed(() => {
    if (isEdit.value && props.editItem) {
      return {
        id: props.editItem.dictionaryItemId,
        key: props.editItem.dictionaryItemKey,
        value: props.editItem.originalValue
      }
    }
    return groupItems.value.find((item) => item.id === formData.dictionaryItemId)
  })

  // 5. 表单校验规则
  const formRules = computed<FormRules>(() => ({
    dictionaryItemId: [
      {
        required: true,
        message: t('dictionary.labelOverride.selectDictionaryItem'),
        trigger: 'change'
      }
    ],
    overrideValue: [
      {
        validator: (_rule, value, callback) => {
          const hasValue = Object.values(value || {}).some((v) => !!v)
          if (!hasValue) {
            callback(new Error(t('dictionary.labelOverride.overrideValueRequired')))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }))

  // 6. 辅助方法
  const getDisplayValue = (value: Record<string, string>) => {
    return value['zh'] || value['en'] || Object.values(value)[0] || ''
  }

  const getLangLabel = (lang: string) => {
    const labels: Record<string, string> = {
      zh: t('dictionary.i18n.zh'),
      en: t('dictionary.i18n.en')
    }
    return labels[lang] || lang
  }

  // 7. 加载分组数据
  const loadGroups = async () => {
    try {
      // 加载系统字典分组
      const systemResult = await getGroups({
        scope: DictionaryScope.System,
        Page: 1,
        PageSize: 200,
        isEnabled: true
      })

      // 加载业务字典分组
      const businessResult = await getGroups({
        scope: DictionaryScope.Business,
        Page: 1,
        PageSize: 200,
        isEnabled: true
      })

      allGroups.value = [...systemResult.items, ...businessResult.items]
    } catch {
      allGroups.value = []
    }
  }

  // 8. 加载字典项
  const loadGroupItems = async (groupId: string) => {
    if (!groupId) {
      groupItems.value = []
      return
    }

    try {
      groupItems.value = await getItems(groupId)
    } catch {
      groupItems.value = []
    }
  }

  // 9. 事件处理
  const handleScopeChange = () => {
    formData.groupId = ''
    formData.dictionaryItemId = ''
    groupItems.value = []
  }

  const handleGroupChange = async () => {
    formData.dictionaryItemId = ''
    await loadGroupItems(formData.groupId)
  }

  const handleItemSelect = () => {
    // 选择字典项后，预填覆盖值为原始值
    if (selectedItem.value) {
      formData.overrideValue = { ...selectedItem.value.value }
    }
  }

  const handleOpen = async () => {
    if (allGroups.value.length === 0) {
      await loadGroups()
    }
  }

  // 10. 提交处理
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true

      const request: Api.Dictionary.UpsertLabelOverrideRequest = {
        dictionaryItemId: isEdit.value
          ? props.editItem!.dictionaryItemId
          : formData.dictionaryItemId,
        overrideValue: formData.overrideValue,
        reason: formData.reason || undefined
      }

      emit('submit', request)
    } catch {
      // 校验失败
    } finally {
      loading.value = false
    }
  }

  // 11. 对话框关闭时重置
  const handleClosed = () => {
    formData.groupId = ''
    formData.dictionaryItemId = ''
    formData.overrideValue = {}
    formData.reason = ''
    groupItems.value = []
    selectedScope.value = DictionaryScope.System
    formRef.value?.resetFields()
  }

  // 12. 编辑模式初始化
  watch(
    () => props.editItem,
    (item) => {
      if (item) {
        formData.dictionaryItemId = item.dictionaryItemId
        formData.overrideValue = { ...item.overrideValue }
        formData.reason = item.reason || ''
      }
    },
    { immediate: true }
  )

  // 13. 暴露方法
  defineExpose({
    setLoading: (val: boolean) => {
      loading.value = val
    },
    close: () => {
      visible.value = false
    }
  })
</script>

<style scoped>
  .group-selector {
    display: flex;
    gap: 8px;
    width: 100%;
  }

  .original-value-display {
    padding: 8px 12px;
    background: var(--el-fill-color-light);
    border-radius: 4px;
  }

  .i18n-row {
    display: flex;
    gap: 8px;
    padding: 4px 0;
  }

  .lang-label {
    flex-shrink: 0;
    width: 40px;
    color: var(--el-text-color-secondary);
  }

  .lang-value {
    color: var(--el-text-color-primary);
  }

  .form-hint {
    margin-top: 4px;
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }
</style>
