<template>
  <div class="container">
    <Breadcrumb :items="['充值账户管理', '骆驼加油账号']" />
    <a-card class="general-card" title="骆驼加油账号管理">
      <!-- 搜索表单区域 -->
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="keyword" label="关键词">
                  <a-input
                    v-model="formModel.keyword"
                    placeholder="请输入账号ID/账号名称/手机号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="status" label="状态">
                  <a-select
                    v-model="formModel.status"
                    placeholder="请选择状态"
                    allow-clear
                  >
                    <a-option :value="0">待登录</a-option>
                    <a-option :value="1">发送验证码</a-option>
                    <a-option :value="2">在线</a-option>
                    <a-option :value="3">已暂停</a-option>
                    <a-option :value="4">已失效</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 42px" direction="vertical" />
        <a-col flex="172px" style="text-align: right">
          <a-space direction="horizontal" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />

      <!-- 操作按钮区域 -->
      <a-row style="margin-bottom: 16px">
        <a-space>
          <a-button @click="download">
            <template #icon>
              <icon-download />
            </template>
            导出
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据表格区域 -->
      <a-table
        :loading="loading"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          pageSizeOptions: [10, 20, 50, 100],
          showPageSize: true
        }"
        :columns="columns"
        :data="renderData"
        :scroll="{ x: 1200 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 状态列模板 -->
        <template #status="{ record }">
          <a-tag size="small" :color="statusColorMapper(record.status)">
            {{ record.statusText || statusMapper(record.status).text }}
          </a-tag>
        </template>

        <!-- 操作列模板 -->
        <template #operations="{ record }">
          <a-space size="small">
            <a-tooltip content="详情">
              <a-button size="small" @click="showDetailModal(record)">
                <template #icon>
                  <icon-list />
                </template>
              </a-button>
            </a-tooltip>
            <a-tooltip content="历史记录">
              <a-button size="small" @click="showHistoryModal(record)">
                <template #icon>
                  <icon-history />
                </template>
              </a-button>
            </a-tooltip>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 账号详情弹窗 -->
    <account-detail
      v-model:visible="state.detailModalVisible"
      :account-id="state.accountId"
    />

    <!-- 账号历史记录弹窗 -->
    <account-history
      v-model:visible="state.historyModalVisible"
      :account-id="state.accountId"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { Notification, TableColumnData } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { jdV2AccountClient } from '@/api/index.ts';
import type { KamiApiCamelOilV1AccountListItem } from '@/api/generated/models/index.ts';
import type {
  ApiJdV2AccountListGetPageSizeEnum,
  ApiJdV2AccountListGetStatusEnum
} from '@/api/generated/apis/jdv2-account-api';
import AccountDetail from './components/detail.vue';
import AccountHistory from './components/history.vue';

// 基础分页配置
const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};

// 状态管理
const pagination = reactive({ ...basePagination });
const { loading, setLoading } = useLoading(true);
const renderData = ref<KamiApiCamelOilV1AccountListItem[]>([]);

// 表格列配置
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    render: ({ rowIndex }) => {
      return rowIndex + 1 + (pagination.current - 1) * pagination.pageSize;
    }
  },
  {
    title: '账号名称',
    dataIndex: 'accountName',
    width: 150
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 130,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '最后使用时间',
    dataIndex: 'lastUsedAt',
    width: 150,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  {
    title: '失败原因',
    dataIndex: 'failureReason',
    width: 150,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    width: 150,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    fixed: 'right',
    width: 120
  }
];

// 搜索表单模型
const generateSearchFormModel = () => ({
  keyword: '',
  status: undefined as ApiJdV2AccountListGetStatusEnum | undefined
});

const formModel = ref(generateSearchFormModel());

// 弹窗状态管理
const state = reactive({
  detailModalVisible: false,
  historyModalVisible: false,
  accountId: '',
  account: null as KamiApiCamelOilV1AccountListItem | null
});

/**
 * 获取账号列表数据
 * @param params 查询参数
 */
const fetchAccountData = async (
  params: {
    current: number;
    pageSize: number;
    keyword?: string;
    status?: ApiJdV2AccountListGetStatusEnum;
  } = { current: 1, pageSize: 50 }
) => {
  setLoading(true);
  try {
    const { data } = await jdV2AccountClient.apiJdV2AccountListGet({
      current: params.current,
      pageSize: params.pageSize as ApiJdV2AccountListGetPageSizeEnum,
      keyword: params.keyword,
      status: params.status
    });

    renderData.value = data.list || [];
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = data.total || 0;
  } catch (error) {
    console.error('获取账号列表失败:', error);
    Notification.error({
      content: '获取账号列表失败',
      closable: true
    });
  } finally {
    setLoading(false);
  }
};

/**
 * 页码变化处理
 * @param current 当前页码
 */
const onPageChange = (current: number) => {
  fetchAccountData({
    ...pagination,
    current,
    keyword: formModel.value.keyword,
    status: formModel.value.status
  });
};

/**
 * 页面大小变化处理
 * @param pageSize 每页条数
 */
const onPageSizeChange = (pageSize: number) => {
  fetchAccountData({
    ...pagination,
    pageSize,
    current: 1,
    keyword: formModel.value.keyword,
    status: formModel.value.status
  });
};

/**
 * 搜索功能
 */
const search = () => {
  fetchAccountData({
    ...basePagination,
    keyword: formModel.value.keyword,
    status: formModel.value.status
  });
};

/**
 * 重置表单
 */
const reset = () => {
  formModel.value = generateSearchFormModel();
  search();
};

/**
 * 显示详情弹窗
 * @param record 账号记录
 */
const showDetailModal = (record: KamiApiCamelOilV1AccountListItem) => {
  state.accountId = record.accountId?.toString() || '';
  state.detailModalVisible = true;
};

/**
 * 显示历史记录弹窗
 * @param record 账号记录
 */
const showHistoryModal = (record: KamiApiCamelOilV1AccountListItem) => {
  state.accountId = record.accountId?.toString() || '';
  state.historyModalVisible = true;
};

/**
 * 状态颜色映射器
 * 基于后端Go定义的状态：
 * - 0: 待登录
 * - 1: 发送验证码
 * - 2: 在线
 * - 3: 已暂停
 * - 4: 已失效
 * 使用 Arco Design 标准颜色以兼容主题切换
 * @param status 状态值
 * @returns 状态颜色
 */
const statusColorMapper = (status: number): string => {
  switch (status) {
    case 0:
      return 'orange'; // 待登录 - 橙色（等待状态）
    case 1:
      return 'blue'; // 发送验证码 - 蓝色（进行中状态）
    case 2:
      return 'green'; // 在线 - 绿色（正常状态）
    case 3:
      return 'orange'; // 已暂停 - 橙色（警告状态）
    case 4:
      return 'red'; // 已失效 - 红色（危险状态）
    default:
      return 'gray'; // 未知状态 - 灰色（中性状态）
  }
};

/**
 * 状态文本映射器（作为备用）
 * 基于后端Go定义的状态
 * @param status 状态值
 * @returns 状态文本
 */
const statusMapper = (status: number): { text: string } => {
  switch (status) {
    case 0:
      return { text: '待登录' }; // 需要登录验证
    case 1:
      return { text: '发送验证码' }; // 正在发送验证码
    case 2:
      return { text: '在线' }; // 账户在线，可用
    case 3:
      return { text: '已暂停' }; // 账户被暂停使用
    case 4:
      return { text: '已失效' }; // 账户已失效
    default:
      return { text: '未知状态' };
  }
};

/**
 * 导出功能
 */
const download = () => {
  // TODO: 实现导出功能
  Notification.info({
    content: '导出功能开发中',
    closable: true
  });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchAccountData();
});
</script>

<style scoped>
.container {
  padding: 0 20px 20px;
}

.general-card {
  min-height: calc(100vh - 170px);
}
</style>
