package com.ruoyi.app.order;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IPointsTransactionService;
import com.ruoyi.system.service.ISysPointControlService;
import com.ruoyi.system.service.IUserWalletService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IPosOrderRatingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 订单评级Controller
 *
 * @author ruoyi
 * @date 2025-07-29
 */
@RestController
@RequestMapping("/system/rating")
public class PosOrderRatingController extends BaseController
{
    @Autowired
    private IPosOrderRatingService posOrderRatingService;
    @Autowired
    private ISysPointControlService pointControlService;
    @Autowired
    private IUserWalletService userWalletService;
    @Autowired
    private IPointsTransactionService pointsTransactionService;


    /**
     * 消费用户保存订单评级
     * @param posOrderRating
     * @return
     */
    @Anonymous
    @Auth
    @PostMapping("/saveOrderRating")
    public AjaxResult saveOrderRating(
            @RequestHeader String token,
            @RequestBody PosOrderRating posOrderRating) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        PosOrderRating review = posOrderRatingService.getOne(new LambdaQueryWrapper<PosOrderRating>().eq(PosOrderRating::getDdId, posOrderRating.getDdId()));
        if(review != null) {
            toAjax(posOrderRatingService.updatePosOrderRating(posOrderRating));
        }
        posOrderRating.setUserId(Long.valueOf(id));
        posOrderRating.setCreateTime(DateUtils.getNowDate());
        //两个星级都设置才能获取积分
        if(posOrderRating.getMdStars()!=null && posOrderRating.getMdStars()>0 && posOrderRating.getQsStars()!=null && posOrderRating.getQsStars()>0){
            addPoint(Long.valueOf(id),posOrderRating.getDdId());
        }

        return toAjax(posOrderRatingService.insertPosOrderRating(posOrderRating));
    }
    /**
     * 添加积分
     */
    /**
     * 添加积分
     */
    private void addPoint(Long userid, String ddId) {
        SysPointControl control = pointControlService.getById(1);
        //开启评论获得积分
        if (control.getReviewEnable().equals(1L)) {
            LambdaQueryWrapper<UserWallet> walletQuery = new LambdaQueryWrapper<>();
            walletQuery.eq(UserWallet::getUserId, userid);
            walletQuery.isNull(UserWallet::getStoreId);
            UserWallet userWallet = userWalletService.getOne(walletQuery);

            if (userWallet == null) {
                userWallet = new UserWallet();
                userWallet.setUserId(userid);
                userWallet.setPointsWallet(control.getReviewPoints());
                userWallet.setBalanceWallet(java.math.BigDecimal.ZERO);
                createPointTransaction(userid, control.getReviewPoints(), userWallet.getPointsWallet(), ddId);
                userWalletService.save(userWallet);
            } else {
                Long userPoint = userWallet.getPointsWallet();
                Long point = control.getReviewPoints();
                Long newPoint = userPoint + point;
                userWallet.setPointsWallet(newPoint);
                int oldVersion = userWallet.getVersion();
                userWallet.setVersion(userWallet.getVersion() + 1);
                walletQuery.eq(UserWallet::getVersion, oldVersion);
                boolean update = userWalletService.update(userWallet, walletQuery);
                if (!update) {
                    throw new ServiceException(MessageUtils.message("no.points.update.fail"));
                }
                createPointTransaction(userid, control.getReviewPoints(), userWallet.getPointsWallet(), ddId);
            }

        }

    }
    /**
     * 创建积分流水
     */
    private void createPointTransaction(Long userid, Long pointsChange, Long currentPoints, String ddId) {
        PointsTransaction pointsTransaction = new PointsTransaction();
        pointsTransaction.setUserId(userid);
        pointsTransaction.setPointsChange("+" + pointsChange);
        pointsTransaction.setCurrentPoints(currentPoints.toString());
        pointsTransaction.setType("0");
        pointsTransaction.setDdId(ddId);
        pointsTransaction.setCreateTime(new Date());
        pointsTransactionService.save(pointsTransaction);
    }




    /**
     * 获取订单评级
     * @return
     */
    @Auth
    @GetMapping("/getOrderRating")
    public AjaxResult getOrderRating(
            @RequestHeader String token,
            @RequestParam String ddId) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        PosOrderRating rating = posOrderRatingService.getOne(new LambdaQueryWrapper<PosOrderRating>().eq(PosOrderRating::getDdId, ddId));
        return success(rating);
    }


    /**
     * 查询订单评级列表
     */
    @PreAuthorize("@ss.hasPermi('system:rating:list')")
    @GetMapping("/list")
    public TableDataInfo list(PosOrderRating posOrderRating)
    {
        startPage();
        List<PosOrderRating> list = posOrderRatingService.selectPosOrderRatingList(posOrderRating);
        return getDataTable(list);
    }

    /**
     * 导出订单评级列表
     */
    @PreAuthorize("@ss.hasPermi('system:rating:export')")
    @Log(title = "订单评级", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PosOrderRating posOrderRating)
    {
        List<PosOrderRating> list = posOrderRatingService.selectPosOrderRatingList(posOrderRating);
        ExcelUtil<PosOrderRating> util = new ExcelUtil<PosOrderRating>(PosOrderRating.class);
        util.exportExcel(list, "订单评级数据");
    }

    /**
     * 获取订单评级详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:rating:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(posOrderRatingService.selectPosOrderRatingById(id));
    }

    /**
     * 新增订单评级
     */
    @PreAuthorize("@ss.hasPermi('system:rating:add')")
    @Log(title = "订单评级", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PosOrderRating posOrderRating)
    {
        return toAjax(posOrderRatingService.insertPosOrderRating(posOrderRating));
    }

    /**
     * 修改订单评级
     */
    @PreAuthorize("@ss.hasPermi('system:rating:edit')")
    @Log(title = "订单评级", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PosOrderRating posOrderRating)
    {
        return toAjax(posOrderRatingService.updatePosOrderRating(posOrderRating));
    }

    /**
     * 删除订单评级
     */
    @PreAuthorize("@ss.hasPermi('system:rating:remove')")
    @Log(title = "订单评级", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(posOrderRatingService.deletePosOrderRatingByIds(ids));
    }
}
