<template>
  <ElDialog
    v-model="dialogVisible"
    :title="isEdit ? t('store.form.editTitle') : t('store.form.createTitle')"
    width="850px"
    destroy-on-close
    @closed="handleClosed"
  >
    <ElForm ref="formRef" :model="formModel" :rules="formRules" label-width="110px">
      <ElTabs v-model="activeTab" class="store-form-tabs">
        <!-- 1. 基础信息 -->
        <ElTabPane :label="t('store.form.tabs.basic')" name="basic">
          <div class="grid gap-4 py-4 md:grid-cols-2">
            <ElFormItem :label="t('store.form.merchantId')" prop="merchantId">
              <MerchantSelect v-model="formModel.merchantId" placeholder="输入商户名搜索并选择" />
            </ElFormItem>
            <ElFormItem :label="t('store.form.code')" prop="code">
              <div class="flex w-full gap-2">
                <ElInput v-model="formModel.code" :placeholder="t('store.form.codePlaceholder')" />
                <ElButton @click="handleGenerateCode" :icon="Refresh" plain title="重新生成" />
              </div>
            </ElFormItem>
            <ElFormItem :label="t('store.form.name')" prop="name">
              <ElInput v-model="formModel.name" :placeholder="t('store.form.namePlaceholder')" />
            </ElFormItem>
            <ElFormItem :label="t('store.form.phone')" prop="phone">
              <ElInput v-model="formModel.phone" :placeholder="t('store.form.phonePlaceholder')" />
            </ElFormItem>
            <ElFormItem :label="t('store.form.managerName')" prop="managerName">
              <ElInput
                v-model="formModel.managerName"
                :placeholder="t('store.form.managerNamePlaceholder')"
              />
            </ElFormItem>
            <ElFormItem
              :label="t('store.form.signboardImageUrl')"
              prop="signboardImageUrl"
              class="col-span-full"
            >
              <ImageUpload
                v-model="formModel.signboardImageUrl"
                upload-type="other"
                box-width="100%"
                box-height="150px"
              />
            </ElFormItem>
          </div>
        </ElTabPane>

        <!-- 2. 位置信息 -->
        <ElTabPane :label="t('store.form.tabs.location')" name="location">
          <div class="grid gap-4 py-4 md:grid-cols-2">
            <ElFormItem :label="t('tenant.manualCreate.field.region')" class="col-span-full">
              <ElCascader
                v-model="regionCodes"
                class="w-full"
                filterable
                clearable
                :options="regionOptions"
                :props="regionProps"
                :placeholder="t('tenant.manualCreate.placeholder.region')"
                @change="handleRegionChange"
              />
            </ElFormItem>
            <ElFormItem :label="t('store.form.province')" prop="province">
              <ElInput v-model="formModel.province" disabled />
            </ElFormItem>
            <ElFormItem :label="t('store.form.city')" prop="city">
              <ElInput v-model="formModel.city" disabled />
            </ElFormItem>
            <ElFormItem :label="t('store.form.district')" prop="district">
              <ElInput v-model="formModel.district" disabled />
            </ElFormItem>
            <ElFormItem :label="t('store.form.address')" prop="address" class="col-span-full">
              <ElInput
                v-model="formModel.address"
                type="textarea"
                :rows="2"
                :placeholder="t('store.form.addressPlaceholder')"
              />
            </ElFormItem>
            <ElFormItem
              :label="t('store.form.coordinate')"
              prop="coordinateText"
              class="col-span-full"
            >
              <div class="flex w-full flex-wrap items-center gap-2">
                <ElInput
                  v-model="formModel.coordinateText"
                  class="min-w-[220px] flex-1"
                  :placeholder="t('store.form.coordinatePlaceholder')"
                  @blur="handleCoordinateBlur"
                >
                  <template #append>
                    <ElButton :loading="pasting" type="primary" link @click="handlePasteCoordinate">
                      {{ t('store.form.coordinatePasteAction') }}
                    </ElButton>
                  </template>
                </ElInput>
                <ElButton plain @click="openCoordinatePicker">
                  {{ t('store.form.coordinatePickerAction') }}
                </ElButton>
              </div>
              <div class="mt-1 text-xs text-gray-500">
                {{ t('store.form.coordinateHint') }}
              </div>
            </ElFormItem>
            <ElFormItem :label="t('store.form.deliveryRadiusKm')" prop="deliveryRadiusKm">
              <ElInputNumber
                v-model="formModel.deliveryRadiusKm"
                class="w-full"
                :min="0"
                :step="0.1"
              />
            </ElFormItem>
          </div>
        </ElTabPane>

        <!-- 3. 经营设置 -->
        <ElTabPane :label="t('store.form.tabs.settings')" name="settings">
          <div class="grid gap-4 py-4 md:grid-cols-2">
            <ElFormItem :label="t('store.form.status')" prop="status">
              <ElSelect v-model="formModel.status" class="w-full">
                <ElOption
                  v-for="option in statusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem :label="t('store.form.ownershipType')" prop="ownershipType">
              <ElSelect v-model="formModel.ownershipType" class="w-full" :disabled="isEdit">
                <ElOption
                  v-for="option in ownershipTypeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem :label="t('store.form.categoryId')" prop="categoryId">
              <CategorySelect
                v-model="formModel.categoryId"
                :placeholder="t('store.form.categoryIdPlaceholder')"
              />
            </ElFormItem>
            <ElFormItem :label="t('store.form.announcement')" prop="announcement">
              <ElInput
                v-model="formModel.announcement"
                type="textarea"
                :rows="2"
                :placeholder="t('store.form.announcementPlaceholder')"
              />
            </ElFormItem>
            <ElFormItem :label="t('store.form.tags')" prop="tags">
              <ElInput v-model="formModel.tags" :placeholder="t('store.form.tagsPlaceholder')" />
            </ElFormItem>
          </div>
        </ElTabPane>

        <!-- 4. 服务设施 -->
        <ElTabPane :label="t('store.form.tabs.services')" name="services">
          <div class="grid gap-6 py-4 md:grid-cols-2 lg:grid-cols-3">
            <div
              v-for="item in serviceOptions"
              :key="item.prop"
              class="flex items-center justify-between rounded-lg border border-[var(--el-border-color-lighter)] p-4 transition-all hover:bg-[var(--el-fill-color-lighter)]"
            >
              <div class="flex items-center gap-3">
                <div
                  class="flex h-10 w-10 items-center justify-center rounded-full bg-[var(--el-color-primary-light-9)] text-[var(--el-color-primary)]"
                >
                  <ArtSvgIcon :icon="item.icon" :size="20" />
                </div>
                <div class="flex flex-col">
                  <span class="text-sm font-medium">{{ t(`store.form.${item.prop}`) }}</span>
                  <span class="text-xs text-[var(--el-text-color-secondary)]">
                    {{ item.desc }}
                  </span>
                </div>
              </div>
              <ElSwitch v-model="formModel[item.prop]" />
            </div>
          </div>
        </ElTabPane>
      </ElTabs>
    </ElForm>
    <template #footer>
      <ElButton @click="dialogVisible = false">{{ t('common.cancel') }}</ElButton>
      <ElButton v-if="currentTabIndex > 0" @click="handlePrev">
        {{ t('common.prevStep') }}
      </ElButton>
      <ElButton v-if="!isLastTab" type="primary" @click="handleNext">
        {{ t('common.nextStep') }}
      </ElButton>
      <ElButton v-else type="primary" :loading="saving" @click="handleSubmit">
        {{ t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, ref, toRefs, watch } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElMessage,
    ElOption,
    ElSelect,
    ElSwitch,
    ElTabs,
    ElTabPane
  } from 'element-plus'
  import { Refresh } from '@element-plus/icons-vue'
  import { fetchCreateStore, fetchUpdateStore } from '@/api/store'
  import { StoreOwnershipType } from '@/enums/StoreOwnershipType'
  import { StoreStatus } from '@/enums/StoreStatus'
  import type { FormInstance, FormRules, CascaderValue, CascaderOption } from 'element-plus'
  import ImageUpload from '@/components/common/ImageUpload.vue'
  import MerchantSelect from '@/components/common/MerchantSelect.vue'
  import CategorySelect from '@/components/common/CategorySelect.vue'
  import ArtSvgIcon from '@/components/core/base/art-svg-icon/index.vue'
  import { regionData, codeToText } from 'element-china-area-data'

  defineOptions({ name: 'StoreFormDialog' })

  interface StoreFormState {
    merchantId: string
    code: string
    name: string
    phone?: string
    managerName?: string
    status: StoreStatus
    signboardImageUrl: string
    ownershipType: StoreOwnershipType
    categoryId?: string
    province?: string
    city?: string
    district?: string
    address?: string
    longitude?: number
    latitude?: number
    coordinateText: string
    announcement?: string
    tags?: string
    deliveryRadiusKm: number
    supportsDineIn: boolean
    supportsPickup: boolean
    supportsDelivery: boolean
    supportsReservation: boolean
    supportsQueueing: boolean
  }

  // 1. 基础输入输出
  const props = withDefaults(
    defineProps<{
      modelValue: boolean
      store?: Api.Store.StoreDto | null
    }>(),
    { store: null }
  )
  const emit = defineEmits<{
    (event: 'update:modelValue', value: boolean): void
    (event: 'saved'): void
  }>()
  const { t } = useI18n()
  const { modelValue, store } = toRefs(props)

  const activeTab = ref('basic')
  const regionCodes = ref<CascaderValue>([])

  /** 随机生成门店编码 */
  const handleGenerateCode = () => {
    const timestamp = Date.now().toString(36).toUpperCase()
    const random = Math.random().toString(36).substring(2, 5).toUpperCase()
    formModel.value.code = `S${timestamp}${random}`
  }

  const regionProps = {
    value: 'value',
    label: 'label',
    children: 'children'
  } as const
  const regionOptions = regionData as unknown as CascaderOption[]

  /** 处理行政区划变更 */
  const handleRegionChange = (value: CascaderValue | null | undefined) => {
    const codes = (Array.isArray(value) ? value : []) as string[]
    const [pCode, cCode, dCode] = codes

    formModel.value.province = pCode ? (codeToText as any)[pCode] || '' : ''
    formModel.value.city = cCode ? (codeToText as any)[cCode] || '' : ''
    formModel.value.district = dCode ? (codeToText as any)[dCode] || '' : ''
  }

  const createDefaultForm = (): StoreFormState => ({
    merchantId: '',
    code: '',
    name: '',
    phone: '',
    managerName: '',
    status: StoreStatus.Closed,
    signboardImageUrl: '',
    ownershipType: StoreOwnershipType.SameEntity,
    categoryId: '',
    province: '',
    city: '',
    district: '',
    address: '',
    longitude: undefined,
    latitude: undefined,
    coordinateText: '',
    announcement: '',
    tags: '',
    deliveryRadiusKm: 0,
    supportsDineIn: true,
    supportsPickup: true,
    supportsDelivery: true,
    supportsReservation: false,
    supportsQueueing: false
  })

  // 2. 表单状态
  const formRef = ref<FormInstance>()
  const saving = ref(false)
  const formModel = ref<StoreFormState>(createDefaultForm())
  const pasting = ref(false)

  // 3. 下拉选项
  const ownershipTypeOptions = [
    { value: StoreOwnershipType.SameEntity, label: t('store.ownership.same') },
    { value: StoreOwnershipType.DifferentEntity, label: t('store.ownership.different') }
  ]
  const statusOptions = [
    { value: StoreStatus.Closed, label: t('store.status.closed') },
    { value: StoreStatus.Preparing, label: t('store.status.preparing') },
    { value: StoreStatus.Operating, label: t('store.status.operating') },
    { value: StoreStatus.Suspended, label: t('store.status.suspended') }
  ]

  const serviceOptions: { prop: keyof StoreFormState; icon: string; desc: string }[] = [
    { prop: 'supportsDineIn', icon: 'ri:restaurant-line', desc: '店内堂食服务' },
    { prop: 'supportsPickup', icon: 'ri:shopping-bag-3-line', desc: '到店自提服务' },
    { prop: 'supportsDelivery', icon: 'ri:bike-line', desc: '外卖配送服务' },
    { prop: 'supportsReservation', icon: 'ri:calendar-check-line', desc: '提前预约订座' },
    { prop: 'supportsQueueing', icon: 'ri:group-line', desc: '在线排队取号' }
  ]

  // 4. 校验规则
  const formRules: FormRules<StoreFormState> = {
    merchantId: [{ required: true, message: t('store.rules.merchantId'), trigger: 'blur' }],
    code: [{ required: true, message: t('store.rules.code'), trigger: 'blur' }],
    name: [{ required: true, message: t('store.rules.name'), trigger: 'blur' }],
    signboardImageUrl: [
      { required: true, message: t('store.rules.signboardImageUrl'), trigger: 'blur' }
    ],
    ownershipType: [{ required: true, message: t('store.rules.ownershipType'), trigger: 'change' }],
    coordinateText: [
      { required: true, message: t('store.rules.coordinateText'), trigger: 'blur' },
      {
        validator: (_, value, callback) => {
          if (!value?.trim()) {
            callback(new Error(t('store.rules.coordinateText')))
            return
          }
          const parsed = parseCoordinateText(value)
          if (!parsed) {
            callback(new Error(t('store.rules.coordinateTextFormat')))
            return
          }
          formModel.value.longitude = parsed.lng
          formModel.value.latitude = parsed.lat
          callback()
        },
        trigger: 'blur'
      }
    ]
  }

  // 5. 视图计算
  const isEdit = computed(() => Boolean(store.value))
  const dialogVisible = computed({
    get: () => modelValue.value,
    set: (value) => emit('update:modelValue', value)
  })
  const normalizeCoordinateText = (lat: number, lng: number) =>
    `${lat.toFixed(6)},${lng.toFixed(6)}`

  const parseCoordinateText = (value: string): { lat: number; lng: number } | null => {
    if (!value?.trim()) return null
    const parts = value
      .trim()
      .replace(/[，\s]+/g, ',')
      .split(',')
      .filter(Boolean)
    if (parts.length < 2) return null
    const first = Number(parts[0])
    const second = Number(parts[1])
    if (Number.isNaN(first) || Number.isNaN(second)) return null
    const absFirst = Math.abs(first)
    const absSecond = Math.abs(second)
    const isLngLat = absFirst > 90 && absSecond <= 90
    const isLatLng = absFirst <= 90 && absSecond <= 180
    if (isLngLat) {
      return { lat: second, lng: first }
    }
    if (isLatLng) {
      return { lat: first, lng: second }
    }
    return null
  }

  const syncCoordinateText = (value: string, normalize = false) => {
    const parsed = parseCoordinateText(value)
    if (!parsed) return false
    formModel.value.longitude = parsed.lng
    formModel.value.latitude = parsed.lat
    if (normalize) {
      formModel.value.coordinateText = normalizeCoordinateText(parsed.lat, parsed.lng)
    }
    return true
  }

  const handleCoordinateBlur = () => {
    if (!formModel.value.coordinateText) return
    syncCoordinateText(formModel.value.coordinateText, true)
  }

  const handlePasteCoordinate = async () => {
    if (!navigator.clipboard?.readText) {
      ElMessage.warning(t('store.form.coordinatePasteUnavailable'))
      return
    }
    pasting.value = true
    try {
      const text = (await navigator.clipboard.readText())?.trim()
      if (!text) {
        ElMessage.warning(t('store.form.coordinatePasteEmpty'))
        return
      }
      formModel.value.coordinateText = text
      if (!syncCoordinateText(text, true)) {
        ElMessage.warning(t('store.form.coordinateInvalid'))
      }
    } catch {
      ElMessage.warning(t('store.form.coordinatePasteUnavailable'))
    } finally {
      pasting.value = false
    }
  }

  const openCoordinatePicker = () => {
    window.open('https://lbs.qq.com/getPoint/', '_blank')
  }

  // Tab 顺序定义
  const tabs = ['basic', 'location', 'settings', 'services']
  const currentTabIndex = computed(() => tabs.indexOf(activeTab.value))
  const isLastTab = computed(() => currentTabIndex.value === tabs.length - 1)

  // 每个 Tab 对应的需要校验的字段
  const tabFields: Record<string, (keyof StoreFormState)[]> = {
    basic: ['merchantId', 'code', 'name', 'phone', 'managerName', 'signboardImageUrl'],
    location: ['province', 'city', 'district', 'address', 'coordinateText', 'deliveryRadiusKm'],
    settings: ['status', 'ownershipType', 'categoryId', 'announcement', 'tags'],
    services: [
      'supportsDineIn',
      'supportsPickup',
      'supportsDelivery',
      'supportsReservation',
      'supportsQueueing'
    ]
  }

  // 6. 同步编辑数据
  watch(
    store,
    (current) => {
      if (!current) {
        formModel.value = createDefaultForm()
        handleGenerateCode() // 新增时生成编码
        regionCodes.value = []
        return
      }
      formModel.value = {
        merchantId: String(current.merchantId),
        code: current.code,
        name: current.name,
        phone: current.phone ?? '',
        managerName: current.managerName ?? '',
        status: current.status,
        signboardImageUrl: current.signboardImageUrl ?? '',
        ownershipType: current.ownershipType,
        categoryId: current.categoryId ? String(current.categoryId) : '',
        province: current.province ?? '',
        city: current.city ?? '',
        district: current.district ?? '',
        address: current.address ?? '',
        longitude: current.longitude ?? undefined,
        latitude: current.latitude ?? undefined,
        coordinateText:
          current.latitude !== null &&
          current.latitude !== undefined &&
          current.longitude !== null &&
          current.longitude !== undefined
            ? normalizeCoordinateText(current.latitude, current.longitude)
            : '',
        announcement: current.announcement ?? '',
        tags: current.tags ?? '',
        deliveryRadiusKm: current.deliveryRadiusKm,
        supportsDineIn: current.supportsDineIn,
        supportsPickup: current.supportsPickup,
        supportsDelivery: current.supportsDelivery,
        supportsReservation: current.supportsReservation,
        supportsQueueing: current.supportsQueueing
      }

      // 如果有详细位置信息，尝试反推级联选择器的值（这里暂不处理反推，因为 codeToText 是单向的，
      // 除非后端存了区域编码。通常建议后端存区域编码以支持回显）
      regionCodes.value = []
    },
    { immediate: true }
  )

  const buildCreatePayload = (): Api.Store.CreateStoreRequest => ({
    merchantId: formModel.value.merchantId.trim(),
    code: formModel.value.code.trim(),
    name: formModel.value.name.trim(),
    phone: formModel.value.phone?.trim() || undefined,
    managerName: formModel.value.managerName?.trim() || undefined,
    status: formModel.value.status,
    signboardImageUrl: formModel.value.signboardImageUrl.trim(),
    ownershipType: formModel.value.ownershipType,
    categoryId: formModel.value.categoryId?.trim() || undefined,
    province: formModel.value.province?.trim() || undefined,
    city: formModel.value.city?.trim() || undefined,
    district: formModel.value.district?.trim() || undefined,
    address: formModel.value.address?.trim() || undefined,
    longitude: formModel.value.longitude ?? undefined,
    latitude: formModel.value.latitude ?? undefined,
    announcement: formModel.value.announcement?.trim() || undefined,
    tags: formModel.value.tags?.trim() || undefined,
    deliveryRadiusKm: formModel.value.deliveryRadiusKm,
    supportsDineIn: formModel.value.supportsDineIn,
    supportsPickup: formModel.value.supportsPickup,
    supportsDelivery: formModel.value.supportsDelivery,
    supportsReservation: formModel.value.supportsReservation,
    supportsQueueing: formModel.value.supportsQueueing
  })

  const buildUpdatePayload = (): Api.Store.UpdateStoreRequest => ({
    merchantId: formModel.value.merchantId.trim(),
    code: formModel.value.code.trim(),
    name: formModel.value.name.trim(),
    phone: formModel.value.phone?.trim() || undefined,
    managerName: formModel.value.managerName?.trim() || undefined,
    status: formModel.value.status,
    signboardImageUrl: formModel.value.signboardImageUrl.trim(),
    categoryId: formModel.value.categoryId?.trim() || undefined,
    province: formModel.value.province?.trim() || undefined,
    city: formModel.value.city?.trim() || undefined,
    district: formModel.value.district?.trim() || undefined,
    address: formModel.value.address?.trim() || undefined,
    longitude: formModel.value.longitude ?? undefined,
    latitude: formModel.value.latitude ?? undefined,
    announcement: formModel.value.announcement?.trim() || undefined,
    tags: formModel.value.tags?.trim() || undefined,
    deliveryRadiusKm: formModel.value.deliveryRadiusKm,
    supportsDineIn: formModel.value.supportsDineIn,
    supportsPickup: formModel.value.supportsPickup,
    supportsDelivery: formModel.value.supportsDelivery,
    supportsReservation: formModel.value.supportsReservation,
    supportsQueueing: formModel.value.supportsQueueing
  })

  /** 下一步 */
  const handleNext = async () => {
    if (!formRef.value) return
    const currentTabName = activeTab.value
    const fieldsToValidate = tabFields[currentTabName]

    // 校验当前页字段
    if (fieldsToValidate) {
      try {
        await formRef.value.validateField(fieldsToValidate)
      } catch {
        return // 校验失败不跳转
      }
    }

    if (currentTabIndex.value < tabs.length - 1) {
      activeTab.value = tabs[currentTabIndex.value + 1]
    }
  }

  /** 上一步 */
  const handlePrev = () => {
    if (currentTabIndex.value > 0) {
      activeTab.value = tabs[currentTabIndex.value - 1]
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) {
      return
    }

    if (formModel.value.coordinateText) {
      syncCoordinateText(formModel.value.coordinateText, true)
    }

    // 1. 校验表单 (最后提交时再全量校验一次，以防万一)
    await formRef.value.validate(async (valid) => {
      if (!valid) {
        return
      }

      // 2. 执行提交
      saving.value = true
      try {
        if (store.value) {
          await fetchUpdateStore(String(store.value.id), buildUpdatePayload())
          ElMessage.success(t('store.message.updateSuccess'))
        } else {
          await fetchCreateStore(buildCreatePayload())
          ElMessage.success(t('store.message.createSuccess'))
        }
        emit('saved')
        dialogVisible.value = false
      } finally {
        saving.value = false
      }
    })
  }

  const handleClosed = () => {
    // 1. 清理校验状态
    formRef.value?.clearValidate()

    // 2. 重置 Tab 和数据
    activeTab.value = 'basic'
    if (!store.value) {
      formModel.value = createDefaultForm()
      regionCodes.value = []
    }
  }
</script>

<style lang="scss" scoped>
  .store-form-tabs {
    :deep(.el-tabs__content) {
      overflow: visible;
    }
  }
</style>
