<template>
  <div class="container">
    <Breadcrumb :items="['充值账户管理', 'Token管理']" />
    <a-card class="general-card" title="Token管理">
      <!-- 搜索表单区域 -->
      <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="tokenName" label="Token名称">
                  <a-input
                    v-model="formModel.tokenName"
                    placeholder="请输入Token名称"
                  />
                </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-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 type="primary" @click="showAddModal()">
            <template #icon>
              <icon-plus />
            </template>
            新增Token
          </a-button>
          <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: 1800 }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 状态列模板 -->
        <template #status="{ record }">
          <a-tag size="small" :color="statusMapper(record.status).color">
            {{ statusMapper(record.status).text }}
          </a-tag>
        </template>

        <!-- 操作列模板 -->
        <template #operations="{ record }">
          <a-space size="small">
            <a-tooltip content="查看绑卡记录">
              <a-button
                size="small"
                status="normal"
                @click="showBindingRecords(record)"
              >
                <template #icon>
                  <icon-list />
                </template>
              </a-button>
            </a-tooltip>
            <a-popconfirm
              content="确认删除此Token吗？"
              @ok="deleteToken(record.id)"
            >
              <a-tooltip content="删除">
                <a-button size="small" status="danger">
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </a-tooltip>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增Token弹窗 -->
    <add-edit-modal
      v-model:visible="state.addEditModalVisible"
      @success="handleModalSuccess"
    />

    <!-- 绑卡记录弹窗 -->
    <binding-records-modal
      v-model:visible="state.bindingRecordsVisible"
      :token-id="state.currentTokenId"
      :token-name="state.currentTokenName"
    />
  </div>
</template>

<script lang="ts" setup>
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { onMounted, reactive, ref } from 'vue';
import { Notification, TableColumnData } from '@arco-design/web-vue';
import AddEditModal from './components/add-edit-modal.vue';
import BindingRecordsModal from './components/binding-records-modal.vue';
import {
  ApiTokenListGetPageSizeEnum,
  KamiApiCamelOilV1TokenInfo
} from '@/api/generated/index.ts';
import { jdV2TokenClient } from '@/api/index.ts';

const basePagination: Pagination = {
  current: 1,
  pageSize: 50
};
const pagination = reactive({
  ...basePagination
});

const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    render: ({ rowIndex }) => {
      return rowIndex + 1 + (pagination.current - 1) * pagination.pageSize;
    }
  },
  {
    title: 'Token名称',
    dataIndex: 'tokenName',
    width: 150
  },
  {
    title: 'Token值',
    dataIndex: 'tokenValue',
    width: 300,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '绑定手机号',
    dataIndex: 'phone',
    width: 130,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '绑定数量',
    dataIndex: 'bindCount',
    width: 100
  },
  {
    title: '累计绑定金额',
    dataIndex: 'totalBindAmount',
    width: 120,
    render: ({ record }) => {
      if (!record.totalBindAmount) return '-';
      return `¥${Number(record.totalBindAmount).toFixed(2)}`;
    }
  },
  {
    title: '总充值金额',
    dataIndex: 'totalRechargeAmount',
    width: 120,
    render: ({ record }) => {
      if (!record.totalRechargeAmount) return '-';
      return `¥${Number(record.totalRechargeAmount).toFixed(2)}`;
    }
  },
  {
    title: '充值限制',
    dataIndex: 'rechargeLimitAmount',
    width: 110,
    render: ({ record }) => {
      if (!record.rechargeLimitAmount) return '-';
      return `¥${Number(record.rechargeLimitAmount).toFixed(2)}`;
    }
  },
  {
    title: '次数限制',
    dataIndex: 'rechargeLimitCount',
    width: 100,
    render: ({ record }) => {
      return record.rechargeLimitCount || '-';
    }
  },
  {
    title: '最后绑定时间',
    dataIndex: 'lastBindAt',
    width: 180,
    ellipsis: true,
    tooltip: true,
    render: ({ record }) => {
      return formatDateTime(record.lastBindAt);
    }
  },
  {
    title: '最后使用时间',
    dataIndex: 'lastUsedAt',
    width: 180,
    ellipsis: true,
    tooltip: true,
    render: ({ record }) => {
      return formatDateTime(record.lastUsedAt);
    }
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  {
    title: '备注',
    dataIndex: 'remark',
    width: 150,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180,
    render: ({ record }) => {
      return formatDateTime(record.createdAt);
    }
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    fixed: 'right',
    width: 150
  }
];

const generateFormModel = () => {
  return {
    tokenName: '',
    status: undefined as number | undefined
  };
};

const { loading, setLoading } = useLoading(true);
const renderData = ref<KamiApiCamelOilV1TokenInfo[]>([]);
const formModel = ref(generateFormModel());

const state = reactive({
  addEditModalVisible: false,
  bindingRecordsVisible: false,
  currentTokenId: 0,
  currentTokenName: ''
});

const fetchData = async (params: any = { current: 1, pageSize: 50 }) => {
  setLoading(true);
  try {
    const { data } = await jdV2TokenClient.apiTokenListGet({
      current: params.current,
      pageSize: params.pageSize as unknown as ApiTokenListGetPageSizeEnum,
      tokenName: params.tokenName,
      status: params.status
    });

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

const onPageChange = (current: number) => {
  fetchData({ ...pagination, current });
};

const onPageSizeChange = (pageSize: number) => {
  fetchData({ ...pagination, pageSize });
};

const search = () => {
  fetchData({
    ...basePagination,
    ...formModel.value
  });
};

const reset = () => {
  formModel.value = generateFormModel();
  search();
};

const showAddModal = () => {
  state.addEditModalVisible = true;
};

const showBindingRecords = (record: KamiApiCamelOilV1TokenInfo) => {
  state.currentTokenId = record.id;
  state.currentTokenName = record.tokenName;
  state.bindingRecordsVisible = true;
};

const deleteToken = async (tokenId: number) => {
  try {
    await jdV2TokenClient.apiTokenDeletePost({
      kamiApiCamelOilV1DeleteTokenReq: {
        tokenId
      }
    });

    Notification.success({
      content: '删除Token成功',
      closable: true
    });

    fetchData({ ...pagination });
  } catch (err) {
    console.error('删除Token失败:', err);
    Notification.error({
      content: '删除Token失败',
      closable: true
    });
  }
};

const handleModalSuccess = () => {
  fetchData({ ...pagination });
};

const statusMapper = (status: number): { text: string; color: string } => {
  switch (status) {
    case 0:
      return { text: '禁用', color: 'red' };
    case 1:
      return { text: '启用', color: 'green' };
    default:
      return { text: '未知', color: 'gray' };
  }
};

const formatDateTime = (dateTime: string | undefined): string => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

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

onMounted(() => {
  fetchData();
});
</script>

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

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