package com.yingpai.stock.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.idev.excel.EasyExcel;
import com.yingpai.stock.domain.bo.StockPoolHistoryBo;
import com.yingpai.stock.domain.vo.StockPoolHistoryVo;
import com.yingpai.stock.service.IStockPoolHistoryService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 股票池历史数据管理
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/stock/history")
public class StockPoolHistoryController extends BaseController {

    private final IStockPoolHistoryService stockPoolHistoryService;

    /**
     * 查询历史数据列表
     */
    @SaCheckPermission("stock:history:list")
    @GetMapping("/list")
    public TableDataInfo<StockPoolHistoryVo> list(StockPoolHistoryBo bo, PageQuery pageQuery) {
        return stockPoolHistoryService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取历史数据详细信息
     */
    @SaCheckPermission("stock:history:query")
    @GetMapping("/{id}")
    public R<StockPoolHistoryVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        return R.ok(stockPoolHistoryService.queryById(id));
    }

    /**
     * 新增历史数据
     */
    @SaCheckPermission("stock:history:add")
    @Log(title = "历史数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R<Void> add(@Validated @RequestBody StockPoolHistoryBo bo) {
        return toAjax(stockPoolHistoryService.insertByBo(bo));
    }

    /**
     * 修改历史数据
     */
    @SaCheckPermission("stock:history:edit")
    @Log(title = "历史数据", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public R<Void> edit(@Validated @RequestBody StockPoolHistoryBo bo) {
        return toAjax(stockPoolHistoryService.updateByBo(bo));
    }

    /**
     * 删除历史数据
     */
    @SaCheckPermission("stock:history:remove")
    @Log(title = "历史数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(stockPoolHistoryService.deleteWithValidByIds(List.of(ids)));
    }

    /**
     * 导入历史数据（Excel）
     * @param file Excel文件
     * @param recordDate 管理员指定的记录日期
     * @param updateSupport 是否更新已存在的数据
     */
    @SaCheckPermission("stock:history:import")
    @Log(title = "历史数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public R<Void> importData(
            @RequestParam("file") MultipartFile file,
            @RequestParam("recordDate") String recordDate,
            @RequestParam(value = "updateSupport", defaultValue = "true") boolean updateSupport) throws Exception {
        String message = stockPoolHistoryService.importData(file, recordDate, updateSupport);
        return R.ok(message);
    }

    /**
     * 下载导入模版
     * 格式：第一行为时间信息，第二行为标题，第三行开始为数据
     */
    @SaCheckPermission("stock:history:import")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("股票池历史数据导入模版", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
        // 第一行：时间信息（类似图片中的格式）
        String dateInfo = "历史行情 指标排序 全部A股 周期:日线 日期" + java.time.LocalDate.now().toString() + " 二 指标:强度打分 使用1000个数据 前复权 过滤50天内新股+北证A股+ST股票";
        List<String> headerRow = new ArrayList<>();
        headerRow.add(dateInfo);
        
        // 第二行：标题行
        List<String> titleRow = new ArrayList<>();
        titleRow.add("代码");
        titleRow.add("名称");
        titleRow.add("涨幅%");
        titleRow.add("收盘");
        titleRow.add("总金额");
        titleRow.add("强度评分");
        titleRow.add("流通市值");
        titleRow.add("主升周期");
        titleRow.add("近期换手");
        titleRow.add("近期涨停");
        titleRow.add("当天最高价");
        titleRow.add("当天最低价");
        titleRow.add("当天均价");
        titleRow.add("当天收盘价");
        
        // 第三行：示例数据
        List<String> dataRow = new ArrayList<>();
        dataRow.add("000547");
        dataRow.add("航天发展");
        dataRow.add("0.59");
        dataRow.add("22.13");
        dataRow.add("1.37E+10");
        dataRow.add("14");
        dataRow.add("351.5");
        dataRow.add("8");
        dataRow.add("40.98");
        dataRow.add("3");
        dataRow.add("23");
        dataRow.add("21.48");
        dataRow.add("22.06");
        dataRow.add("22.13");
        
        // 使用EasyExcel写入，不使用注解类
        EasyExcel.write(response.getOutputStream())
            .sheet("导入模版")
            .doWrite(java.util.Arrays.asList(headerRow, titleRow, dataRow));
    }
}
