package com.ruoyi.app.order;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.system.domain.*;
import jakarta.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.mapper.PosReviewMapper;
import com.ruoyi.system.service.*;
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.transaction.annotation.Transactional;
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.common.utils.MessageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * reviewController
 *
 * @author ruoyi
 * @date 2023-06-08
 */
@RestController
@RequestMapping("/system/review")
public class PosReviewController extends BaseController {
    @Autowired
    private IPosReviewService posReviewService;
    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private PosReviewMapper posReviewMapper;

    @Autowired
    private ISysPointControlService pointControlService;
    @Autowired
    private IUserWalletService userWalletService;
    @Autowired
    private IPointsTransactionService pointsTransactionService;

    /**
     * 查询用户的评论列表
     *
     * @param token
     * @param page
     * @param size
     * @return
     */
    @Anonymous
    @Auth
    @GetMapping("/getUserRevew")
    public AjaxResult getUserRevew(
            @RequestHeader String token,
            @RequestParam(defaultValue = "",required = false) String ddId,
            @RequestParam(required = false) Long mdId,
            @RequestParam Integer page,
            @RequestParam Integer size
    ) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        Long userId = Long.valueOf(id);
        IPage<PosReview> palist = new Page<>(page, size);
        QueryWrapper<PosReview> Wrapper = new QueryWrapper<>();
        Wrapper.eq("user_id", userId);
        Wrapper.eq(!StrUtil.isEmpty(ddId),"dd_id",ddId);
        Wrapper.eq(mdId!=null,"md_id",mdId);
        IPage<PosReview> list = posReviewService.page(palist, Wrapper);
        List<PosReview> orlist = list.getRecords();
        JSONArray arr = new JSONArray();
        for (int i = 0; i < orlist.size(); i++) {
            JSONObject org = new JSONObject();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            org.put("id", orlist.get(i).getId());
            org.put("ddId", orlist.get(i).getDdId());
            org.put("score", orlist.get(i).getScore());
            org.put("cretim", sdf.format(orlist.get(i).getCretim()));
            org.put("content", orlist.get(i).getContent());
            org.put("images", orlist.get(i).getImages());
            org.put("user", orlist.get(i).getAnonymous() == 0 ? infoUserService.getById(orlist.get(i).getUserId()) : "匿名");
            arr.add(org);
        }
        return success(arr);
    }

    @Anonymous
    @GetMapping("/getmdrevew")
    public AjaxResult getmdrevew(@RequestParam Integer page,
                                 @RequestParam Integer size,
                                 @RequestParam Long mdid) {
        IPage<PosReview> palist = new Page<>(page, size);
        QueryWrapper<PosReview> Wrapper = new QueryWrapper<>();
        Wrapper.eq("md_id", mdid);
        IPage<PosReview> list = posReviewService.page(palist, Wrapper);
        List<PosReview> orlist = list.getRecords();
        JSONArray arr = new JSONArray();
        for (int i = 0; i < orlist.size(); i++) {
            JSONObject org = new JSONObject();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            org.put("id", orlist.get(i).getId());
            org.put("ddId", orlist.get(i).getDdId());
            org.put("score", orlist.get(i).getScore());
            org.put("cretim", sdf.format(orlist.get(i).getCretim()));
            org.put("content", orlist.get(i).getContent());
            org.put("images", orlist.get(i).getImages());
            org.put("user", orlist.get(i).getAnonymous() == 0 ? infoUserService.getById(orlist.get(i).getUserId()) : "匿名");
            arr.add(org);
        }
        return success(arr);
    }

    @Transactional(rollbackFor = Exception.class)
    @Anonymous
    @Auth
    @PostMapping("/addrevew")
    public AjaxResult addrevew(@RequestHeader String token, @RequestBody PosReview posReview) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        PosReview review = posReviewMapper.getrewiew(posReview.getDdId());
        if (review == null) {
            posReview.setUserId(Long.valueOf(id));
            //判断是否为新增
            if (ObjectUtil.isEmpty(posReview.getId())) {
                addPoint(Long.valueOf(id), posReview.getDdId());
            }
            boolean org = posReviewService.saveOrUpdate(posReview);
            if (org) {
                return success(MessageUtils.message("no.comment.success"));
            } else {
                throw new ServiceException(MessageUtils.message("no.comment.fail"));
            }
        } else {
            return error(MessageUtils.message("no.comment.repeat"));
        }
    }

    /**
     * 添加积分
     */
    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) {

                userWalletService.createUserWallet(userid);
            } 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, "1");
            }

        }

    }

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


    /**
     * 查询review列表
     */
    @PreAuthorize("@ss.hasPermi('system:review:list')")
    @GetMapping("/list")
    public TableDataInfo list(PosReview posReview) {
        startPage();
        List<PosReview> list = posReviewService.selectPosReviewList(posReview);
        return getDataTable(list);
    }

    /**
     * 导出review列表
     */
    @PreAuthorize("@ss.hasPermi('system:review:export')")
    @Log(title = "review", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PosReview posReview) {
        List<PosReview> list = posReviewService.selectPosReviewList(posReview);
        ExcelUtil<PosReview> util = new ExcelUtil<PosReview>(PosReview.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.review"));
    }

    /**
     * 获取review详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:review:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(posReviewService.selectPosReviewById(id));
    }

    /**
     * 新增review
     */
    @PreAuthorize("@ss.hasPermi('system:review:add')")
    @Log(title = "review", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PosReview posReview) {
        return toAjax(posReviewService.insertPosReview(posReview));
    }

    /**
     * 修改review
     */
    @PreAuthorize("@ss.hasPermi('system:review:edit')")
    @Log(title = "review", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PosReview posReview) {
        return toAjax(posReviewService.updatePosReview(posReview));
    }

    /**
     * 删除review
     */
    @PreAuthorize("@ss.hasPermi('system:review:remove')")
    @Log(title = "review", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(posReviewService.deletePosReviewByIds(ids));
    }
}
