<template>
  <ElDialog
    v-model="visible"
    :title="t('store.audit.riskControl.title')"
    width="520px"
    destroy-on-close
    @closed="handleClosed"
  >
    <div class="mb-4 text-sm text-gray-500">
      {{ t('store.audit.riskControl.storeName', { name: storeName || '-' }) }}
    </div>
    <ElForm ref="formRef" :model="formModel" :rules="formRules" label-width="110px">
      <ElFormItem :label="t('store.audit.riskControl.action')" prop="action">
        <ElRadioGroup v-model="formModel.action">
          <ElRadioButton :label="RiskControlAction.ForceClose">
            {{ t('store.audit.riskControl.forceClose') }}
          </ElRadioButton>
          <ElRadioButton :label="RiskControlAction.Reopen">
            {{ t('store.audit.riskControl.reopen') }}
          </ElRadioButton>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem
        v-if="formModel.action === RiskControlAction.ForceClose"
        :label="t('store.audit.riskControl.reason')"
        prop="reason"
      >
        <ElInput
          v-model="formModel.reason"
          :placeholder="t('store.audit.riskControl.reasonPlaceholder')"
        />
      </ElFormItem>
      <ElFormItem :label="t('store.audit.riskControl.remark')" prop="remark">
        <ElInput
          v-model="formModel.remark"
          type="textarea"
          :rows="3"
          :placeholder="t('store.audit.riskControl.remarkPlaceholder')"
        />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="visible = false">{{ t('common.cancel') }}</ElButton>
      <ElButton type="primary" :loading="saving" @click="handleSubmit">
        {{ t('common.confirm') }}
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElMessage,
    ElRadioButton,
    ElRadioGroup
  } from 'element-plus'
  import { fetchForceCloseStore, fetchReopenStore } from '@/api/storeAudit'
  import type { FormInstance, FormRules } from 'element-plus'

  defineOptions({ name: 'StoreRiskControlDialog' })

  enum RiskControlAction {
    ForceClose = 'force-close',
    Reopen = 'reopen'
  }

  interface RiskControlFormState {
    action: RiskControlAction
    reason: string
    remark: string
  }

  interface OpenOptions {
    storeId: string
    storeName?: string
    action?: RiskControlAction
  }

  // 1. 基础状态
  const { t } = useI18n()
  const emit = defineEmits<{
    (event: 'saved'): void
  }>()
  const formRef = ref<FormInstance>()
  const saving = ref(false)
  const storeId = ref<string>('')
  const storeName = ref<string>('')
  const visible = ref(false)

  // 2. 表单状态
  const formModel = ref<RiskControlFormState>({
    action: RiskControlAction.ForceClose,
    reason: '',
    remark: ''
  })

  // 3. 表单校验
  const formRules: FormRules<RiskControlFormState> = {
    action: [
      { required: true, message: t('store.audit.riskControl.rules.action'), trigger: 'change' }
    ],
    reason: [
      {
        validator: (_, value, callback) => {
          if (formModel.value.action !== RiskControlAction.ForceClose) {
            callback()
            return
          }
          if (!value || !value.trim()) {
            callback(new Error(t('store.audit.riskControl.rules.reason')))
            return
          }
          callback()
        },
        trigger: 'blur'
      }
    ]
  }

  // 4. 动作判断
  const isForceClose = computed(() => formModel.value.action === RiskControlAction.ForceClose)

  const open = (options: OpenOptions) => {
    visible.value = true
    storeId.value = options.storeId
    storeName.value = options.storeName || ''
    formModel.value = {
      action: options.action ?? RiskControlAction.ForceClose,
      reason: '',
      remark: ''
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value || !storeId.value) {
      return
    }
    await formRef.value.validate(async (valid) => {
      if (!valid) {
        return
      }
      saving.value = true
      try {
        if (isForceClose.value) {
          await fetchForceCloseStore(storeId.value, {
            reason: formModel.value.reason.trim(),
            remark: formModel.value.remark.trim() || undefined
          })
          ElMessage.success(t('store.audit.riskControl.forceCloseSuccess'))
        } else {
          await fetchReopenStore(storeId.value, {
            remark: formModel.value.remark.trim() || undefined
          })
          ElMessage.success(t('store.audit.riskControl.reopenSuccess'))
        }
        emit('saved')
        visible.value = false
      } finally {
        saving.value = false
      }
    })
  }

  const handleClosed = () => {
    storeId.value = ''
    storeName.value = ''
    formRef.value?.clearValidate()
  }

  defineExpose({ open })
</script>
