<template>
  <ElDrawer
    v-model="visible"
    :title="t('store.audit.detail.title')"
    size="900px"
    direction="rtl"
    @closed="handleClosed"
  >
    <div class="px-4 pb-4" v-loading="loading">
      <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <div class="text-lg font-semibold">
            {{ detail?.store?.name || t('store.audit.detail.empty') }}
          </div>
          <div class="text-sm text-gray-500">
            {{ detail?.tenant?.name || '-' }}
          </div>
        </div>
        <div class="flex flex-wrap items-center gap-2">
          <ElButton type="success" :disabled="!canApprove" @click="handleApprove">
            {{ t('store.audit.action.approve') }}
          </ElButton>
          <ElButton type="danger" :disabled="!canReject" @click="openRejectDialog">
            {{ t('store.audit.action.reject') }}
          </ElButton>
          <ElButton type="warning" :disabled="!canRiskControl" @click="openRiskControl">
            {{ t('store.audit.action.riskControl') }}
          </ElButton>
        </div>
      </div>

      <ElAlert v-if="errorMessage" type="error" show-icon :title="errorMessage" class="mb-4" />

      <ElTabs v-model="activeTab">
        <ElTabPane :label="t('store.audit.detail.tabs.basic')" name="basic">
          <ElDescriptions v-if="detail" :column="2" border>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.storeName')">
              {{ detail.store.name || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.storeCode')">
              {{ detail.store.code || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.auditStatus')">
              <ElTag :type="getAuditStatusType(detail.store.auditStatus)">
                {{ getAuditStatusText(detail.store.auditStatus) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.ownershipType')">
              {{ getOwnershipTypeText(detail.store.ownershipType) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.phone')">
              {{ detail.store.phone || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.address')">
              {{ formatFullAddress(detail.store) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.submittedAt')">
              {{ formatDateTime(detail.store.submittedAt) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.signboard')">
              <ElImage
                v-if="detail.store.signboardImageUrl"
                :src="detail.store.signboardImageUrl"
                :preview-src-list="buildPreviewList(detail.store.signboardImageUrl)"
                class="signboard-image"
                fit="cover"
              />
              <span v-else>-</span>
            </ElDescriptionsItem>
          </ElDescriptions>

          <ElDivider content-position="left">{{
            t('store.audit.detail.sections.tenant')
          }}</ElDivider>
          <ElDescriptions v-if="detail" :column="2" border>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.tenantName')">
              {{ detail.tenant.name || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.tenantContact')">
              {{ detail.tenant.contactName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.tenantPhone')">
              {{ detail.tenant.contactPhone || '-' }}
            </ElDescriptionsItem>
          </ElDescriptions>

          <ElDivider content-position="left">{{
            t('store.audit.detail.sections.merchant')
          }}</ElDivider>
          <ElDescriptions v-if="detail" :column="2" border>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.merchantName')">
              {{ detail.merchant.name || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.merchantLegal')">
              {{ detail.merchant.legalName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.audit.detail.fields.merchantCredit')">
              {{ detail.merchant.creditCode || '-' }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </ElTabPane>

        <ElTabPane :label="t('store.audit.detail.tabs.qualification')" name="qualification">
          <ElEmpty
            v-if="!detail?.qualifications?.length"
            :description="t('store.audit.detail.empty')"
          />
          <ElTable v-else :data="detail.qualifications" border>
            <ElTableColumn
              prop="qualificationType"
              :label="t('store.qualification.table.type')"
              min-width="140"
            >
              <template #default="{ row }">
                {{ getQualificationTypeText(row.qualificationType) }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="documentNumber"
              :label="t('store.qualification.table.documentNumber')"
              min-width="160"
            />
            <ElTableColumn
              prop="issuedAt"
              :label="t('store.qualification.form.issuedAt')"
              width="140"
            >
              <template #default="{ row }">
                {{ formatDate(row.issuedAt) }}
              </template>
            </ElTableColumn>
            <ElTableColumn
              prop="expiresAt"
              :label="t('store.qualification.table.expiresAt')"
              width="140"
            >
              <template #default="{ row }">
                {{ formatDate(row.expiresAt) }}
              </template>
            </ElTableColumn>
            <ElTableColumn :label="t('store.qualification.table.status')" width="120">
              <template #default="{ row }">
                <ElTag :type="getQualificationStatusType(row)">
                  {{ getQualificationStatusText(row) }}
                </ElTag>
              </template>
            </ElTableColumn>
            <ElTableColumn :label="t('store.audit.detail.fields.file')" min-width="140">
              <template #default="{ row }">
                <ElLink v-if="row.fileUrl" :href="row.fileUrl" target="_blank" type="primary">
                  {{ t('store.audit.detail.viewFile') }}
                </ElLink>
                <span v-else>-</span>
              </template>
            </ElTableColumn>
          </ElTable>
        </ElTabPane>

        <ElTabPane :label="t('store.audit.detail.tabs.history')" name="history">
          <ElEmpty
            v-if="!detail?.auditHistory?.length"
            :description="t('store.audit.detail.empty')"
          />
          <ElTable v-else :data="detail.auditHistory" border>
            <ElTableColumn prop="actionName" :label="t('store.audit.history.action')" width="140" />
            <ElTableColumn
              prop="operatorName"
              :label="t('store.audit.history.operator')"
              width="140"
            />
            <ElTableColumn prop="remark" :label="t('store.audit.history.remark')" min-width="200" />
            <ElTableColumn prop="createdAt" :label="t('store.audit.history.createdAt')" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.createdAt) }}
              </template>
            </ElTableColumn>
          </ElTable>
        </ElTabPane>
      </ElTabs>
    </div>

    <StoreRiskControlDialog ref="riskControlRef" @saved="handleRiskSaved" />

    <ElDialog
      v-model="rejectDialogVisible"
      :title="t('store.audit.reject.title')"
      width="520px"
      destroy-on-close
      @closed="handleRejectClosed"
    >
      <ElForm ref="rejectFormRef" :model="rejectForm" :rules="rejectRules" label-width="110px">
        <ElFormItem :label="t('store.audit.reject.reason')" prop="rejectionReasonId">
          <ElSelect v-model="rejectForm.rejectionReasonId" class="w-full">
            <ElOption
              v-for="option in rejectReasonOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem
          v-if="isOtherRejectReason"
          :label="t('store.audit.reject.reasonText')"
          prop="rejectionReasonText"
        >
          <ElInput
            v-model="rejectForm.rejectionReasonText"
            :placeholder="t('store.audit.reject.reasonTextPlaceholder')"
          />
        </ElFormItem>
        <ElFormItem :label="t('store.audit.reject.remark')" prop="remark">
          <ElInput
            v-model="rejectForm.remark"
            type="textarea"
            :rows="3"
            :placeholder="t('store.audit.reject.remarkPlaceholder')"
          />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="rejectDialogVisible = false">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="rejecting" @click="handleRejectSubmit">
          {{ t('common.confirm') }}
        </ElButton>
      </template>
    </ElDialog>
  </ElDrawer>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElAlert,
    ElButton,
    ElDescriptions,
    ElDescriptionsItem,
    ElDialog,
    ElDivider,
    ElDrawer,
    ElEmpty,
    ElForm,
    ElFormItem,
    ElImage,
    ElInput,
    ElLink,
    ElMessage,
    ElMessageBox,
    ElOption,
    ElSelect,
    ElTable,
    ElTableColumn,
    ElTabs,
    ElTabPane,
    ElTag
  } from 'element-plus'
  import {
    fetchApproveStoreAudit,
    fetchRejectStoreAudit,
    fetchStoreAuditDetail
  } from '@/api/storeAudit'
  import { StoreAuditStatus } from '@/enums/StoreAuditStatus'
  import { StoreOwnershipType } from '@/enums/StoreOwnershipType'
  import { StoreQualificationType } from '@/enums/StoreQualificationType'
  import { formatDate, formatDateTime } from '@/utils/billing'
  import StoreRiskControlDialog from '@/views/platform/store-audits/components/StoreRiskControlDialog.vue'
  import type { FormInstance, FormRules } from 'element-plus'

  defineOptions({ name: 'StoreAuditDetailDrawer' })

  type DetailTab = 'basic' | 'qualification' | 'history'

  interface RejectFormState {
    rejectionReasonId?: number
    rejectionReasonText: string
    remark: string
  }

  // 1. 基础状态
  const { t } = useI18n()
  const emit = defineEmits<{
    (event: 'updated'): void
  }>()
  const visible = ref(false)
  const loading = ref(false)
  const storeId = ref<string>('')
  const detail = ref<Api.StoreAudit.StoreAuditDetailDto | null>(null)
  const errorMessage = ref<string | null>(null)
  const activeTab = ref<DetailTab>('basic')
  const currentLoadToken = ref(0)

  // 2. 风控弹窗
  const riskControlRef = ref<InstanceType<typeof StoreRiskControlDialog>>()

  // 3. 驳回弹窗
  const rejectDialogVisible = ref(false)
  const rejectFormRef = ref<FormInstance>()
  const rejecting = ref(false)
  const rejectForm = ref<RejectFormState>({
    rejectionReasonId: undefined,
    rejectionReasonText: '',
    remark: ''
  })
  const rejectReasonOptions = [
    { value: 1001, label: t('store.audit.reject.reasonOptions.licenseMissing') },
    { value: 1002, label: t('store.audit.reject.reasonOptions.photoBlur') },
    { value: 1003, label: t('store.audit.reject.reasonOptions.inconsistent') },
    { value: 1099, label: t('store.audit.reject.reasonOptions.other') }
  ]
  const isOtherRejectReason = computed(() => rejectForm.value.rejectionReasonId === 1099)

  // 4. 驳回校验
  const rejectRules: FormRules<RejectFormState> = {
    rejectionReasonId: [
      { required: true, message: t('store.audit.reject.rules.reason'), trigger: 'change' }
    ],
    rejectionReasonText: [
      {
        validator: (_, value, callback) => {
          if (!isOtherRejectReason.value) {
            callback()
            return
          }
          if (!value || !value.trim()) {
            callback(new Error(t('store.audit.reject.rules.reasonText')))
            return
          }
          callback()
        },
        trigger: 'blur'
      }
    ]
  }

  // 5. 权限状态
  const canApprove = computed(() => detail.value?.store?.auditStatus === StoreAuditStatus.Pending)
  const canReject = computed(() => canApprove.value)
  const canRiskControl = computed(
    () => detail.value?.store?.auditStatus === StoreAuditStatus.Activated
  )

  const open = async (id: string) => {
    visible.value = true
    storeId.value = id
    activeTab.value = 'basic'
    await loadDetail()
  }

  const loadDetail = async () => {
    if (!storeId.value) {
      return
    }
    const token = ++currentLoadToken.value
    loading.value = true
    errorMessage.value = null
    try {
      const response = await fetchStoreAuditDetail(storeId.value)
      if (token !== currentLoadToken.value) {
        return
      }
      detail.value = response
    } catch (error) {
      console.error(error)
      errorMessage.value = t('store.audit.detail.loadFailed')
    } finally {
      if (token === currentLoadToken.value) {
        loading.value = false
      }
    }
  }

  const handleApprove = async () => {
    if (!storeId.value) {
      return
    }
    try {
      const { value } = await ElMessageBox.prompt(
        t('store.audit.approve.prompt'),
        t('store.audit.action.approve'),
        {
          confirmButtonText: t('common.confirm'),
          cancelButtonText: t('common.cancel'),
          inputType: 'textarea',
          inputPlaceholder: t('store.audit.approve.placeholder')
        }
      )
      const remark = value?.trim() || undefined
      await fetchApproveStoreAudit(storeId.value, { remark })
      ElMessage.success(t('store.audit.approve.success'))
      await loadDetail()
      emit('updated')
    } catch {
      // 取消操作不处理
    }
  }

  const openRejectDialog = () => {
    rejectDialogVisible.value = true
  }

  const handleRejectSubmit = async () => {
    if (!storeId.value || !rejectFormRef.value) {
      return
    }
    await rejectFormRef.value.validate(async (valid) => {
      if (!valid) {
        return
      }
      rejecting.value = true
      try {
        await fetchRejectStoreAudit(storeId.value, {
          rejectionReasonId: rejectForm.value.rejectionReasonId ?? 0,
          rejectionReasonText: rejectForm.value.rejectionReasonText.trim() || undefined,
          remark: rejectForm.value.remark.trim() || undefined
        })
        ElMessage.success(t('store.audit.reject.success'))
        rejectDialogVisible.value = false
        await loadDetail()
        emit('updated')
      } finally {
        rejecting.value = false
      }
    })
  }

  const handleRejectClosed = () => {
    rejectForm.value = {
      rejectionReasonId: undefined,
      rejectionReasonText: '',
      remark: ''
    }
    rejectFormRef.value?.clearValidate()
  }

  const openRiskControl = () => {
    if (!storeId.value) {
      return
    }
    riskControlRef.value?.open({
      storeId: storeId.value,
      storeName: detail.value?.store?.name || ''
    })
  }

  const handleRiskSaved = async () => {
    await loadDetail()
    emit('updated')
  }

  const handleClosed = () => {
    visible.value = false
    detail.value = null
    storeId.value = ''
    errorMessage.value = null
    activeTab.value = 'basic'
  }

  // 6. 展示辅助
  const getAuditStatusType = (status: StoreAuditStatus) => {
    switch (status) {
      case StoreAuditStatus.Draft:
        return 'info'
      case StoreAuditStatus.Pending:
        return 'warning'
      case StoreAuditStatus.Activated:
        return 'success'
      case StoreAuditStatus.Rejected:
        return 'danger'
      default:
        return 'info'
    }
  }
  const getAuditStatusText = (status: StoreAuditStatus) => {
    switch (status) {
      case StoreAuditStatus.Draft:
        return t('store.auditStatus.draft')
      case StoreAuditStatus.Pending:
        return t('store.auditStatus.pending')
      case StoreAuditStatus.Activated:
        return t('store.auditStatus.activated')
      case StoreAuditStatus.Rejected:
        return t('store.auditStatus.rejected')
      default:
        return t('store.auditStatus.unknown')
    }
  }
  const getOwnershipTypeText = (type?: StoreOwnershipType) => {
    switch (type) {
      case StoreOwnershipType.SameEntity:
        return t('store.ownership.same')
      case StoreOwnershipType.DifferentEntity:
        return t('store.ownership.different')
      default:
        return '-'
    }
  }
  const getQualificationTypeText = (type: StoreQualificationType) => {
    switch (type) {
      case StoreQualificationType.BusinessLicense:
        return t('store.qualification.type.businessLicense')
      case StoreQualificationType.FoodServiceLicense:
        return t('store.qualification.type.foodService')
      case StoreQualificationType.StorefrontPhoto:
        return t('store.qualification.type.storefront')
      case StoreQualificationType.InteriorPhoto:
        return t('store.qualification.type.interior')
      default:
        return '-'
    }
  }
  const getQualificationStatusType = (row: Api.Store.StoreQualificationDto) => {
    if (row.isExpired) {
      return 'danger'
    }
    if (row.isExpiringSoon) {
      return 'warning'
    }
    return 'success'
  }
  const getQualificationStatusText = (row: Api.Store.StoreQualificationDto) => {
    if (row.isExpired) {
      return t('store.qualification.status.expired')
    }
    if (row.isExpiringSoon) {
      return t('store.qualification.status.expiringSoon')
    }
    return t('store.qualification.status.valid')
  }
  const formatFullAddress = (target: Api.StoreAudit.StoreAuditStoreDto) =>
    `${target.province ?? ''}${target.city ?? ''}${target.district ?? ''}${target.address ?? ''}` ||
    '-'
  const buildPreviewList = (url?: string | null) => (url ? [url] : [])

  defineExpose({ open })
</script>

<style scoped>
  .signboard-image {
    width: 120px;
    height: 80px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
  }
</style>
