package com.qnfhq.modules.c2c.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.qnfhq.annotation.RepeatSubmit;
import com.qnfhq.common.constant.Constant;
import com.qnfhq.common.page.PageData;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.common.utils.Result;
import com.qnfhq.common.validator.ValidatorUtils;
import com.qnfhq.modules.c2c.dto.RatingsReviewsDTO;
import com.qnfhq.modules.c2c.dto.RatingsReviewsListDTO;
import com.qnfhq.modules.c2c.dto.setting.ReviewSetting;
import com.qnfhq.modules.c2c.entity.C2cOrderEntity;
import com.qnfhq.modules.c2c.entity.RatingsReviewsEntity;
import com.qnfhq.modules.c2c.enums.C2cOrderStatusEnum;
import com.qnfhq.modules.c2c.enums.ReviewsAnonymousEnum;
import com.qnfhq.modules.c2c.service.C2cOrderService;
import com.qnfhq.modules.c2c.service.RatingsReviewsService;
import com.qnfhq.modules.user.entity.SettingEntity;
import com.qnfhq.modules.user.enums.SettingEnum;
import com.qnfhq.modules.user.service.SettingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * c2c交易对象评价
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-29
 */
@RestController
@RequestMapping("/reviews")
@Tag(name="c2c交易对象评价")
@Slf4j
public class RatingsReviewsController {
    @Resource
    private RatingsReviewsService ratingsReviewsService;

    @Resource
    private SettingService settingService;

    @Resource
    private C2cOrderService c2cOrderService;


    @PostMapping("/list")
    @Operation(summary = "收到的评价")
    public Result<PageData<RatingsReviewsEntity>> list(@RequestBody RatingsReviewsListDTO dto){
        ValidatorUtils.validateEntity(dto);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Constant.PAGE, dto.getPageNum());
        params.put(Constant.LIMIT, dto.getPageSize());
        params.put(Constant.ORDER_FIELD, "id");
        params.put(Constant.ORDER, "desc");
        params.put("userId", StpUtil.getLoginIdAsLong());
        params.put("rating", dto.getRating());
        PageData<RatingsReviewsEntity> page = ratingsReviewsService.selectPageByUserId(params);
        return new Result<PageData<RatingsReviewsEntity>>().ok(page);
    }


    /**
     *  对c2c订单交易评价，交易双方都能评价一次
     * @param dto
     * @return
     */
    @PostMapping("/create")
    @Operation(summary = "发表评价")
    @RepeatSubmit(interval = 3000, message = "请求过于频繁")
    public Result create(@RequestBody RatingsReviewsDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto);

        Long orderId = dto.getOrderId();
        C2cOrderEntity order = c2cOrderService.selectById(orderId);
        if (order == null) {
            return new Result().error(MessageUtils.message("c2c.order.not.exist"));//订单编号无效
        }

        //确认是交易方
        if (StpUtil.getLoginIdAsLong()!=order.getUserId().longValue()
                && StpUtil.getLoginIdAsLong()!=order.getTranUserId().longValue()) {
            return new Result().error(MessageUtils.message("c2c.order.reviews.not.tran.user"));//订单的交易方才能发表评论
        }

        if(order.getStatus() != C2cOrderStatusEnum.COMPLETE.getCode()) {
            return new Result().error(MessageUtils.message("c2c.order.reviews.not.complete"));//订单状态"已完成"才能发表评论
        }

        Long inputUserId = StpUtil.getLoginIdAsLong();//提交人编号
        String inputNickname = null;//提交人昵称
        Long ratingUserId = null;//被评价人编号
        String ratingNickname = null;//被评价人昵称
        if(order.getUserId().longValue() == inputUserId.longValue()) {
            ratingUserId = order.getTranUserId();
            ratingNickname = order.getTranUserName();
            inputNickname = order.getUserName();
        } else {
            ratingUserId = order.getUserId();
            ratingNickname = order.getUserName();
            inputNickname = order.getTranUserName();
        }

        RatingsReviewsEntity reviews = ratingsReviewsService.selectByOrderIdInputUserId(orderId, StpUtil.getLoginIdAsLong());
        if(reviews!=null) {
            return new Result().error(MessageUtils.message("c2c.order.you.reviewed"));//该订单您已发表评价
        }

        reviews = new RatingsReviewsEntity();
        reviews.setOrderId(orderId);
        reviews.setUserId(ratingUserId);
        reviews.setNickname(ratingNickname);
        reviews.setRating(dto.getRating());
        reviews.setLables(dto.getLables());
        reviews.setContent(dto.getContent());
        reviews.setIsAnonymous(dto.getIsAnonymous());
        if(dto.getIsAnonymous().equals(ReviewsAnonymousEnum.YES.getCode())) {
            reviews.setInputNickname("匿名");
        } else {
            reviews.setInputNickname(inputNickname);
        }
        reviews.setStatus(0);//待审核
        reviews.setInputUserId(inputUserId);
        reviews.setCreateTime(new Date());
        reviews.setUpdateTime(new Date());
        try {
            return ratingsReviewsService.create(reviews);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new Result().error(MessageUtils.message("c2c.order.reviews.create.fail"));//发表评价
        }
    }

    @PostMapping("/lables")
    @Operation(summary = "评价标签")
    public Result lables(){
        SettingEntity setting = settingService.getSetting(SettingEnum.REVIEW_SETTING.name());
        List<ReviewSetting> settingsList = JSONUtil.toList(JSONUtil.parseArray(setting.getSettingValue()), ReviewSetting.class);
        if (CollectionUtils.isEmpty(settingsList)) {
            return new Result().error(MessageUtils.message("c2c.reviews.lables.notset"));//"未配置评价标签"
        }
        return new Result().ok(settingsList);
    }

}
