package cn.pluss.platform.controller.userIntegral;


import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.base.BaseModelController;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.userIntegral.UserIntegralService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 积分商城controller
 * </p>
 *
 * @author bzg
 * @since 2020-11-11
 */
@Controller
@RequestMapping("/userIntegral")
public class UserIntegralController extends BaseModelController<UserIntegralService, UserIntegral> {


    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/index")
    public String index() {
        return "userIntegral/list";
    }

    @Override
    public Result<Page<UserIntegral>> page(Page<UserIntegral> page, UserIntegral condition, OrderItem orderItem) {
        orderItem.setColumn("id").setAsc(false);
        return super.page(page, condition, orderItem);
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = {"/detail/{id}", "/detail"})
    public String detail(HttpServletRequest request, @PathVariable(value = "id", required = false) Integer id) {
        if (id != null) {
            UserIntegral integral = baseService.getById(id);
            request.setAttribute("entity", integral);
        }
        return "userIntegral/detail";
    }

    /**
     * 保存
     * @param entity
     * @return
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Result<String> saveOrUpdate(UserIntegral entity) {
        if("1".equals(entity.getType())){
            MsgException.checkBlank(entity.getOrderNumber(),"交易类型的积分必须填写订单号");
            MsgException.checkNull(entity.getOrderAmt(),"交易类型的积分必须填写订单金额");
            UserIntegral userIntegral = baseService.getByOrderNumber(entity.getOrderNumber());
            MsgException.check(userIntegral != null,"订单号已存在");
        }else if("2".equals(entity.getType())){
            MsgException.check(!"2".equals(entity.getSource()) && !"5".equals(entity.getSource()),"机具活动暂时只支持云音箱和扫码王！");
            QueryWrapper<UserIntegral> queryWrapper = new QueryWrapper<UserIntegral>().eq("userId",entity.getUserId())
                    .eq("type",entity.getType()).eq("source",entity.getSource());
            List<UserIntegral> list = baseService.list(queryWrapper);
            if(!list.isEmpty()){
                MsgException.throwException("机具活动积分来源只能添加一次");
            }
        }
        baseService.saveOrUpdate(entity);
        return ResultGenerator.genSuccessResult("操作成功",null);
    }
}
