package cn.pluss.platform.controller.rewardConfig;


import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.base.BaseModelController;
import cn.pluss.platform.entity.RewardConfig;
import cn.pluss.platform.entity.UserRole;
import cn.pluss.platform.rewardConfig.RewardConfigService;
import cn.pluss.platform.user.UserRoleService;
import com.alibaba.fastjson.JSON;
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.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 用户奖励配置 前端控制器
 * </p>
 *
 * @author bzg
 * @since 2022-02-22
 */
@Controller
@RequestMapping("/rewardConfig")
public class RewardConfigController extends BaseModelController<RewardConfigService, RewardConfig> {

    @Resource
    private UserRoleService userRoleService;


    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/index")
    public String index(HttpServletRequest request) {
        List<UserRole> list = userRoleService.list();
        request.setAttribute("roleList", JSON.toJSONString(list));
        return "rewardConfig/list";
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = {"/detail/{id}", "/detail"})
    public String detail(HttpServletRequest request, @PathVariable(value = "id", required = false) Integer id) {
        List<UserRole> list = userRoleService.list();
        if (id != null) {
            RewardConfig entity = baseService.getOne(new QueryWrapper<RewardConfig>().eq("id",id));
            request.setAttribute("entity", entity);
        }
        request.setAttribute("roleList", list);
        return "rewardConfig/detail";
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = "/save")
    @Override
    public Result<String> save(@RequestBody RewardConfig entity) {
        try {
            entity.setType(RewardConfig.DEFAULT_TYPE);
            entity.setScale(entity.getScale().divide(BigDecimal.valueOf(10000)));
            return super.save(entity);
        }catch (Exception e){
            return ResultGenerator.genFailResult("系统开小差了");
        }
    }

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