package shop.alien.second.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.SecondVideoTask;
import shop.alien.entity.result.R;
import shop.alien.entity.second.SecondGoods;
import shop.alien.entity.second.enums.SecondGoodsStatusEnum;
import shop.alien.entity.second.vo.SecondGoodsStatusVo;
import shop.alien.entity.second.vo.SecondGoodsVo;
import shop.alien.mapper.second.SecondGoodsAuditMapper;
import shop.alien.second.service.SecondGoodsAuditService;
import shop.alien.second.service.SecondGoodsService;
import shop.alien.second.service.VideoModerationService;
import shop.alien.util.common.JwtUtil;
import shop.alien.config.filter.NoRepeatSubmit;
import shop.alien.util.common.safe.ImageModerationUtil;
import shop.alien.util.common.safe.TextModerationResultVO;
import shop.alien.util.common.safe.TextModerationUtil;
import shop.alien.util.common.safe.TextReviewServiceEnum;
import shop.alien.util.common.safe.*;

import java.util.List;

/**
 * 二手商品控制器
 */
@Slf4j
@Api(tags = {"二手平台-商品管理"})
@ApiSort(1)
@CrossOrigin
@RestController
@RequestMapping("/secondGoods")
@RequiredArgsConstructor
public class SecondGoodsController {

    /**
     * 视频审核服务
     */
    private final VideoModerationService videoModerationService;
    /**
     * 二手商品服务
     */
    private final SecondGoodsService secondGoodsService;

    /**
     * 二手商品审核表
     */
    private final SecondGoodsAuditMapper secondGoodsAuditMapper;

    // 注入文本审核工具
    private final TextModerationUtil textModerationUtil;

    // 注入图片审核工具
    private final ImageModerationUtil imageModerationUtil;

    // 注入二手商品审核服务
    private final SecondGoodsAuditService secondGoodsAuditService;

    /**
     * 根据ID获取二手商品
     */
    @GetMapping("/getSecondGoodsById")
    @ApiOperation("根据ID获取二手商品 - 商品编辑回显")
    public R<SecondGoodsVo> getSecondGoodsById(@ApiParam("根据ID获取二手商品 - 商品编辑回显") @RequestParam Integer id) {
        log.info("SecondGoodsController.getSecondGoodsById?id={}", id);
        return R.data(secondGoodsService.getSecondGoodsById(id), "获取成功");
    }

    /**
     * 根据商品ID查询商品状态
     */
    @GetMapping("/getGoodsStatusById")
    @ApiOperation("根据商品ID查询商品状态（0草稿 1审核中 2审核失败 3已上架 4已下架 5已售出）")
    public R<SecondGoodsStatusVo> getGoodsStatusById(@ApiParam("商品ID") @RequestParam Integer id) {
        log.info("SecondGoodsController.getGoodsStatusById?id={}", id);
        if (id == null) {
            return R.fail("商品ID不能为空");
        }
        SecondGoods goods = secondGoodsService.getById(id);
        if (goods == null) {
            return R.fail("商品不存在");
        }
        SecondGoodsStatusVo vo = new SecondGoodsStatusVo();
        vo.setId(goods.getId());
        vo.setGoodsStatus(goods.getGoodsStatus());
        SecondGoodsStatusEnum statusEnum = SecondGoodsStatusEnum.fromCode(goods.getGoodsStatus());
        vo.setGoodsStatusName(statusEnum != null ? statusEnum.getDescription() : null);
        vo.setFailedReason(goods.getFailedReason());
        return R.data(vo, "查询成功");
    }

    /**
     * 添加二手商品
     */
    @PostMapping("/save")
    @ApiOperation("发布二手商品")
    @NoRepeatSubmit(expireTime = 5, message = "请勿重复提交发布商品请求")
    public R<Void> addSecondGoods(@ApiParam("二手商品信息") @RequestBody SecondGoodsVo secondGoods) throws Exception {
        log.info("SecondGoodsController.addSecondGoods?secondGoods={}", secondGoods.toString());
        JSONObject data = JwtUtil.getCurrentUserInfo();
        if (null != data) {
            int userId = data.getInteger("userId");
            secondGoods.setUserId(userId);// 设置用户ID （发布者）
        }
        if(secondGoods.getSaveType().equals(0)){
            if (!secondGoodsService.saveAsDraft(secondGoods)) {
                return R.fail("保存商品为草稿失败");
            }
            return R.success("保存商品为草稿成功");
        } else {
            String validateMsg = secondGoodsService.validatePublishQualification(secondGoods.getUserId());
            if (validateMsg != null) {
                return R.fail(validateMsg);
            }
            // 添加商品 0 创建
            if (!secondGoodsService.createBasicInfo(secondGoods,0)) {
                return R.fail("添加二手商品失败");
            }
            return R.success("添加二手商品成功");
        }
    }

    /**
     * 更新二手商品
     */
    @PostMapping("/edit")
    @ApiOperation("更新二手商品")
    @NoRepeatSubmit(expireTime = 5, message = "请勿重复提交更新商品请求")
    public R<Void> updateSecondGoods(@ApiParam("二手商品信息") @RequestBody SecondGoodsVo secondGoods) throws Exception {
        log.info("SecondGoodsController.updateSecondGoods?secondGoods={}", secondGoods.toString());
        JSONObject data = JwtUtil.getCurrentUserInfo();
        if (null != data) {
            int userId = data.getInteger("userId");
            secondGoods.setUserId(userId);// 设置用户ID （发布者）
        }
        // 添加商品 0 创建 1 更新
        if (!secondGoodsService.createBasicInfo(secondGoods,1)) {
            return R.fail("修改二手商品失败");
        }
        return R.success("修改二手商品成功");
    }


    /**
     * 下架二手商品
     */
    @PostMapping("/shelve")
    @ApiOperation("下架二手商品")
    @NoRepeatSubmit(expireTime = 3, message = "请勿重复提交下架商品请求")
    public R<Void> shelveSecondGoods(@ApiParam("下架二手商品") @RequestBody SecondGoodsVo secondGoods) {
        log.info("SecondGoodsController.shelveSecondGoods?secondGoods={}", secondGoods.toString());
        boolean shelveResult = secondGoodsService.shelveSecondGoods(secondGoods);
        if (shelveResult) {
            return R.success("下架成功");
        } else {
            return R.fail("下架失败");
        }
    }

    /**
     * 删除二手商品
     */
    @PostMapping("/delete")
    @ApiOperation("删除二手商品")
    @NoRepeatSubmit(expireTime = 3, message = "请勿重复提交删除商品请求")
    public R<Void> deleteSecondGoods(@ApiParam("删除二手商品") @RequestBody SecondGoodsVo secondGoods) {
        log.info("SecondGoodsController.deleteSecondGoods?secondGoods={}", secondGoods.toString());
        SecondGoods goods = secondGoodsService.getById(secondGoods.getId());
        if (goods != null) {
            boolean removeResult = secondGoodsService.removeById(secondGoods.getId());
            if (removeResult) {
                // 设置删除标记并记录操作历史
                goods.setDeleteFlag(1);
                secondGoodsService.recordGoodsOperation(goods,"删除商品");
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } else {
            return R.fail("商品不存在");
        }
    }

    /**
     * 商品审核状态查询-消息跳转用
     */
    @GetMapping("/getGoodsAuditStatus")
    @ApiOperation("商品审核状态查询-消息跳转用(商品状态 0:草稿 1:审核中 2:审核失败 3:已上架 4:已下架 5:已售出)")
    public R<SecondGoods> getGoodsAuditStatus(@ApiParam("商品审核id") @RequestParam Integer goodsId) {
        log.info("SecondGoodsController.getGoodsAuditStatus?goodsId={}", goodsId);
//        Integer goodsId = secondGoodsAuditMapper.selectById(auditId).getGoodsId();
        if (goodsId != null){
            // 获取商品审核状态
            QueryWrapper<SecondGoods> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(SecondGoods::getId, goodsId);
            return R.data(secondGoodsService.getOne(queryWrapper));
        }else {
            return R.fail("商品不存在");
        }
    }

    /**
     * 商品热度添加接口
     */
    @PostMapping("/addGoodsHot")
    @ApiOperation("商品热度添加，热度数量加1")
    public R<Void> addGoodsHot(@ApiParam("商品ID") @RequestParam Integer goodsId) {
        log.info("SecondGoodsController.addGoodsHot?goodsId={}", goodsId);
        if (goodsId == null) {
            return R.fail("商品ID不能为空");
        }
        
        SecondGoods goods = secondGoodsService.getById(goodsId);
        if (goods == null) {
            return R.fail("商品不存在");
        }
        
        // 热度数量加1（使用likeCount字段表示热度）
        SecondGoods updateGoods = new SecondGoods();
        updateGoods.setId(goodsId);
        updateGoods.setLikeCount(goods.getLikeCount() == null ? 1 : goods.getLikeCount() + 1);
        boolean result = secondGoodsService.updateById(updateGoods);
        
        if (result) {
            return R.success("热度添加成功");
        } else {
            return R.fail("热度添加失败");
        }
    }

    /**
     * 文本审核接口 - 商品发布场景
     */
    @GetMapping("/textModeration/productPublish")
    @ApiOperation("文本审核 - 商品发布场景（大语言模型输入文字检测、广告法合规检测_专业版）")
    public R<TextModerationResultVO> productPublishTextModeration(@ApiParam("待审核文本") @RequestParam String text) {
        log.info("SecondGoodsController.productPublishTextModeration?text={}", text);
        try {
            List<String> servicesList = Lists.newArrayList();
            servicesList.add(TextReviewServiceEnum.AD_COMPLIANCE_DETECTION_PRO.getService());
            servicesList.add(TextReviewServiceEnum.LLM_QUERY_MODERATION.getService());
            TextModerationResultVO textModerationResultVO = textModerationUtil.invokeFunction(text,servicesList);
            return R.data(textModerationResultVO);
        } catch (Exception e) {
            log.error("文本审核异常", e);
            return R.fail("文本审核异常: " + e.getMessage());
        }
    }

    /**
     * 文本审核接口 - 聊一聊场景
     */
    @GetMapping("/textModeration/chat")
    @ApiOperation("文本审核 - 聊一聊场景（私聊互动内容检测_专业版、广告法合规检测_专业版）")
    public R<TextModerationResultVO> chatTextModeration(@ApiParam("待审核文本") @RequestParam String text) {
        log.info("SecondGoodsController.chatTextModeration?text={}", text);
        try {
            List<String> servicesList = Lists.newArrayList();
            servicesList.add(TextReviewServiceEnum.AD_COMPLIANCE_DETECTION_PRO.getService());
            servicesList.add(TextReviewServiceEnum.CHAT_DETECTION_PRO.getService());
            TextModerationResultVO textModerationResultVO = textModerationUtil.invokeFunction(text,servicesList);
            return R.data(textModerationResultVO);
        } catch (Exception e) {
            log.error("文本审核异常", e);
            return R.fail("文本审核异常: " + e.getMessage());
        }
    }

    /**
     * 文本审核接口 - 评论场景
     */
    @GetMapping("/textModeration/comment")
    @ApiOperation("文本审核 - 评论场景（公聊评论内容检测_专业版、广告法合规检测_专业版）")
    public R<TextModerationResultVO> commentTextModeration(@ApiParam("待审核文本") @RequestParam String text) {
        log.info("SecondGoodsController.commentTextModeration?text={}", text);
        try {
            List<String> servicesList = Lists.newArrayList();
            servicesList.add(TextReviewServiceEnum.AD_COMPLIANCE_DETECTION_PRO.getService());
            servicesList.add(TextReviewServiceEnum.CHAT_DETECTION_PRO.getService());
            TextModerationResultVO textModerationResultVO = textModerationUtil.invokeFunction(text,servicesList);
            return R.data(textModerationResultVO);
        } catch (Exception e) {
            log.error("文本审核异常", e);
            return R.fail("文本审核异常: " + e.getMessage());
        }
    }

    /**
     * 图片审核接口 - 发布商品场景
     */
    @GetMapping("/imageModeration/productPublish")
    @ApiOperation("图片审核 - 发布商品场景（内容治理检测、AIGC图片风险检测）")
    public R<ImageModerationResultVO> productPublishImageModeration(@ApiParam("图片地址") @RequestParam String imageUrl) {
        log.info("SecondGoodsController.productPublishImageModeration?imageUrl={}", imageUrl);
        try {
            List<String> servicesList = Lists.newArrayList();
            // TODO 后续配置到数据库 中
            servicesList.add(ImageReviewServiceEnum.TONALITY_IMPROVE.getService());
            servicesList.add(ImageReviewServiceEnum.AIGC_CHECK.getService());
            ImageModerationResultVO response = imageModerationUtil.productPublishCheck(imageUrl,servicesList);
            return R.data(response);
        } catch (Exception e) {
            log.error("图片审核异常", e);
            return R.fail("图片审核异常: " + e.getMessage());
        }
    }

    /**
     * 图片审核接口 - 聊一聊场景
     */
    @GetMapping("/imageModeration/chat")
    @ApiOperation("图片审核 - 聊一聊场景（内容治理检测）")
    public R<ImageModerationResultVO> chatImageModeration(@ApiParam("图片地址") @RequestParam String imageUrl) {
        log.info("SecondGoodsController.chatImageModeration?imageUrl={}", imageUrl);
        try {
            List<String> servicesList = Lists.newArrayList();
            // TODO 后续配置到数据库 中
            servicesList.add(ImageReviewServiceEnum.TONALITY_IMPROVE.getService());
            ImageModerationResultVO response = imageModerationUtil.productPublishCheck(imageUrl,servicesList);
            return R.data(response, "审核成功");
        } catch (Exception e) {
            log.error("图片审核异常", e);
            return R.fail("图片审核异常: " + e.getMessage());
        }
    }

    /**
     * 处理视频审核结果
     * @param taskId 视频审核任务ID
     * @return 处理结果
     */
    @ApiOperation("处理视频审核结果")
    @GetMapping("/processVideoResult")
    public boolean processVideoResult(String taskId) {
        try {
            SecondVideoTask task = videoModerationService.getTaskByTaskId(taskId);
            if (task == null) {
                return false;
            }
            secondGoodsService.processVideoModerationResult(task);
            return true;
        } catch (Exception e) {
            log.error("处理视频审核结果时发生异常，任务ID: {}", taskId, e);
            return false;
        }
    }

    /**
     * 获取AI商品审核结果
     * 查询所有状态为处理中的AI审核任务，并更新审核结果
     * @return 处理结果
     */
    @ApiOperation("获取AI商品审核结果")
    @GetMapping("/getAiGoodsCheckResult")
    public R<String> getAiGoodsCheckResult() {
        log.info("SecondGoodsController.getAiGoodsCheckResult");
        try {
            String result = secondGoodsAuditService.getAiGoodsCheckResult();
            return R.data(result, "获取AI审核结果完成");
        } catch (Exception e) {
            log.error("获取AI商品审核结果异常", e);
            return R.fail("获取AI商品审核结果异常: " + e.getMessage());
        }
    }

    /**
     * 处理视频审核结果
     * 查询所有待处理的视频审核任务，拉取审核结果并更新商品状态
     * @return 处理结果
     */
    @ApiOperation("处理所有待处理的视频审核任务")
    @GetMapping("/processVideoModerationResult")
    public R<String> processVideoModerationResult() {
        log.info("SecondGoodsController.processVideoModerationResult");
        try {
            String result = videoModerationService.processAllPendingVideoTasks();
            return R.data(result, "视频审核结果处理完成");
        } catch (Exception e) {
            log.error("处理视频审核结果异常", e);
            return R.fail("处理视频审核结果异常: " + e.getMessage());
        }
    }
}