<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="market">
              <el-select v-model="queryParams.market" placeholder="请选择市场" clearable>
                <el-option label="上海" value="SH" />
                <el-option label="深圳" value="SZ" />
              </el-select>
            </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">
          <el-col :span="1.5">
            <el-button v-has-permi="['stock:info:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-has-permi="['stock:info:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-has-permi="['stock:info: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:info: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="stockList" @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="market">
          <template #default="scope">
            <el-tag :type="scope.row.market === 'SH' ? 'danger' : 'success'" size="small">
              {{ scope.row.market === 'SH' ? '沪' : '深' }}
            </el-tag>
          </template>
        </el-table-column>
        <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="turnoverRate">
          <template #default="scope">{{ formatPercent(scope.row.turnoverRate) }}</template>
        </el-table-column>
        <el-table-column label="成交额(亿)" align="center" prop="tradeAmount">
          <template #default="scope">{{ scope.row.tradeAmount || '-' }}</template>
        </el-table-column>
        <el-table-column label="池状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.inShortPool" type="danger" size="small" class="mr-1">超短池</el-tag>
            <el-tag v-if="scope.row.inStrongPool" type="warning" size="small">强势池</el-tag>
            <span v-if="!scope.row.inShortPool && !scope.row.inStrongPool" class="text-gray-400">未入池</span>
          </template>
        </el-table-column>
        <el-table-column label="加入股票池" align="center" width="220">
          <template #default="scope">
            <el-button v-if="!scope.row.inShortPool" v-has-permi="['stock:pool:add']" type="danger" size="small" @click="handleAddToPool(scope.row, 1)">
              加入超短池
            </el-button>
            <el-button v-else v-has-permi="['stock:pool:remove']" type="info" size="small" plain @click="handleRemoveFromPool(scope.row, 1)">
              移出超短池
            </el-button>
            <el-button v-if="!scope.row.inStrongPool" v-has-permi="['stock:pool:add']" type="warning" size="small" @click="handleAddToPool(scope.row, 2)">
              加入强势池
            </el-button>
            <el-button v-else v-has-permi="['stock:pool:remove']" type="info" size="small" plain @click="handleRemoveFromPool(scope.row, 2)">
              移出强势池
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-has-permi="['stock:info:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-has-permi="['stock:info: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="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="stockFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="股票代码" prop="stockCode">
          <el-input v-model="form.stockCode" placeholder="请输入股票代码" maxlength="10" />
        </el-form-item>
        <el-form-item label="股票名称" prop="stockName">
          <el-input v-model="form.stockName" placeholder="请输入股票名称" maxlength="64" />
        </el-form-item>
        <el-form-item label="市场" prop="market">
          <el-select v-model="form.market" placeholder="请选择市场">
            <el-option label="上海" value="SH" />
            <el-option label="深圳" value="SZ" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup name="StockInfo" lang="ts">
import { ref, reactive, onMounted, onUnmounted, onActivated, onDeactivated, getCurrentInstance } from 'vue';
import { listStockInfo, getStockInfo, addStockInfo, updateStockInfo, delStockInfo, addToPool, removeFromPool } from '@/api/stock/info';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

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

const queryFormRef = ref<ElFormInstance>();
const stockFormRef = ref<ElFormInstance>();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  stockCode: '',
  stockName: '',
  market: undefined as string | undefined
});

const dialog = reactive({ visible: false, title: '' });
const form = ref<any>({});

const rules: Record<string, any[]> = {
  stockCode: [
    { required: true, message: '股票代码不能为空', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '股票代码必须是6位数字', trigger: 'blur' }
  ],
  stockName: [{ required: true, message: '股票名称不能为空', trigger: 'blur' }],
  market: [{ required: true, message: '市场不能为空', trigger: 'change' }]
};

/** 获取随机刷新间隔 (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 listStockInfo(queryParams.value);
    stockList.value = res.rows || [];
    total.value = res.total || 0;
    startAutoRefresh();
  } catch (error) {
    console.error('获取股票列表失败:', error);
    stockList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 局部刷新行情数据（不显示loading） */
const refreshQuotesOnly = async () => {
  if (stockList.value.length === 0) return;
  try {
    const res = await listStockInfo(queryParams.value);
    const newData = res.rows || [];
    // 局部更新行情字段
    stockList.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.yesterdayClose = newItem.yesterdayClose;
        item.inShortPool = newItem.inShortPool;
        item.inStrongPool = newItem.inStrongPool;
        item.poolStatus = newItem.poolStatus;
      }
    });
  } 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/info/export', {
      stockCode: queryParams.value.stockCode,
      stockName: queryParams.value.stockName,
      market: queryParams.value.market
    }, `stock_info_${new Date().getTime()}.xlsx`);
  } finally {
    setTimeout(() => { exporting.value = false; }, 1000);
  }
};

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

/** 格式化百分比 */
const formatPercent = (val: any) => (val != null ? `${Number(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' : '';
};

/** 加入股票池 */
const handleAddToPool = async (row: any, poolType: number) => {
  const poolName = poolType === 1 ? '超短池' : '强势池';
  try {
    await addToPool({ stockCode: row.stockCode, stockName: row.stockName, poolType: poolType });
    proxy?.$modal.msgSuccess(`已加入${poolName}`);
    await refreshQuotesOnly();
  } catch (error) {
    console.error('加入股票池失败:', error);
  }
};

/** 从股票池移除 */
const handleRemoveFromPool = async (row: any, poolType: number) => {
  const poolName = poolType === 1 ? '超短池' : '强势池';
  await proxy?.$modal.confirm(`确认将 ${row.stockName} 从${poolName}移除？`);
  try {
    await removeFromPool(row.stockCode, poolType);
    proxy?.$modal.msgSuccess(`已从${poolName}移除`);
    await refreshQuotesOnly();
  } catch (error) {
    console.error('移除失败:', error);
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.market = undefined;
  handleQuery();
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加股票信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getStockInfo(id);
  form.value = res.data;
  dialog.visible = true;
  dialog.title = '修改股票信息';
};

/** 提交按钮 */
const submitForm = () => {
  stockFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        await updateStockInfo(form.value);
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addStockInfo(form.value);
        proxy?.$modal.msgSuccess('新增成功');
      }
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const stockIds = row?.id ? [row.id] : ids.value;
  await proxy?.$modal.confirm(`是否确认删除股票编号为"${stockIds}"的数据项？`);
  await delStockInfo(stockIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = { id: undefined, stockCode: '', stockName: '', market: undefined };
  stockFormRef.value?.resetFields();
};

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

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

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

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

<style scoped>
.mr-1 { margin-right: 4px; }
.text-gray-400 { color: #9ca3af; }
.text-red-500 { color: #ef4444; }
.text-green-500 { color: #22c55e; }
.font-bold { font-weight: bold; }
</style>
