package com.ycwl.basic.controller.mobile;

import cn.hutool.core.date.DateUtil;
import com.ycwl.basic.biz.OrderBiz;
import com.ycwl.basic.constant.FreeStatus;
import com.ycwl.basic.image.watermark.edge.PuzzleDefaultWatermarkTemplateBuilder;
import com.ycwl.basic.image.watermark.edge.WatermarkEdgeTaskCreator;
import com.ycwl.basic.image.watermark.edge.WatermarkRequest;
import com.ycwl.basic.model.mobile.order.IsBuyRespVO;
import com.ycwl.basic.model.mobile.scenic.content.ContentPageVO;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.model.pc.puzzle.entity.MemberPuzzleEntity;
import com.ycwl.basic.model.pc.scenic.entity.ScenicEntity;
import com.ycwl.basic.pricing.dto.PriceCalculationRequest;
import com.ycwl.basic.pricing.dto.PriceCalculationResult;
import com.ycwl.basic.pricing.dto.ProductItem;
import com.ycwl.basic.pricing.enums.ProductType;
import com.ycwl.basic.pricing.service.IPriceCalculationService;
import com.ycwl.basic.puzzle.edge.task.PuzzleEdgeRenderTaskService;
import com.ycwl.basic.puzzle.entity.PuzzleGenerationRecordEntity;
import com.ycwl.basic.puzzle.mapper.MemberPuzzleMapper;
import com.ycwl.basic.puzzle.repository.PuzzleRepository;
import com.ycwl.basic.repository.FaceRepository;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.service.pc.FaceService;
import com.ycwl.basic.service.printer.PrinterService;
import com.ycwl.basic.utils.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/mobile/puzzle/v1")
@RequiredArgsConstructor
public class AppPuzzleController {

    private final PuzzleRepository puzzleRepository;
    private final FaceRepository faceRepository;
    private final IPriceCalculationService iPriceCalculationService;
    private final PrinterService printerService;
    private final OrderBiz orderBiz;
    private final MemberPuzzleMapper memberPuzzleMapper;
    private final WatermarkEdgeTaskCreator watermarkEdgeTaskCreator;
    private final FaceService faceService;
    private final ScenicRepository scenicRepository;

    /**
     * 根据faceId查询三拼图数量
     */
    @GetMapping("/count/{faceId}")
    public ApiResponse<Integer> countByFaceId(@PathVariable("faceId") Long faceId) {
        if (faceId == null) {
            return ApiResponse.fail("faceId不能为空");
        }
        // 通过关联表查询数量
        List<MemberPuzzleEntity> relations = memberPuzzleMapper.listByFaceId(faceId);
        return ApiResponse.success(relations.size());
    }

    /**
     * 根据faceId查询所有三拼图记录
     */
    @GetMapping("/list/{faceId}")
    public ApiResponse<List<ContentPageVO>> listByFaceId(@PathVariable("faceId") Long faceId) {
        if (faceId == null) {
            return ApiResponse.fail("faceId不能为空");
        }
        // 通过关联表查询，获取关联的拼图记录
        List<MemberPuzzleEntity> relations = memberPuzzleMapper.listByFaceId(faceId);
        List<ContentPageVO> result = relations.stream()
                .map(relation -> {
                    PuzzleGenerationRecordEntity record = puzzleRepository.getRecordById(relation.getRecordId());
                    if (record == null) {
                        return null;
                    }
                    return convertToContentPageVO(record, relation);
                })
                .filter(vo -> vo != null)
                .collect(Collectors.toList());
        return ApiResponse.success(result);
    }

    /**
     * 根据recordId查询单个三拼图记录
     */
    @GetMapping("/detail/{recordId}")
    public ApiResponse<ContentPageVO> getByRecordId(@PathVariable("recordId") Long recordId) {
        if (recordId == null) {
            return ApiResponse.fail("recordId不能为空");
        }
        PuzzleGenerationRecordEntity record = puzzleRepository.getRecordById(recordId);
        if (record == null) {
            return ApiResponse.fail("未找到对应的拼图记录");
        }
        // 查询关联记录
        MemberPuzzleEntity relation = memberPuzzleMapper.getByFaceAndRecord(record.getFaceId(), recordId);
        ContentPageVO result = convertToContentPageVO(record, relation);
        return ApiResponse.success(result);
    }

    /**
     * 根据recordId下载拼图资源
     * 如果是免费赠送的拼图，会添加水印后返回
     */
    @GetMapping("/download/{recordId}")
    public ApiResponse<List<String>> download(@PathVariable("recordId") Long recordId) {
        if (recordId == null) {
            return ApiResponse.fail("recordId不能为空");
        }
        PuzzleGenerationRecordEntity record = puzzleRepository.getRecordById(recordId);
        if (record == null) {
            return ApiResponse.fail("未找到对应的拼图记录");
        }
        String resultImageUrl = record.getResultImageUrl();
        if (resultImageUrl == null || resultImageUrl.isEmpty()) {
            return ApiResponse.fail("该拼图记录没有可用的图片URL");
        }

        // 查询该拼图的关联记录，判断是否为免费赠送
        Long faceId = record.getFaceId();
        if (faceId != null) {
            MemberPuzzleEntity memberPuzzle = memberPuzzleMapper.getByFaceAndRecord(faceId, recordId);
            if (memberPuzzle != null && FreeStatus.isFree(memberPuzzle.getIsFree())) {
                // 免费赠送的拼图，需要添加水印
                String watermarkedUrl = addWatermarkForFreePuzzle(record);
                if (watermarkedUrl != null) {
                    return ApiResponse.success(Collections.singletonList(watermarkedUrl));
                }
                // 如果水印添加失败，记录日志并返回原图
                log.warn("免费拼图水印添加失败，返回原图: recordId={}", recordId);
            }
        }

        return ApiResponse.success(Collections.singletonList(resultImageUrl));
    }

    /**
     * 为免费赠送的拼图添加水印
     *
     * @param record 拼图记录
     * @return 带水印的图片URL，失败返回null
     */
    private String addWatermarkForFreePuzzle(PuzzleGenerationRecordEntity record) {
        try {
            Long faceId = record.getFaceId();
            FaceEntity face = faceRepository.getFace(faceId);
            if (face == null) {
                log.warn("添加水印失败：未找到人脸信息, faceId={}", faceId);
                return null;
            }

            // 获取景区信息
            ScenicEntity scenic = scenicRepository.getScenic(face.getScenicId());
            String scenicLine = scenic != null ? scenic.getName() : "";

            // 获取二维码URL
            String qrcodeUrl = faceService.bindWxaCode(faceId);

            // 格式化日期时间
            String datetimeLine = record.getCreateTime() != null
                    ? DateUtil.format(record.getCreateTime(), "yyyy-MM-dd")
                    : "";

            // 构建水印请求
            WatermarkRequest request = WatermarkRequest.builder()
                    .originalImageUrl(record.getResultImageUrl())
                    .imageWidth(record.getResultWidth() != null ? record.getResultWidth() : 0)
                    .imageHeight(record.getResultHeight() != null ? record.getResultHeight() : 0)
                    .qrcodeUrl(qrcodeUrl)
                    .faceUrl(face.getFaceUrl())
                    .scenicLine(scenicLine)
                    .datetimeLine(datetimeLine)
                    .outputFormat("JPEG")
                    .outputQuality(90)
                    .build();

            // 创建水印任务并等待结果
            PuzzleEdgeRenderTaskService.TaskWaitResult result = watermarkEdgeTaskCreator.createAndWait(
                    PuzzleDefaultWatermarkTemplateBuilder.STYLE,
                    request,
                    record.getId(),
                    faceId,
                    "free_puzzle_download",
                    30_000L  // 30秒超时
            );

            if (result.isSuccess()) {
                log.info("免费拼图水印添加成功: recordId={}, url={}", record.getId(), result.getImageUrl());
                return result.getImageUrl();
            } else {
                log.error("免费拼图水印添加失败: recordId={}, error={}", record.getId(), result.getErrorMessage());
                return null;
            }
        } catch (Exception e) {
            log.error("免费拼图水印添加异常: recordId={}", record.getId(), e);
            return null;
        }
    }

    /**
     * 根据recordId查询拼图价格
     */
    @GetMapping("/price/{recordId}")
    public ApiResponse<PriceCalculationResult> getPriceByRecordId(@PathVariable("recordId") Long recordId) {
        if (recordId == null) {
            return ApiResponse.fail("recordId不能为空");
        }
        PuzzleGenerationRecordEntity record = puzzleRepository.getRecordById(recordId);
        if (record == null) {
            return ApiResponse.fail("未找到对应的拼图记录");
        }
        FaceEntity face = faceRepository.getFace(record.getFaceId());
        if (face == null) {
            return ApiResponse.fail("未找到对应的人脸信息");
        }

        PriceCalculationRequest calculationRequest = new PriceCalculationRequest();
        ProductItem productItem = new ProductItem();
        productItem.setProductType(ProductType.PHOTO_LOG);
        productItem.setProductId(record.getTemplateId().toString());
        productItem.setPurchaseCount(1);
        productItem.setScenicId(face.getScenicId().toString());
        calculationRequest.setProducts(Collections.singletonList(productItem));
        calculationRequest.setUserId(face.getMemberId());
        calculationRequest.setFaceId(record.getFaceId());
        calculationRequest.setPreviewOnly(true); // 仅查询价格,不实际使用优惠
        PriceCalculationResult calculationResult = iPriceCalculationService.calculatePrice(calculationRequest);

        return ApiResponse.success(calculationResult);
    }

    /**
     * 将拼图导入到打印列表
     */
    @PostMapping("/import-to-print/{recordId}")
    public ApiResponse<Integer> importToPrint(@PathVariable("recordId") Long recordId) {
        if (recordId == null) {
            return ApiResponse.fail("recordId不能为空");
        }

        // 查询拼图记录
        PuzzleGenerationRecordEntity record = puzzleRepository.getRecordById(recordId);
        if (record == null) {
            return ApiResponse.fail("未找到对应的拼图记录");
        }

        // 检查是否有图片URL
        String imageUrl = record.getResultImageUrl();
        if (imageUrl == null || imageUrl.isEmpty()) {
            return ApiResponse.fail("该拼图记录没有可用的图片URL");
        }

        // 获取人脸信息
        FaceEntity face = faceRepository.getFace(record.getFaceId());
        if (face == null) {
            return ApiResponse.fail("未找到对应的人脸信息");
        }

        // 调用服务添加到打印列表
        Integer memberPrintId = printerService.addUserPhotoFromPuzzle(
                face.getMemberId(),
                face.getScenicId(),
                record.getFaceId(),
                imageUrl,
                recordId  // 拼图记录ID，用于关联 puzzle_record 表
        );

        if (memberPrintId == null) {
            return ApiResponse.fail("添加到打印列表失败");
        }

        return ApiResponse.success(memberPrintId);
    }

    /**
     * 将PuzzleGenerationRecordEntity转换为ContentPageVO
     *
     * @param record   拼图生成记录
     * @param relation 会员拼图关联记录，用于获取免费状态
     */
    private ContentPageVO convertToContentPageVO(PuzzleGenerationRecordEntity record, MemberPuzzleEntity relation) {
        ContentPageVO vo = new ContentPageVO();

        // 内容类型为3（拼图）
        vo.setContentType(3);

        // 源素材类型为3（拼图）
        vo.setSourceType(3);
        vo.setGroup("拼图");

        // 只要存在记录，lockType不为0（设置为-1表示已生成）
        vo.setLockType(-1);

        // 通过faceId填充scenicId的信息
        FaceEntity face = faceRepository.getFace(record.getFaceId());
        if (record.getFaceId() != null) {
            vo.setScenicId(face.getScenicId());
        }

        // contentId为生成记录id
        vo.setContentId(record.getId());

        // templateCoverUrl和生成的图是一致的
        vo.setTemplateCoverUrl(record.getResultImageUrl());

        // 设置模板ID
        vo.setTemplateId(record.getTemplateId());
        IsBuyRespVO isBuyScenic = orderBiz.isBuy(face.getScenicId(), face.getMemberId(), face.getId(), 5, face.getScenicId());
        if (isBuyScenic.isBuy()) {
            vo.setIsBuy(1);
        } else {
            IsBuyRespVO isBuyRespVO = orderBiz.isBuy(face.getScenicId(), face.getMemberId(), face.getId(), 5, record.getTemplateId());
            if (isBuyRespVO.isBuy()) {
                vo.setIsBuy(1);
            } else {
                vo.setIsBuy(0);
                // 从关联记录读取免费状态
                if (relation != null && FreeStatus.isFree(relation.getIsFree())) {
                    vo.setFreeCount(1);
                } else {
                    vo.setFreeCount(0);
                }
            }
        }
        return vo;
    }
}
