<template>
  <el-dialog
    v-model="visible"
    title="删除渠道"
    width="560px"
    align-center
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="loading">
      <p class="mb-3 text-sm text-gray-600">确定删除渠道「{{ deptName }}」？可勾选一并删除的关联数据：</p>
      <el-alert
        v-if="preview?.user_count > 0"
        type="error"
        :closable="false"
        class="mb-3"
        :title="`该渠道下仍有 ${preview.user_count} 个用户，请先转移或删除用户`"
      />
      <el-checkbox-group v-model="checkedTables" class="flex flex-col gap-2">
        <el-checkbox
          v-for="item in preview?.relations || []"
          :key="item.table"
          :label="item.table"
          :disabled="preview?.user_count > 0"
        >
          {{ item.label }}（{{ item.count }} 条）
        </el-checkbox>
      </el-checkbox-group>
      <p v-if="!preview?.relations?.length" class="text-sm text-gray-500">无关联业务数据，仅删除渠道本身。</p>
    </div>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="danger"
        :loading="submitting"
        :disabled="preview?.user_count > 0"
        @click="handleConfirm"
      >
        确认删除
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import api from '@/api/system/dept'
  import { ElMessage } from 'element-plus'

  interface Props {
    modelValue: boolean
    deptId?: number | null
    deptName?: string
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    deptId: null,
    deptName: ''
  })

  const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }>()

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

  const loading = ref(false)
  const submitting = ref(false)
  const preview = ref<any>(null)
  const checkedTables = ref<string[]>([])

  watch(
    () => props.modelValue,
    async (open) => {
      if (!open || !props.deptId) {
        return
      }
      loading.value = true
      checkedTables.value = []
      try {
        const res: any = await api.destroyPreview(props.deptId)
        const list = res?.data ?? res
        preview.value = Array.isArray(list) ? list[0] : list
        checkedTables.value = (preview.value?.relations || []).map((r: any) => r.table)
      } finally {
        loading.value = false
      }
    }
  )

  const handleClose = () => {
    visible.value = false
  }

  const handleConfirm = async () => {
    if (!props.deptId) {
      return
    }
    submitting.value = true
    try {
      await api.delete({ ids: props.deptId, delete_tables: checkedTables.value })
      ElMessage.success('删除成功')
      emit('success')
      handleClose()
    } catch (e: unknown) {
      let msg = '删除失败'
      if (e !== null && typeof e === 'object' && 'message' in e) {
        const m = Reflect.get(e, 'message')
        if (typeof m === 'string' && m !== '') {
          msg = m
        }
      }
      ElMessage.error(msg)
    } finally {
      submitting.value = false
    }
  }
</script>
