package cn.reghao.tnb.sb.controller;

import cn.reghao.jutil.jdk.web.result.WebResult;
import cn.reghao.tnb.sb.model.AccountProofModel;
import com.itextpdf.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author reghao
 * @date 2025-05-28 15:40:56
 */
@Slf4j
@Controller
public class IndexController {
    private final Configuration configuration;
    private Random r = new Random();

    public IndexController(Configuration configuration) {
        this.configuration = configuration;
    }

    @GetMapping("/pdf/preview")
    public ResponseEntity<byte[]> pdfPreview(ModelMap model) {
        AccountProofModel accountProofModel = new AccountProofModel.Builder()
                .generationDate(LocalDate.now().toString())
                .memberName("Nick Liu")
                .memberAddress("Nanshan District, Shenzhen city, Guangdong Province")
                .accountNo("88888888888888")
                .bankName("ICBC")
                .bankSwiftCode("ABCDEFG")
                .bankAddress("Shenzhen city of Guangdong Province")
                .countryName("China")
                .build();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            String templateName = "/pdfview.ftl";
            // 不建议直接创建Template实例，开销比较大，可以直接通过Configuration实例获取，有缓存机制
            Template template = configuration.getTemplate(templateName);
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, accountProofModel);

            ITextRenderer renderer = new ITextRenderer();
            // 如果内容有中文则需要添加支持中文的字体
            renderer.getFontResolver().addFont("/fonts/calibri.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.setDocumentFromString(content);
            renderer.layout();
            renderer.createPDF(baos);
            renderer.finishPDF();
        } catch (Exception e) {
            log.error("fail to generate pdf: {} {}", e.getMessage(), e);
            return ResponseEntity.internalServerError().body(null);
        }

        HttpHeaders respHeaders = new HttpHeaders();
        respHeaders.setContentType(MediaType.APPLICATION_PDF);
        respHeaders.setContentDisposition(ContentDisposition.inline().filename("accountProof.pdf", StandardCharsets.UTF_8).build());
        return new ResponseEntity<>(baos.toByteArray(), respHeaders, HttpStatus.OK);
    }

    @PostMapping(value = "/file/upload", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String uploadFile(MultipartFile file) {
        String url = "fileService.putFile(file)";
        Map<String, String> map = new HashMap<>();
        map.put("name", file.getOriginalFilename());
        map.put("url", url);
        return WebResult.success(map);
    }

    @GetMapping(value = "/index/get", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String getIndex() throws InterruptedException {
        int value = 40;
        System.out.printf("Thread-%s sleep %ss\n", Thread.currentThread().getName(), value);
        Thread.sleep(value*1000L);

        double v = r.nextGaussian() * Math.sqrt(10) + 53;
        Map<String, Object> map = new HashMap<>();
        map.put("value", v);
        map.put("timestamp", System.currentTimeMillis());
        return WebResult.success(map);
    }
}
