<template>
  <div class="p-2">
    <!-- 搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="股票代码" prop="stockCode">
              <el-input v-model="queryParams.stockCode" placeholder="请输入股票代码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="股票名称" prop="stockName">
              <el-input v-model="queryParams.stockName" placeholder="请输入股票名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="当前有效" :value="2" />
                <el-option label="历史有效" :value="1" />
                <el-option label="已移除" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="入池时间" prop="dateRange">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb-2">
          <el-col :span="1.5">
            <el-button v-has-permi="['stock:pool:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">移除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-has-permi="['stock:pool:export']" type="warning" plain icon="Download" @click="handleExport" :loading="exporting">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Refresh" @click="refreshQuotes" :loading="refreshing">刷新行情</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="poolList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="股票代码" align="center" prop="stockCode" />
        <el-table-column label="股票名称" align="center" prop="stockName" />
        <el-table-column label="当前价" align="center" prop="currentPrice">
          <template #default="scope">
            <span :class="getPriceClass(scope.row)">{{ formatPrice(scope.row.currentPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="涨跌幅" align="center" prop="changePercent">
          <template #default="scope">
            <span :class="getChangeClass(scope.row.changePercent)">{{ formatPercent(scope.row.changePercent) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入池价" align="center" prop="addPrice">
          <template #default="scope">{{ formatPrice(scope.row.addPrice) }}</template>
        </el-table-column>
        <el-table-column label="入池收益" align="center" prop="profitPercent">
          <template #default="scope">
            <span :class="getChangeClass(scope.row.profitPercent)">{{ formatPercent(scope.row.profitPercent) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="换手率" align="center" prop="turnoverRate">
          <template #default="scope">{{ formatPercent(scope.row.turnoverRate) }}</template>
        </el-table-column>
        <el-table-column label="成交额(亿)" align="center" prop="tradeAmount">
          <template #default="scope">{{ formatAmount(scope.row.tradeAmount) }}</template>
        </el-table-column>
        <el-table-column label="入池日期" align="center" prop="addDate" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 2" type="success">当前有效</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="warning">历史有效</el-tag>
            <el-tag v-else type="info">已移除</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-tooltip content="修改状态" placement="top">
              <el-button v-has-permi="['stock:pool:edit']" link type="primary" icon="Edit" @click="handleUpdateStatus(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="移除" placement="top">
              <el-button v-has-permi="['stock:pool:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 修改状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="修改状态" width="400px" append-to-body>
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="股票名称">
          <el-input v-model="statusForm.stockName" disabled />
        </el-form-item>
        <el-form-item label="股票代码">
          <el-input v-model="statusForm.stockCode" disabled />
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag v-if="statusForm.currentStatus === 2" type="success">当前有效</el-tag>
          <el-tag v-else-if="statusForm.currentStatus === 1" type="warning">历史有效</el-tag>
          <el-tag v-else type="info">已移除</el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.newStatus" placeholder="请选择状态">
            <el-option label="当前有效" :value="2" />
            <el-option label="历史有效" :value="1" />
            <el-option label="已移除" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStatusChange">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ShortPool" lang="ts">
import { ref, onMounted, onUnmounted, onActivated, onDeactivated, getCurrentInstance } from 'vue';
import { listStockPool, removeFromPool, updatePoolStatus } from '@/api/stock/pool';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const poolList = ref<any[]>([]);
const loading = ref(true);
const refreshing = ref(false);
const exporting = ref(false);
const showSearch = ref(true);
const ids = ref<number[]>([]);
const multiple = ref(true);
const total = ref(0);

// 修改状态对话框
const statusDialogVisible = ref(false);
const statusForm = ref({
  id: null as number | null,
  stockName: '',
  stockCode: '',
  currentStatus: null as number | null,
  newStatus: null as number | null
});

let refreshTimer: ReturnType<typeof setTimeout> | null = null;
let isPageVisible = true; // 页面是否可见

const queryFormRef = ref<ElFormInstance>();
const dateRange = ref<string[]>([]);

const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  stockCode: '',
  stockName: '',
  poolType: 1,  // 固定为超短池
  status: undefined as number | undefined,
  startDate: undefined as string | undefined,
  endDate: undefined as string | undefined
});


/** 获取随机刷新间隔 (2000-3000ms) */
const getRandomInterval = () => 2000 + Math.random() * 1000;

/** 启动自动刷新 */
const startAutoRefresh = () => {
  if (!isPageVisible) return; // 页面不可见时不启动
  stopAutoRefresh();
  refreshTimer = setTimeout(async () => {
    if (!isPageVisible) return; // 再次检查
    await refreshQuotesOnly();
    startAutoRefresh();
  }, getRandomInterval());
};

/** 停止自动刷新 */
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearTimeout(refreshTimer);
    refreshTimer = null;
  }
};

/** 处理页面可见性变化 */
const handleVisibilityChange = () => {
  if (document.hidden) {
    isPageVisible = false;
    stopAutoRefresh();
  } else {
    isPageVisible = true;
    startAutoRefresh();
  }
};

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  stopAutoRefresh();
  try {
    const res = await listStockPool(queryParams.value);
    poolList.value = res.rows || [];
    total.value = res.total || 0;
    startAutoRefresh();
  } catch (error) {
    console.error('获取超短池列表失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 局部刷新行情数据 */
const refreshQuotesOnly = async () => {
  if (poolList.value.length === 0) return;
  try {
    const res = await listStockPool(queryParams.value);
    const newData = res.rows || [];
    poolList.value.forEach((item) => {
      const newItem = newData.find((n: any) => n.id === item.id);
      if (newItem) {
        item.currentPrice = newItem.currentPrice;
        item.changePercent = newItem.changePercent;
        item.turnoverRate = newItem.turnoverRate;
        item.tradeAmount = newItem.tradeAmount;
        item.profitPercent = newItem.profitPercent;
      }
    });
  } catch (error) {
    console.error('刷新行情失败:', error);
  }
};

/** 手动刷新行情 */
const refreshQuotes = async () => {
  refreshing.value = true;
  stopAutoRefresh();
  try {
    await refreshQuotesOnly();
    startAutoRefresh();
  } finally {
    refreshing.value = false;
  }
};

/** 导出 */
const handleExport = async () => {
  exporting.value = true;
  try {
    proxy?.download('stock/pool/export', {
      stockCode: queryParams.value.stockCode,
      stockName: queryParams.value.stockName,
      poolType: 1,
      status: queryParams.value.status
    }, `short_pool_${new Date().getTime()}.xlsx`);
  } finally {
    setTimeout(() => { exporting.value = false; }, 1000);
  }
};

/** 搜索按钮 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startDate = dateRange.value[0];
    queryParams.value.endDate = dateRange.value[1];
  } else {
    queryParams.value.startDate = undefined;
    queryParams.value.endDate = undefined;
  }
  getList();
};

/** 重置按钮 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRange.value = [];
  queryParams.value.status = 1;
  queryParams.value.startDate = undefined;
  queryParams.value.endDate = undefined;
  handleQuery();
};

/** 多选框选中 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id);
  multiple.value = !selection.length;
};

/** 删除按钮 */
const handleDelete = async (row?: any) => {
  const poolIds = row?.id ? [row.id] : ids.value;
  await proxy?.$modal.confirm(`是否确认移除选中的股票？`);
  await removeFromPool(poolIds);
  proxy?.$modal.msgSuccess('移除成功');
  await getList();
};

/** 修改状态按钮 */
const handleUpdateStatus = (row: any) => {
  statusForm.value = {
    id: row.id,
    stockName: row.stockName,
    stockCode: row.stockCode,
    currentStatus: row.status,
    newStatus: row.status
  };
  statusDialogVisible.value = true;
};

/** 提交状态修改 */
const submitStatusChange = async () => {
  if (statusForm.value.newStatus === statusForm.value.currentStatus) {
    proxy?.$modal.msgWarning('状态未改变');
    return;
  }
  try {
    await updatePoolStatus(statusForm.value.id!, statusForm.value.newStatus!);
    proxy?.$modal.msgSuccess('状态修改成功');
    statusDialogVisible.value = false;
    await getList();
  } catch (error) {
    console.error('修改状态失败:', error);
  }
};

/** 格式化价格 */
const formatPrice = (val: any) => (val != null ? Number(val).toFixed(2) : '-');

/** 格式化百分比 */
const formatPercent = (val: any) => (val != null ? `${Number(val) >= 0 ? '+' : ''}${Number(val).toFixed(2)}%` : '-');

/** 格式化成交额 */
const formatAmount = (val: any) => (val != null && val !== 0 ? Number(val).toFixed(2) : '-');

/** 获取价格样式 */
const getPriceClass = (row: any) => {
  if (row.changePercent == null) return '';
  return row.changePercent > 0 ? 'text-red-500' : row.changePercent < 0 ? 'text-green-500' : '';
};

/** 获取涨跌样式 */
const getChangeClass = (val: any) => {
  if (val == null) return '';
  return val > 0 ? 'text-red-500 font-bold' : val < 0 ? 'text-green-500 font-bold' : '';
};

onMounted(() => {
  document.addEventListener('visibilitychange', handleVisibilityChange);
  getList();
});

onActivated(() => {
  isPageVisible = true;
  getList();
});

onDeactivated(() => {
  isPageVisible = false;
  stopAutoRefresh();
});

onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
  stopAutoRefresh();
});
</script>

<style scoped>
.text-red-500 { color: #ef4444; }
.text-green-500 { color: #22c55e; }
.font-bold { font-weight: bold; }
</style>
