<template>
  <ElDialog
    v-model="dialogVisible"
    title="手动更新卡实名状态"
    width="400px"
    @closed="handleDialogClosed"
  >
    <ElForm ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <ElFormItem label="资产标识">
        <span style="font-weight: bold; color: #409eff">{{ assetIdentifier }}</span>
      </ElFormItem>
      <ElFormItem label="当前状态">
        <ElTag :type="currentRealnameStatus === 1 ? 'success' : 'warning'">
          {{ currentRealnameStatus === 1 ? '已实名' : '未实名' }}
        </ElTag>
      </ElFormItem>
      <ElFormItem label="实名状态" prop="real_name_status">
        <ElRadioGroup v-model="formData.real_name_status">
          <ElRadio :value="0">未实名</ElRadio>
          <ElRadio :value="1">已实名</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" :loading="submitLoading" @click="handleSubmit">确认</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { AssetService } from '@/api/modules'
  import type { RealNameStatus } from '@/types/api'

  interface Props {
    modelValue: boolean
    assetIdentifier: string
    currentRealnameStatus?: RealNameStatus
  }

  const props = withDefaults(defineProps<Props>(), {
    currentRealnameStatus: 0
  })

  const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    success: []
  }>()

  const dialogVisible = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
  })

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

  const formData = reactive({
    real_name_status: 0 as 0 | 1
  })

  const formRules: FormRules = {
    real_name_status: [{ required: true, message: '请选择实名状态', trigger: 'change' }]
  }

  watch(dialogVisible, (val) => {
    if (val) {
      formData.real_name_status = props.currentRealnameStatus ?? 0
    }
  })

  const handleDialogClosed = () => {
    formRef.value?.resetFields()
  }

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

    await formRef.value.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        try {
          await AssetService.updateRealnameStatus(props.assetIdentifier, {
            real_name_status: formData.real_name_status
          })
          ElMessage.success('实名状态更新成功')
          dialogVisible.value = false
          emit('success')
        } catch (error) {
          console.error('更新实名状态失败:', error)
        } finally {
          submitLoading.value = false
        }
      }
    })
  }
</script>
