package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.entity.result.R;
import shop.alien.entity.store.LifeComment;
import shop.alien.entity.store.vo.LifePinglunVo;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.LifeCommentService;
import shop.alien.util.common.FileUpload;
import shop.alien.util.common.ListToPage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 评论
 */
@Api(tags = {"一期-评论"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/comment")
@RequiredArgsConstructor
public class LifeCommentController {

    private final LifeCommentService lifeCommentService;

    private final FileUpload fileUpload;

    /**
     * 点赞接口
     *
     * @param userId  用户ID
     * @param huifuId 被点赞对象ID（评论ID/动态ID/活动ID等）
     * @param type    点赞类型（1-评论 2-社区动态 3-活动 4-推荐菜 5-店铺打卡 6-二手商品 7-律师评分 8-点赞员工）
     * @return 点赞结果
     */
    @TrackEvent(
            eventType = "POST_LIKE",
            eventCategory = "INTERACTION",
            storeId = "",
            userId = "#userId",
            targetId = "#huifuId",
            targetType = "POST"
    )
    @ApiOperation("点赞")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "huifuId", value = "被点赞对象ID（评论ID/动态ID/活动ID等）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "点赞类型（1-评论 2-社区动态 3-活动 4-推荐菜 5-店铺打卡 6-二手商品 7-律师评分 8-点赞员工）", dataType = "String", paramType = "query", required = true)
    })
    @PostMapping("/like")
    public R<Boolean> like(@RequestParam("userId") String userId,
                           @RequestParam("huifuId") String huifuId,
                           @RequestParam("type") String type) {
        log.info("点赞请求，userId={}，huifuId={}，type={}", userId, huifuId, type);
        
        try {
            // 参数校验
            if (!StringUtils.hasText(userId)) {
                log.warn("点赞失败，用户ID为空");
                return R.fail("用户ID不能为空");
            }
            if (!StringUtils.hasText(huifuId)) {
                log.warn("点赞失败，被点赞对象ID为空");
                return R.fail("被点赞对象ID不能为空");
            }
            if (!StringUtils.hasText(type)) {
                log.warn("点赞失败，点赞类型为空");
                return R.fail("点赞类型不能为空");
            }
            
            int result = lifeCommentService.like(userId, huifuId, type);
            if (result > 0) {
                log.info("点赞成功，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return R.success("点赞成功");
            } else {
                log.warn("点赞失败，可能已点赞或操作失败，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return R.fail("点赞失败，可能已点赞或操作失败");
            }
        } catch (Exception e) {
            log.error("点赞异常，userId={}，huifuId={}，type={}，异常信息：{}", userId, huifuId, type, e.getMessage(), e);
            return R.fail("点赞失败：" + e.getMessage());
        }
    }

    /**
     * 取消点赞接口
     *
     * @param userId  用户ID
     * @param huifuId 被取消点赞对象ID（评论ID/动态ID/活动ID等）
     * @param type    点赞类型（1-评论 2-社区动态 3-活动 4-推荐菜 5-店铺打卡 6-二手商品 7-律师评分 8-点赞员工）
     * @return 取消点赞结果
     */
    @ApiOperation("取消点赞")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "huifuId", value = "被取消点赞对象ID（评论ID/动态ID/活动ID等）", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "点赞类型（1-评论 2-社区动态 3-活动 4-推荐菜 5-店铺打卡 6-二手商品 7-律师评分 8-点赞员工）", dataType = "String", paramType = "query", required = true)
    })
    @PostMapping("/cancelLike")
    public R<Boolean> cancelLike(@RequestParam("userId") String userId,
                                  @RequestParam("huifuId") String huifuId,
                                  @RequestParam("type") String type) {
        log.info("取消点赞请求，userId={}，huifuId={}，type={}", userId, huifuId, type);
        
        try {
            // 参数校验
            if (!StringUtils.hasText(userId)) {
                log.warn("取消点赞失败，用户ID为空");
                return R.fail("用户ID不能为空");
            }
            if (!StringUtils.hasText(huifuId)) {
                log.warn("取消点赞失败，被取消点赞对象ID为空");
                return R.fail("被取消点赞对象ID不能为空");
            }
            if (!StringUtils.hasText(type)) {
                log.warn("取消点赞失败，点赞类型为空");
                return R.fail("点赞类型不能为空");
            }
            
            int result = lifeCommentService.cancelLike(userId, huifuId, type);
            if (result > 0) {
                log.info("取消点赞成功，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return R.success("取消点赞成功");
            } else {
                log.warn("取消点赞失败，可能未点赞或操作失败，userId={}，huifuId={}，type={}", userId, huifuId, type);
                return R.fail("取消点赞失败，可能未点赞或操作失败");
            }
        } catch (Exception e) {
            log.error("取消点赞异常，userId={}，huifuId={}，type={}，异常信息：{}", userId, huifuId, type, e.getMessage(), e);
            return R.fail("取消点赞失败：" + e.getMessage());
        }
    }

    @ApiOperation("回复评论")
    @ApiOperationSupport(order = 3)
    @PostMapping("/addOrUpdateComment")
    public R<Boolean> addOrUpdateComment(@RequestBody LifeComment pingun,
                                         @RequestParam(value = "image1", required = false) MultipartFile image1,
                                         @RequestParam(value = "image2", required = false) MultipartFile image2) {
        log.info("LifeCommentController.addOrUpdateComment?store={}&image1={}&image2={}", pingun.toString(),
                image1 == null ? null : image1.getOriginalFilename(),
                image2 == null ? null : image2.getOriginalFilename());
        try {
            int num = lifeCommentService.addOrUpdateStore(pingun);
            String path = "";
            if (image1 != null && !StringUtils.isEmpty(image1.getOriginalFilename())) {
                path = fileUpload.saveImage(image1);
            }
            if (image2 != null && !StringUtils.isEmpty(image2.getOriginalFilename())) {
                String image1Path2 = fileUpload.saveImage(image2);
                if (StringUtils.isEmpty(path)) {
                    path = path + ";" + image1Path2;
                }
            }
            // 设置图片路径
            if (StringUtils.isEmpty(pingun.getImagePath())) {
                pingun.setImagePath(path);
            }
            if (num == 0) {
                return R.fail("回复评论失败");
            }
            return R.success("回复评论成功");
        } catch (Exception e) {
            log.error("LifeCommentController.addOrUpdateComment ERROR Msg={}", e.getMessage());
            return R.fail("回复评论失败");
        }
    }

    @ApiOperation("评论列表")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({@ApiImplicitParam(name = "page", value = "分页页数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "分页条数", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "storeId", value = "storeId", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isHuifu", value = "isHuifu", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pinglunLevel", value = "pinglunLevel", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pinglunDays", value = "pinglunDays", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pinglunLeibie", value = "pinglunLeibie", dataType = "String", paramType = "query")})
    @GetMapping("/getCommentByCondition")
    private R<IPage<Map<String, Object>>> getCommentByCondition(@RequestParam(value = "userId", defaultValue = "") String userId,
                                                                @RequestParam(value = "storeId", defaultValue = "") String storeId,
                                                                @RequestParam(value = "isHuifu", defaultValue = "") String isHuifu,
                                                                @RequestParam(value = "pinglunLevel", defaultValue = "") String pinglunLevel,
                                                                @RequestParam(value = "pinglunDays", defaultValue = "") String pinglunDays,
                                                                @RequestParam(value = "pinglunLeibie", defaultValue = "") String pinglunLeibie,
                                                                @RequestParam(defaultValue = "1") int page,
                                                                @RequestParam(defaultValue = "10") int size) {
        log.info("LifeCommentController.getCommentByCondition?userId={}, storeId={}, isHuifu={}, pinglunLevel={}, pinglunDays={}, pinglunLeibie={}, page={}, size={}", userId, storeId, isHuifu, pinglunLevel, pinglunDays, pinglunLeibie, page, size);
        // 转换结果
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, List<LifePinglunVo>> mapList = lifeCommentService.getAppealByStoreId(userId, storeId, isHuifu, pinglunLevel, pinglunDays, pinglunLeibie);
        // 遍历输入 map
        int totalPinglun = 0;
        for (Map.Entry<String, List<LifePinglunVo>> entry : mapList.entrySet()) {
            String year = entry.getKey();
            List<LifePinglunVo> records = entry.getValue();
            Map<String, Object> newMap = new HashMap<>();
            newMap.put("huifuId", year);
            newMap.put("records", records);
            newMap.put("pinglunCount", records.size());
            totalPinglun = totalPinglun + records.size();
            result.add(newMap);
        }
        return R.data(ListToPage.setPage(result, page, size));
    }


    @ApiOperation("商家端-顾客评论")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "页数", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "storeId", value = "店铺id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "isReply", value = "是否回复,0:全部;1:已回复;2:未回复;", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "commentType", value = "评论类别,0:全部;1:好评;2:中评;3:差评;", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "date", value = "查询日期", dataType = "String", paramType = "query")
    })
    @GetMapping("/getStoreComment")
    public R<IPage<LifeComment>> getStoreComment(Integer pageNum, Integer pageSize, Integer storeId, Integer isReply, Integer commentType, String date) {
        return R.data(lifeCommentService.getStoreComment(pageNum, pageSize, storeId, isReply, commentType, date));
    }

}
