<template>
  <ElDialog
    v-model="dialogVisible"
    :title="t('store.businessStatus.title')"
    width="480px"
    destroy-on-close
    @closed="handleClosed"
  >
    <ElAlert
      v-if="isForceClosed"
      type="warning"
      :title="t('store.businessStatus.forceClosedTip')"
      show-icon
      class="mb-4"
    />
    <ElForm ref="formRef" :model="formModel" :rules="formRules" label-width="110px">
      <ElFormItem :label="t('store.businessStatus.targetStatus')" prop="businessStatus">
        <ElRadioGroup v-model="formModel.businessStatus" :disabled="isForceClosed">
          <ElRadioButton :label="StoreBusinessStatus.Open">
            {{ t('store.businessStatus.open') }}
          </ElRadioButton>
          <ElRadioButton :label="StoreBusinessStatus.Resting">
            {{ t('store.businessStatus.resting') }}
          </ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem
        v-if="formModel.businessStatus === StoreBusinessStatus.Resting"
        :label="t('store.businessStatus.closureReason')"
        prop="closureReason"
      >
        <ElSelect v-model="formModel.closureReason" class="w-full" :disabled="isForceClosed">
          <ElOption
            v-for="option in closureReasonOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem
        v-if="formModel.businessStatus === StoreBusinessStatus.Resting"
        :label="t('store.businessStatus.closureReasonText')"
        prop="closureReasonText"
      >
        <ElInput
          v-model="formModel.closureReasonText"
          type="textarea"
          :rows="3"
          :placeholder="t('store.businessStatus.closureReasonTextPlaceholder')"
          :disabled="isForceClosed"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="dialogVisible = false">{{ t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="saving" :disabled="isForceClosed" @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 {
    ElAlert,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElMessage,
    ElOption,
    ElRadioButton,
    ElRadioGroup,
    ElSelect
  } from 'element-plus'
  import { fetchToggleBusinessStatus } from '@/api/store'
  import { StoreBusinessStatus } from '@/enums/StoreBusinessStatus'
  import { StoreClosureReason } from '@/enums/StoreClosureReason'
  import type { FormInstance, FormRules } from 'element-plus'

  defineOptions({ name: 'BusinessStatusDialog' })

  interface BusinessStatusFormState {
    businessStatus: StoreBusinessStatus
    closureReason?: StoreClosureReason | null
    closureReasonText?: string
  }

  // 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)

  // 2. 表单状态
  const formRef = ref<FormInstance>()
  const saving = ref(false)
  const formModel = ref<BusinessStatusFormState>({
    businessStatus: StoreBusinessStatus.Open,
    closureReason: undefined,
    closureReasonText: ''
  })

  // 3. 视图计算
  const dialogVisible = computed({
    get: () => modelValue.value,
    set: (value) => emit('update:modelValue', value)
  })
  const isForceClosed = computed(
    () => store.value?.businessStatus === StoreBusinessStatus.ForceClosed
  )

  // 4. 下拉选项
  const closureReasonOptions = [
    { value: StoreClosureReason.EquipmentMaintenance, label: t('store.closureReason.equipment') },
    { value: StoreClosureReason.OwnerVacation, label: t('store.closureReason.vacation') },
    { value: StoreClosureReason.OutOfStock, label: t('store.closureReason.outOfStock') },
    {
      value: StoreClosureReason.TemporarilyClosed,
      label: t('store.closureReason.temporarilyClosed')
    },
    { value: StoreClosureReason.Other, label: t('store.closureReason.other') }
  ]

  // 5. 校验规则
  const formRules: FormRules<BusinessStatusFormState> = {
    businessStatus: [
      { required: true, message: t('store.businessStatus.rules.status'), trigger: 'change' }
    ],
    closureReason: [
      {
        validator: (_, value, callback) => {
          if (formModel.value.businessStatus !== StoreBusinessStatus.Resting) {
            callback()
            return
          }
          if (value === undefined || value === null) {
            callback(new Error(t('store.businessStatus.rules.reason')))
            return
          }
          callback()
        },
        trigger: 'change'
      }
    ]
  }

  // 6. 同步门店状态
  watch(
    store,
    (current) => {
      if (!current) {
        formModel.value = {
          businessStatus: StoreBusinessStatus.Open,
          closureReason: undefined,
          closureReasonText: ''
        }
        return
      }
      formModel.value = {
        businessStatus: current.businessStatus,
        closureReason: current.closureReason ?? undefined,
        closureReasonText: current.closureReasonText ?? ''
      }
    },
    { immediate: true }
  )

  const buildPayload = (): Api.Store.ToggleBusinessStatusRequest => ({
    businessStatus: formModel.value.businessStatus,
    closureReason:
      formModel.value.businessStatus === StoreBusinessStatus.Resting
        ? formModel.value.closureReason
        : undefined,
    closureReasonText:
      formModel.value.businessStatus === StoreBusinessStatus.Resting
        ? formModel.value.closureReasonText?.trim() || undefined
        : undefined
  })

  const handleSubmit = async () => {
    const form = formRef.value
    const currentStore = store.value
    if (!currentStore || !form) return

    const storeId = String(currentStore.id)

    // 1. 校验表单
    await form.validate(async (valid) => {
      if (!valid) {
        return
      }

      // 2. 提交状态变更
      saving.value = true
      try {
        await fetchToggleBusinessStatus(storeId, buildPayload())
        ElMessage.success(t('store.message.statusUpdated'))
        emit('saved')
        dialogVisible.value = false
      } finally {
        saving.value = false
      }
    })
  }

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