<template>
  <ElDialog v-model="visible" title="客户账号列表" width="80%" @close="handleClose">
    <!-- 搜索栏 -->
    <ArtSearchBar
      v-model:filter="searchForm"
      :items="searchFormItems"
      :show-expand="false"
      @reset="handleReset"
      @search="handleSearch"
    ></ArtSearchBar>

    <!-- 表格 -->
    <ArtTable
      ref="tableRef"
      row-key="ID"
      :loading="loading"
      :data="accountList"
      height="60vh"
      :currentPage="pagination.page"
      :pageSize="pagination.pageSize"
      :total="pagination.total"
      :marginTop="10"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #default>
        <ElTableColumn v-for="col in columns" :key="col.prop || (col as any).type" v-bind="col" />
      </template>
    </ArtTable>
  </ElDialog>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { ElTag } from 'element-plus'
  import { AccountService } from '@/api/modules'
  import type { SearchFormItem } from '@/types'
  import type { PlatformAccount } from '@/types/api'
  import { formatDateTime } from '@/utils/business/format'

  // 用户类型映射
  const getUserTypeName = (type: number): string => {
    const typeMap: Record<number, string> = {
      1: '超级管理员',
      2: '平台用户',
      3: '代理账号',
      4: '企业账号'
    }
    return typeMap[type] || '未知'
  }

  // 状态名称映射
  const getStatusName = (status: number): string => {
    return status === 1 ? '启用' : '禁用'
  }

  const props = defineProps<{
    modelValue: boolean
    shopId?: number
    enterpriseId?: number
  }>()

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

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

  const loading = ref(false)
  const tableRef = ref()
  const accountList = ref<PlatformAccount[]>([])

  // 搜索表单初始值
  const initialSearchState = {
    username: '',
    phone: '',
    user_type: undefined as number | undefined,
    status: undefined as number | undefined
  }

  // 搜索表单
  const searchForm = reactive({ ...initialSearchState })

  // 分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0
  })

  // 搜索表单配置
  const searchFormItems: SearchFormItem[] = [
    {
      label: '用户名',
      prop: 'username',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入用户名'
      }
    },
    {
      label: '手机号',
      prop: 'phone',
      type: 'input',
      config: {
        clearable: true,
        placeholder: '请输入手机号'
      }
    },
    {
      label: '用户类型',
      prop: 'user_type',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '代理账号', value: 3 },
        { label: '企业账号', value: 4 }
      ]
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      config: {
        clearable: true,
        placeholder: '全部'
      },
      options: () => [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 }
      ]
    }
  ]

  // 获取用户类型标签类型
  const getUserTypeTag = (type: number) => {
    return type === 3 ? 'success' : 'primary'
  }

  // 获取状态标签类型
  const getStatusTag = (status: number) => {
    return status === 1 ? 'success' : 'info'
  }

  // 列配置
  const columns = computed(() => [
    {
      prop: 'username',
      label: '用户名',
      minWidth: 150
    },
    {
      prop: 'phone',
      label: '手机号',
      width: 130
    },
    {
      prop: 'user_type',
      label: '用户类型',
      width: 110,
      formatter: (row: PlatformAccount) => {
        return h(ElTag, { type: getUserTypeTag(row.user_type) }, () =>
          getUserTypeName(row.user_type)
        )
      }
    },
    {
      prop: 'shop_id',
      label: '店铺ID',
      width: 100,
      formatter: (row: PlatformAccount) => String(row.shop_id || '-')
    },
    {
      prop: 'enterprise_id',
      label: '企业ID',
      width: 100,
      formatter: (row: PlatformAccount) => String(row.enterprise_id || '-')
    },
    {
      prop: 'status',
      label: '状态',
      width: 100,
      formatter: (row: PlatformAccount) => {
        return h(ElTag, { type: getStatusTag(row.status) }, () => getStatusName(row.status))
      }
    },
    {
      prop: 'CreatedAt',
      label: '创建时间',
      width: 180,
      formatter: (row: PlatformAccount) => formatDateTime(row.CreatedAt)
    }
  ])

  // 监听弹窗打开，重新加载数据
  watch(
    () => props.modelValue,
    (newVal) => {
      if (newVal) {
        handleReset()
      }
    }
  )

  // 获取客户账号列表
  const getTableData = async () => {
    loading.value = true
    try {
      const params: any = {
        page: pagination.page,
        page_size: pagination.pageSize,
        username: searchForm.username || undefined,
        phone: searchForm.phone || undefined,
        user_type: searchForm.user_type,
        status: searchForm.status
      }

      // 根据传入的参数筛选
      if (props.shopId) {
        params.shop_id = props.shopId
      }
      if (props.enterpriseId) {
        params.enterprise_id = props.enterpriseId
      }

      // 清理空值
      Object.keys(params).forEach((key) => {
        if (params[key] === '' || params[key] === undefined) {
          delete params[key]
        }
      })

      const res = await AccountService.getAccounts(params)
      if (res.code === 0) {
        accountList.value = res.data.items || []
        pagination.total = res.data.total || 0
      }
    } catch (error) {
      console.error(error)
      console.log('获取客户账号列表失败')
    } finally {
      loading.value = false
    }
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(searchForm, { ...initialSearchState })
    pagination.page = 1
    getTableData()
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getTableData()
  }

  // 处理表格分页变化
  const handleSizeChange = (newPageSize: number) => {
    pagination.pageSize = newPageSize
    getTableData()
  }

  const handleCurrentChange = (newCurrentPage: number) => {
    pagination.page = newCurrentPage
    getTableData()
  }

  // 关闭弹窗
  const handleClose = () => {
    // 重置搜索表单
    Object.assign(searchForm, { ...initialSearchState })
    pagination.page = 1
    accountList.value = []
  }
</script>

<style lang="scss" scoped>
  // 客户账号列表弹窗样式
</style>
