package com.ycwl.basic.controller.extern;

import cn.hutool.http.HttpUtil;
import com.ycwl.basic.annotation.IgnoreToken;
import com.ycwl.basic.image.enhancer.adapter.BceImageEnhancer;
import com.ycwl.basic.image.enhancer.entity.BceEnhancerConfig;
import com.ycwl.basic.image.pipeline.core.PhotoProcessContext;
import com.ycwl.basic.image.pipeline.stages.DownloadStage;
import com.ycwl.basic.image.pipeline.stages.ImageEnhanceStage;
import com.ycwl.basic.image.pipeline.stages.ImageSRStage;
import com.ycwl.basic.image.pipeline.stages.SourcePhotoUpdateStage;
import com.ycwl.basic.image.pipeline.stages.CleanupStage;
import com.ycwl.basic.pipeline.core.Pipeline;
import com.ycwl.basic.pipeline.core.PipelineBuilder;
import com.ycwl.basic.mapper.AioDeviceMapper;
import com.ycwl.basic.mapper.MemberMapper;
import com.ycwl.basic.model.aio.entity.AioDeviceBannerEntity;
import com.ycwl.basic.model.aio.entity.AioDeviceEntity;
import com.ycwl.basic.model.aio.entity.AioDevicePriceConfigEntity;
import com.ycwl.basic.model.aio.req.AioDeviceCreateOrderReq;
import com.ycwl.basic.model.aio.resp.AioDeviceCreateOrderResp;
import com.ycwl.basic.model.aio.resp.AioDeviceInfoResp;
import com.ycwl.basic.model.mobile.face.FaceRecognizeResp;
import com.ycwl.basic.model.mobile.goods.GoodsDetailVO;
import com.ycwl.basic.model.mobile.goods.GoodsReqQuery;
import com.ycwl.basic.model.pc.face.resp.FaceRespVO;
import com.ycwl.basic.model.pc.member.entity.MemberEntity;
import com.ycwl.basic.pay.entity.PayResponse;
import com.ycwl.basic.service.aio.AioDeviceService;
import com.ycwl.basic.service.mobile.GoodsService;
import com.ycwl.basic.service.pc.FaceService;
import com.ycwl.basic.service.pc.OrderService;
import com.ycwl.basic.service.pc.SourceService;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.SnowFlakeUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@IgnoreToken
@RestController
@RequestMapping("/api/aio")
public class AioDeviceController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private FaceService faceService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private AioDeviceMapper aioDeviceMapper;
    @Autowired
    private AioDeviceService aioDeviceService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SourceService sourceService;

    @GetMapping("/info")
    public ApiResponse<AioDeviceInfoResp> getDeviceInfo(HttpServletRequest request) {
        String deviceId = request.getHeader("X-DeviceId");
        AioDeviceEntity aioDevice = aioDeviceMapper.getByKey(deviceId);
        if (aioDevice == null) {
            return ApiResponse.fail("设备不存在");
        }
        List<AioDeviceBannerEntity> banners = aioDeviceMapper.getBannerByDeviceId(aioDevice.getId());
        return ApiResponse.success(new AioDeviceInfoResp(aioDevice, banners));
    }

    @GetMapping("/banners")
    public ApiResponse<List<AioDeviceBannerEntity>> getBanners(HttpServletRequest request) {
        String deviceId = request.getHeader("X-DeviceId");
        AioDeviceEntity aioDevice = aioDeviceMapper.getByKey(deviceId);
        if (aioDevice == null) {
            return ApiResponse.fail("设备不存在");
        }
        List<AioDeviceBannerEntity> banners = aioDeviceMapper.getBannerByDeviceId(aioDevice.getId());
        return ApiResponse.success(banners);
    }

    @GetMapping("/config")
    public ApiResponse<AioDevicePriceConfigEntity> getPriceConfig(HttpServletRequest request) {
        String deviceId = request.getHeader("X-DeviceId");
        AioDeviceEntity aioDevice = aioDeviceMapper.getByKey(deviceId);
        if (aioDevice == null) {
            return ApiResponse.fail("设备不存在");
        }
        AioDevicePriceConfigEntity config = aioDeviceMapper.getPriceConfigByDeviceId(aioDevice.getId());
        return ApiResponse.success(config);
    }

    @PostMapping("/faceUpload")
    public ApiResponse<FaceRecognizeResp> faceUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String deviceId = request.getHeader("X-DeviceId");
        AioDeviceEntity aioDevice = aioDeviceMapper.getByKey(deviceId);
        if (aioDevice == null) {
            return ApiResponse.fail("设备不存在");
        }
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setScenicId(aioDevice.getScenicId());
        memberEntity.setCreateDate(new Date());
        memberEntity.setId(SnowFlakeUtil.getLongId());
        memberEntity.setNickname("用户");
        memberMapper.add(memberEntity);
        FaceRecognizeResp resp = faceService.faceUpload(file, aioDevice.getScenicId(), memberEntity.getId(), "");
        // 尝试超分
        new Thread(() -> {
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                return;
            }
            GoodsReqQuery query = new GoodsReqQuery();
            query.setSourceType(2);
            query.setFaceId(resp.getFaceId());
            List<GoodsDetailVO> sourcePhotoList = goodsService.sourceGoodsList(query);
            if (sourcePhotoList == null || sourcePhotoList.isEmpty()) {
                log.info("无源图片");
                redisTemplate.opsForValue().set("aio:faceId:"+resp.getFaceId().toString()+":pass", "1", 1, TimeUnit.DAYS);
                return;
            }
            log.info("超分开始！共{}张图片待处理", sourcePhotoList.size());

            sourcePhotoList.forEach(photo -> {
                if (StringUtils.contains(photo.getUrl(), "_q_")) {
                    log.debug("跳过已增强的图片: {}", photo.getUrl());
                    return;
                }

                try {
                    // 创建超分Pipeline
                    Pipeline<PhotoProcessContext> superResolutionPipeline = createSuperResolutionPipeline(photo.getGoodsId());

                    // 使用静态工厂方法创建Context
                    PhotoProcessContext context = PhotoProcessContext.forSuperResolution(
                            photo.getGoodsId(), photo.getUrl(), photo.getScenicId()
                    );

                    // 启用图像增强和超分的Stage
                    context.enableStage("image_enhance");
                    context.enableStage("image_sr");

                    // 执行Pipeline
                    boolean success = superResolutionPipeline.execute(context);

                    if (success) {
                        log.info("超分成功: {} -> {}", photo.getUrl(), context.getResultUrl());
                    } else {
                        log.error("超分失败: {}", photo.getGoodsId());
                    }

                } catch (Exception e) {
                    log.error("超分失败：{}", photo.getGoodsId(), e);
                }
            });
            redisTemplate.opsForValue().set("aio:faceId:"+sourcePhotoList.getFirst().getFaceId().toString()+":pass", "1", 1, TimeUnit.DAYS);
        }).start();
        return ApiResponse.success(resp);
    }

    // 人脸信息
    @GetMapping("/{faceId}")
    public ApiResponse<FaceRespVO> faceInfo(@PathVariable Long faceId) {
        return faceService.getById(faceId);
    }
    @GetMapping("/face/{faceId}/check")
    public ApiResponse<Boolean> faceCheck(@PathVariable Long faceId) {
        if (redisTemplate.hasKey("aio:faceId:"+faceId.toString()+":pass")) {
            return ApiResponse.success(true);
        } else {
            return ApiResponse.success(false);
        }
    }
    @GetMapping("/face/{faceId}/bindWxaCode")
    public ApiResponse<String> bindWxaCode(@PathVariable Long faceId) {
        return ApiResponse.success(faceService.bindWxaCode(faceId));
    }
    // 照片商品列表
    @GetMapping("/{faceId}/photo")
    public ApiResponse<List<GoodsDetailVO>> sourceGoodsList(@PathVariable Long faceId) {
        GoodsReqQuery query = new GoodsReqQuery();
        query.setSourceType(2);
        query.setFaceId(faceId);
        List<GoodsDetailVO> goodsDetailVOS = goodsService.sourceGoodsList(query);
        return ApiResponse.success(goodsDetailVOS);
    }

    // 创建订单
    @PostMapping("/order")
    public ApiResponse<AioDeviceCreateOrderResp> createOrder(HttpServletRequest request, @RequestBody AioDeviceCreateOrderReq req) {
        String deviceId = request.getHeader("X-DeviceId");
        AioDeviceEntity aioDevice = aioDeviceMapper.getByKey(deviceId);
        if (aioDevice == null) {
            return ApiResponse.fail("设备不存在");
        }
        return ApiResponse.success(aioDeviceService.createOrder(aioDevice, req));
    }

    // 查询订单
    @GetMapping("/order/{orderId}")
    public ApiResponse<PayResponse> queryOrder(HttpServletRequest request, @PathVariable("orderId") Long orderId) {
        String deviceId = request.getHeader("X-DeviceId");
        AioDeviceEntity aioDevice = aioDeviceMapper.getByKey(deviceId);
        if (aioDevice == null) {
            return ApiResponse.fail("设备不存在");
        }
        return ApiResponse.success(orderService.queryOrder(orderId));
    }

    /**
     * 创建源图片超分辨率增强Pipeline
     *
     * @param sourceId 源图片ID
     * @return 超分Pipeline
     */
    private Pipeline<PhotoProcessContext> createSuperResolutionPipeline(Long sourceId) {
        // 创建带有百度云配置的ImageEnhanceStage
        BceEnhancerConfig config = new BceEnhancerConfig();
        config.setQps(1);
        config.setAppId("119554288");
        config.setApiKey("OX6QoijgKio3eVtA0PiUVf7f");
        config.setSecretKey("dYatXReVriPeiktTjUblhfubpcmYfuMk");

        return new PipelineBuilder<PhotoProcessContext>("SourcePhotoSuperResolutionPipeline")
                .addStage(new DownloadStage())                                    // 1. 下载图片
                .addStage(new ImageEnhanceStage(config)).addStage(new ImageSRStage(config)) // 2. 图像增强(超分)
                .addStage(new SourcePhotoUpdateStage(sourceService, sourceId))   // 3. 上传并更新数据库
                .addStage(new CleanupStage())                                    // 4. 清理临时文件
                .build();
    }

    private BceImageEnhancer getEnhancer() {
        BceImageEnhancer enhancer = new BceImageEnhancer();
        BceEnhancerConfig config = new BceEnhancerConfig();
        config.setQps(1);
        config.setAppId("119554288");
        config.setApiKey("OX6QoijgKio3eVtA0PiUVf7f");
        config.setSecretKey("dYatXReVriPeiktTjUblhfubpcmYfuMk");
        enhancer.setConfig(config);
        return enhancer;
    }
}
