<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="poolType">
              <el-select v-model="queryParams.poolType" placeholder="请选择池类型" clearable>
                <el-option label="超短池" :value="1" />
                <el-option label="强势池" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <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:info:add']" type="primary" plain icon="Plus" @click="handleAddStock">添加股票</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Refresh" @click="refreshQuotes" :loading="refreshing">刷新行情</el-button>
          </el-col>
          <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>
          <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="poolTypeName">
          <template #default="scope">
            <el-tag :type="scope.row.poolType === 1 ? 'danger' : 'warning'">{{ scope.row.poolTypeName }}</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="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">{{ 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 :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '有效' : '已移除' }}</el-tag>
          </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: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>

    <!-- 添加股票到stock_info对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="股票代码" prop="stockCode">
          <el-input v-model="form.stockCode" placeholder="请输入6位股票代码" maxlength="6" />
        </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="StockPool" lang="ts">
import { ref, reactive, onMounted, onUnmounted, onActivated, getCurrentInstance } from 'vue';
import { listStockPool, removeFromPool } from '@/api/stock/pool';
import { addStockInfo } from '@/api/stock/info';

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);

let refreshTimer: ReturnType<typeof setTimeout> | null = null;

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

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

const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  stockCode: '',
  stockName: '',
  poolType: undefined as number | undefined,
  status: 1 as number | undefined,
  startDate: undefined as string | undefined,
  endDate: undefined as string | undefined
});

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

const rules = {
  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 = () => {
  stopAutoRefresh();
  refreshTimer = setTimeout(async () => {
    await refreshQuotesOnly();
    startAutoRefresh();
  }, getRandomInterval());
};

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

/** 查询列表（首次加载或翻页） */
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;
  }
};

/** 局部刷新行情数据（不显示loading） */
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.changeAmount = newItem.changeAmount;
        item.turnoverRate = newItem.turnoverRate;
        item.tradeAmount = newItem.tradeAmount;
        item.yesterdayClose = newItem.yesterdayClose;
        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: queryParams.value.poolType,
      status: queryParams.value.status
    }, `stock_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.poolType = undefined;
  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;
};

/** 添加股票按钮（添加到stock_info表） */
const handleAddStock = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加股票信息';
};

/** 提交表单（添加股票到stock_info） */
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await addStockInfo(form.value);
      proxy?.$modal.msgSuccess('添加成功');
      dialog.visible = false;
    }
  });
};

/** 删除按钮 */
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 cancel = () => {
  dialog.visible = false;
  reset();
};

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

/** 格式化价格 */
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' : '';
};

onMounted(() => {
  getList();
});

onActivated(() => {
  // 页面被激活时（从其他页面切换回来）刷新数据
  getList();
});

onUnmounted(() => {
  stopAutoRefresh();
});
</script>

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