package com.ruoyi.web.controller.school.salary;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.xluobo.core.page.RespPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.school.salary.domain.ScCommissionPlans;
import com.ruoyi.school.salary.service.ScCommissionPlansService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("commissionPlans")
@AllArgsConstructor
public class ScCommissionPlansController {

    private final ScCommissionPlansService service;


    @PostMapping("list")
    public AjaxResult list(@RequestBody Map<String,Object> params){
        RespPage<ScCommissionPlans> page = new RespPage<>((Integer) params.get("pageNum"), (Integer) params.get("pageSize"));
        RespPage<ScCommissionPlans> page1 = service.page(page, Wrappers.<ScCommissionPlans>lambdaQuery()
                .eq(StrUtil.isNotEmpty((CharSequence) params.get("planName")),
                        ScCommissionPlans::getPlanName, params.get("planName"))
                .eq(ScCommissionPlans::getTenantId, SecurityUtils.getLoginUser().getNowTenantId())
                .eq(ObjectUtil.isNotEmpty(params.get("isActive")),
                        ScCommissionPlans::getIsActive, params.get("isActive"))
        );
        return AjaxResult.success(page1);
    }

    @GetMapping("/listAll")
    public AjaxResult listAll(){
        List<ScCommissionPlans> page1 = service.list( Wrappers.<ScCommissionPlans>lambdaQuery()
                .eq(ScCommissionPlans::getIsActive, 1)
                .eq(ScCommissionPlans::getTenantId, SecurityUtils.getLoginUser().getNowTenantId())
        );
        return AjaxResult.success(page1);
    }
    @PostMapping("saveOrEdit")
    public AjaxResult saveOrEdit(@RequestBody ScCommissionPlans salaryBase){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        salaryBase.setTenantId(loginUser.getNowTenantId());
        if (salaryBase.getIsActive().equals("0")){
            if (ObjectUtil.isNotEmpty(salaryBase.getId())){
                salaryBase.setIsActive(new Byte("1"));
            }
        }
        service.saveOrUpdate(salaryBase);
        return AjaxResult.success();
    }

    @PostMapping("remove")
    public AjaxResult remove(Integer id){
        if (service.isUsed(id)){
            return AjaxResult.error("方案已经被使用，无法删除");
        }
        service.removeById(id);
        return AjaxResult.success();
    }

}
