package jnpf.culture.controller;

import jnpf.base.ActionResult;
import jnpf.culture.service.CultureClockInService;
import jnpf.exception.HandleException;
import jnpf.model.culture.vo.Base64ImageVo;
import jnpf.model.culture.vo.CultureClockInVo;
import jnpf.model.culture.vo.RecordListVo;
import jnpf.model.culture.vo.YearDataVo;
import jnpf.util.UserProvider;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Base64;

/**
 * 文化打卡
 *
 * @author yanwenfu
 * @create 2025-12-23
 */
@RestController
@RequestMapping(value = "/culture/clock-in")
public class CultureClockInController {

    @Resource
    private CultureClockInService cultureClockInService;

    @Value("${config.requestUrl}")
    private String requestUrl;

    /**
     * 打卡分享 - 获取随机图片
     * @param lastCombo 上次组合
     * @param response HttpServletResponse
     */
    @GetMapping(value = "/random-preview")
    public void getRandomPicPreview(@RequestParam(value = "lastCombo", required = false) String lastCombo, HttpServletRequest request, HttpServletResponse response) throws Exception {

        MutablePair<String, BufferedImage> pair = cultureClockInService.getRandomPicPreview(lastCombo, requestUrl);
        if (pair == null || pair.getRight() == null) {
            response.sendError(HttpServletResponse.SC_NO_CONTENT);
            return;
        }
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("X-ClockIn-Combo", pair.getLeft());
        try (OutputStream os = response.getOutputStream()) {
            ImageIO.write(pair.getRight(), "png", os);
            os.flush();
        }
    }

    /**
     * 打卡分享 - 获取随机图片[base64]
     * @param lastCombo 上次组合
     * @param response HttpServletResponse
     */
    @GetMapping(value = "/random-preview/base64")
    public ActionResult<Base64ImageVo> getRandomPicPreviewBase64(@RequestParam(value = "lastCombo", required = false) String lastCombo, HttpServletRequest request, HttpServletResponse response) throws Exception {

        MutablePair<String, BufferedImage> pair = cultureClockInService.getRandomPicPreview(lastCombo, requestUrl);
        if (pair == null || pair.getRight() == null) {
            throw new Exception("获取图片失败，请重试");
        }
        byte[] bytes;
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            ImageIO.write(pair.getRight(), "png", output);
            bytes = output.toByteArray();
        }
        String base64 = Base64.getEncoder().encodeToString(bytes);
        String base64Img = "data:image/png;base64," + base64;
        return ActionResult.success(new Base64ImageVo(pair.getLeft(), base64Img));
    }

    /**
     * 打卡分享 - 打卡
     * @param currentCombo 当前组合
     * @return jnpf.base.ActionResult<jnpf.model.culture.vo.CultureClockInVo>
     */
    @GetMapping(value = "/pic")
    public ActionResult<CultureClockInVo> getCultureClockInPic(@RequestParam(value = "currentCombo") String currentCombo) throws Exception {

        if (UserProvider.getUser().getUserAccount().equals("admin")) {
            throw new HandleException("管理员账号无法进行打卡");
        }
        CultureClockInVo cultureClockIn = cultureClockInService.getCultureClockInPic(currentCombo, requestUrl);
        return ActionResult.success(cultureClockIn);
    }

    /**
     * 打卡动态 - 打卡记录列表
     * @param cursorDate 游标日期(yyyy-MM-dd)[首次不传]
     * @param limitNum 返回有数据的天数
     * @return jnpf.base.ActionResult<jnpf.model.culture.vo.RecordListVo>
     */
    @GetMapping(value = "/dynamic")
    public ActionResult<RecordListVo> getRecordList(@RequestParam(value = "cursorDate", required = false) String cursorDate,
                                                    @RequestParam(value = "limitNum", required = false, defaultValue = "10") Integer limitNum) {

        limitNum = Math.max(10, Math.min(limitNum, 30));
        RecordListVo recordList = cultureClockInService.getRecordList(cursorDate, limitNum);
        return ActionResult.success(recordList);
    }

    /**
     * 打卡日历
     * @param year 年
     * @return jnpf.base.ActionResult<jnpf.model.culture.vo.YearDataVo>
     */
    @GetMapping(value = "/year-data")
    public ActionResult<YearDataVo> getYearData(@RequestParam(value = "year") Integer year) {

        YearDataVo yearData = cultureClockInService.getYearData(year);
        return ActionResult.success(yearData);
    }
}
