package com.lanyuanxiaoyao.leopard.strategy;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyuanxiaoyao.leopard.core.entity.QDaily;
import com.lanyuanxiaoyao.leopard.core.repository.DailyRepository;
import com.lanyuanxiaoyao.leopard.core.service.AssessmentService;
import com.lanyuanxiaoyao.leopard.core.service.TuShareService;
import com.lanyuanxiaoyao.leopard.core.service.selector.PyramidStockSelector;
import jakarta.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@SpringBootApplication(scanBasePackages = "com.lanyuanxiaoyao.leopard")
@EnableJpaAuditing
public class StrategyApplication {
  private static final ObjectMapper mapper = new ObjectMapper();
  @Resource
  private PyramidStockSelector pyramidStockSelector;
  @Resource
  private AssessmentService assessmentService;
  @Resource
  private TuShareService tuShareService;
  @Resource
  private DailyRepository dailyRepository;

  public static void main(String[] args) {
    SpringApplication.run(StrategyApplication.class, args);
  }

  private static void render(Map<String, Object> data) throws IOException {
    Files.writeString(
      Path.of("result.html"),
      StrUtil.format(
        // language=HTML
        """
          <html lang='zh'>
          <head>
            <meta charset='utf-8'/>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
            <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
            <title>Strategy</title>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/amis/6.13.0/antd.min.css"/>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/amis/6.13.0/helper.min.css"/>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/amis/6.13.0/iconfont.min.css"/>
            <style>
              html, body, #root {
                position: relative;
                width: 100%;
                height: 100%;
                margin: 0;
                padding: 0;
              }
            </style>
          </head>
          <body>
          <div id='root'/>
          </body>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/amis/6.13.0/sdk.min.js"></script>
          <script type='text/javascript'>
            (function () {
              const amis = amisRequire('amis/embed')
              const amisJson = {
                type: 'page',
                title: 'Strategy',
                data: {},
                body: [
                  /*{
                    type: 'table2',
                    source: '${items}',
                    columns: [
                      {
                        name: 'date',
                        label: 'Date',
                        width: 100,
                      },
                      {
                        name: 'code',
                        label: 'Code',
                        width: 100,
                      },
                      {
                        name: 'name',
                        label: 'Name',
                        width: 100,
                      },
                      {
                        name: 'sma5',
                        label: 'SMA-5',
                        width: 100,
                      },
                      {
                        name: 'sma10',
                        label: 'SMA-10',
                        width: 100,
                      },
                    ],
                  },*/
                  {
                    type: 'chart',
                    height: 800,
                    config: {
                      backgroundColor: '#fff',
                      animation: true,
                      animationDuration: 1000,
                      tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                          type: 'cross',
                        },
                        backgroundColor: 'rgba(0, 0, 0, 0.7)',
                        borderColor: '#333',
                        borderWidth: 1,
                        textStyle: {
                          color: '#fff',
                          fontSize: 12,
                        },
                        padding: 12,
                        formatter: function (params) {
                          const param = params[0]
                          const open = param.data[1].toFixed(2)
                          const close = param.data[2].toFixed(2)
                          const lowest = param.data[3].toFixed(2)
                          const highest = param.data[4].toFixed(2)
          
                          return `<div class="text-center font-bold mb-2">${param.name}</div>
                                  <div class="text-center">
                                    <span>开盘:</span>
                                    <span class="font-bold ml-4">${open}</span>
                                  </div>
                                  <div class="text-center">
                                    <span>收盘:</span>
                                    <span class="font-bold ml-4">${close}</span>
                                  </div>
                                  <div class="text-center">
                                    <span>最低:</span>
                                    <span class="font-bold ml-4">${lowest}</span>
                                  </div>
                                  <div class="text-center">
                                    <span>最高:</span>
                                    <span class="font-bold ml-4">${highest}</span>
                                  </div>`
                        },
                      },
                      grid: {
                        left: '2%',
                        right: '2%',
                        top: '5%',
                        bottom: '12%',
                        containLabel: true,
                      },
                      xAxis: {
                        data: '${xList || []}',
                        axisLine: {
                          lineStyle: {
                            color: '#e0e0e0',
                          },
                        },
                        axisLabel: {
                          color: '#666',
                          fontWeight: 'bold',
                        },
                        splitLine: {
                          show: false,
                        },
                        axisTick: {
                          show: false,
                        },
                      },
                      yAxis: {
                        scale: true,
                        axisLine: {
                          lineStyle: {
                            color: '#e0e0e0',
                          },
                        },
                        axisLabel: {
                          color: '#666',
                          fontWeight: 'bold',
                          formatter: function (value) {
                            return value.toFixed(2)
                          },
                        },
                        splitLine: {
                          lineStyle: {
                            type: 'dashed',
                            color: '#f0f0f0',
                          },
                        },
                        axisTick: {
                          show: false,
                        },
                      },
                      dataZoom: [
                        {
                          type: 'inside',
                          start: 0,
                          end: 100,
                        },
                        {
                          show: true,
                          type: 'slider',
                          top: '90%',
                          start: 0,
                          end: 100,
                        },
                      ],
                      series: [
                        {
                          type: 'candlestick',
                          data: '${yList || []}',
                          itemStyle: {
                            color: '#eb5454',
                            color0: '#4aaa93',
                            borderColor: '#eb5454',
                            borderColor0: '#4aaa93',
                            borderWidth: 1,
                          },
                        },
                        {
                          type: 'line',
                          data: '${sma10 || []}',
                          smooth: true,
                          lineStyle: {
                            color: '#dcb38a',
                          },
                          symbol: 'none',
                        },
                        {
                          type: 'line',
                          data: '${sma60 || []}',
                          smooth: true,
                          lineStyle: {
                            color: '#6ce3c6',
                          },
                          symbol: 'none',
                        },
                        {
                          type: 'line',
                          data: '${sma120 || []}',
                          smooth: true,
                          lineStyle: {
                            color: '#6cd5e3',
                          },
                          symbol: 'none',
                        },
                      ],
                    },
                  },
                ],
              }
              amis.embed('#root', amisJson, {}, {theme: 'antd'})
            })()
          </script>
          </html>
          """,
        mapper.writeValueAsString(data)
      )
    );
  }

  @Transactional(readOnly = true)
  @EventListener(ApplicationReadyEvent.class)
  public void test() {
    var dailies = dailyRepository.findAll(QDaily.daily.factor.isNull(), QDaily.daily.tradeDate.asc());
    for (var daily : dailies) {
      log.info("{} {} {}", daily.getStock().getCode(), daily.getStock().getName(), daily.getTradeDate());
      // var response = tuShareService.factorList(daily.getTradeDate(), daily.getStock().getCode());
      // var factor = response.data().items().getFirst().get(2);
    }
  }
}
