<template>
  <a-modal
    v-model:visible="modalVisible"
    title="账号变更记录"
    width="1000px"
    :footer="false"
  >
    <a-spin :loading="loading" style="width: 100%">
      <div class="history-container">
        <!-- 时间筛选 -->
        <a-row style="margin-bottom: 16px">
          <a-col :flex="1">
            <a-form
              :model="filterForm"
              :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="dateRange" label="时间范围">
                    <a-range-picker
                      v-model="filterForm.dateRange"
                      style="width: 100%"
                      :shortcut="dateShortcuts"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item field="changeType" label="变更类型">
                    <a-select
                      v-model="filterForm.changeType"
                      placeholder="请选择变更类型"
                      allow-clear
                      style="width: 100%"
                    >
                      <a-option value="create">创建账号</a-option>
                      <a-option value="login">登录成功</a-option>
                      <a-option value="offline">检测到掉线</a-option>
                      <a-option value="login_fail">登录失败</a-option>
                      <a-option value="pause">订单数达到10，暂停使用</a-option>
                      <a-option value="resume">次日重置，恢复使用</a-option>
                      <a-option value="invalidate">
                        单日下单不足10个，账号失效
                      </a-option>
                      <a-option value="order_bind">绑定订单</a-option>
                      <a-option value="order_complete">订单完成</a-option>
                      <a-option value="update">更新账号信息</a-option>
                      <a-option value="delete">删除账号</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
          <a-col flex="120px" style="text-align: right">
            <a-space>
              <a-button type="primary" @click="searchHistory">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="resetFilter">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>

        <!-- 历史记录表格 -->
        <a-table
          :data="historyData"
          :columns="columns"
          :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            pageSizeOptions: [10, 20, 50],
            showPageSize: true,
            showTotal: true
          }"
          :loading="tableLoading"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #changeType="{ record }">
            <a-tag :color="changeTypeMapper(record.changeType).color">
              {{ changeTypeMapper(record.changeType).text }}
            </a-tag>
          </template>

          <template #beforeStatus="{ record }">
            <a-tag
              v-if="
                record.statusBefore !== undefined &&
                record.statusBefore !== null
              "
              :color="statusColorMapper(record.statusBefore)"
            >
              {{ statusMapper(record.statusBefore).text }}
            </a-tag>
            <span v-else>-</span>
          </template>

          <template #afterStatus="{ record }">
            <a-tag
              v-if="
                record.statusAfter !== undefined && record.statusAfter !== null
              "
              :color="statusColorMapper(record.statusAfter)"
            >
              {{ statusMapper(record.statusAfter).text }}
            </a-tag>
            <span v-else>-</span>
          </template>

          <template #remark="{ record }">
            <a-tooltip v-if="record.remark" :content="record.remark">
              <a-button size="small" type="text">
                <template #icon>
                  <icon-eye />
                </template>
                查看详情
              </a-button>
            </a-tooltip>
            <span v-else>-</span>
          </template>
        </a-table>
      </div>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';
import { Message } from '@arco-design/web-vue';
import { TableColumnData } from '@arco-design/web-vue';
import { Pagination } from '@/types/global';
import { jdV2AccountClient } from '@/api/index.ts';
import type { KamiApiCamelOilV1AccountHistoryItem } from '@/api/generated/models/index.ts';
import type { ApiJdV2AccountHistoryGetPageSizeEnum } from '@/api/generated/apis/jdv2-account-api';

// Props 定义
interface Props {
  visible: boolean;
  accountId: string;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  accountId: ''
});

// Emits 定义
interface Emits {
  (e: 'update:visible', value: boolean): void;
}

const emit = defineEmits<Emits>();

// 响应式数据
const loading = ref(false);
const tableLoading = ref(false);
const historyData = ref<KamiApiCamelOilV1AccountHistoryItem[]>([]);

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

const pagination = reactive({ ...basePagination });

// 筛选表单
const filterForm = reactive({
  dateRange: [] as Date[],
  changeType: undefined as string | undefined
});

// 时间快捷选项
const dateShortcuts = [
  {
    label: '今天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      return [start, end];
    }
  },
  {
    label: '昨天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24);
      end.setTime(end.getTime() - 3600 * 1000 * 24);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    label: '最近7天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    label: '最近30天',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  }
];

// 表格列配置
const columns: TableColumnData[] = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    render: ({ rowIndex }) => {
      return rowIndex + 1 + (pagination.current - 1) * pagination.pageSize;
    }
  },
  {
    title: '变更类型',
    dataIndex: 'changeType',
    slotName: 'changeType',
    width: 180
  },
  {
    title: '变更前状态',
    dataIndex: 'statusBefore',
    slotName: 'beforeStatus',
    width: 100
  },
  {
    title: '变更后状态',
    dataIndex: 'statusAfter',
    slotName: 'afterStatus',
    width: 100
  },
  {
    title: '备注说明',
    dataIndex: 'remark',
    width: 200,
    ellipsis: true,
    tooltip: true
  },
  {
    title: '失败次数',
    dataIndex: 'failureCount',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180
  }
];

// 计算属性
const modalVisible = computed({
  get: () => props.visible,
  set: value => emit('update:visible', value)
});

/**
 * 获取历史记录数据
 * @param params 查询参数
 */
const fetchHistoryData = async (
  params: {
    current: number;
    pageSize: ApiJdV2AccountHistoryGetPageSizeEnum;
  } = { current: 1, pageSize: 20 }
) => {
  if (!props.accountId) return;

  tableLoading.value = true;
  try {
    const { data } = await jdV2AccountClient.apiJdV2AccountHistoryGet({
      current: params.current,
      pageSize: params.pageSize as ApiJdV2AccountHistoryGetPageSizeEnum,
      accountId: parseInt(props.accountId)
    });

    historyData.value = data.list || [];
    pagination.current = params.current;
    pagination.pageSize = params.pageSize;
    pagination.total = data.total || 0;
  } catch (error) {
    console.error('获取历史记录失败:', error);
    Message.error('获取历史记录失败');
    historyData.value = [];
  } finally {
    tableLoading.value = false;
  }
};

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

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

/**
 * 搜索历史记录
 */
const searchHistory = () => {
  fetchHistoryData({
    ...basePagination
  });
};

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  filterForm.dateRange = [];
  filterForm.changeType = undefined;
  searchHistory();
};

/**
 * 变更类型映射器
 * 基于后端Go定义的CamelOilAccountChangeType
 * @param changeType 变更类型
 * @returns 变更类型文本和颜色
 */
const changeTypeMapper = (
  changeType: string
): { text: string; color: string } => {
  switch (changeType) {
    case 'create':
      return { text: '创建账号', color: 'green' };
    case 'login':
      return { text: '登录成功', color: 'blue' };
    case 'offline':
      return { text: '检测到掉线', color: 'orange' };
    case 'login_fail':
      return { text: '登录失败', color: 'red' };
    case 'pause':
      return { text: '订单数达到10，暂停使用', color: 'orange' };
    case 'resume':
      return { text: '次日重置，恢复使用', color: 'green' };
    case 'invalidate':
      return { text: '单日下单不足10个，账号失效', color: 'red' };
    case 'order_bind':
      return { text: '绑定订单', color: 'blue' };
    case 'order_complete':
      return { text: '订单完成', color: 'green' };
    case 'update':
      return { text: '更新账号信息', color: 'blue' };
    case 'delete':
      return { text: '删除账号', color: 'red' };
    default:
      return { text: '未知变更', color: 'gray' };
  }
};

/**
 * 状态颜色映射器
 * 基于后端Go定义的CamelOilAccountStatus
 * @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定义的CamelOilAccountStatus
 * @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: '未知状态' };
  }
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  visible => {
    if (visible && props.accountId) {
      fetchHistoryData();
    }
  },
  { immediate: true }
);

// 监听账号ID变化
watch(
  () => props.accountId,
  accountId => {
    if (accountId && props.visible) {
      fetchHistoryData();
    }
  }
);
</script>

<style scoped>
.history-container {
  padding: 16px 0;
}

:deep(.arco-modal-body) {
  max-height: 70vh;
  overflow-y: auto;

  /* 确保滚动条样式跟随主题 */
  scrollbar-width: thin;
  scrollbar-color: var(--color-border-3) transparent;
}

:deep(.arco-modal-body::-webkit-scrollbar) {
  width: 6px;
}

:deep(.arco-modal-body::-webkit-scrollbar-thumb) {
  background-color: var(--color-border-3);
  border-radius: 3px;
}

:deep(.arco-modal-body::-webkit-scrollbar-track) {
  background-color: transparent;
}
</style>
