package cn.estsh.i3plus.core.apiservice.controller.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysRoleService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.util.PlatformConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.ResourceEnumUtil;
import cn.estsh.i3plus.pojo.platform.bean.SysRefRoleMenu;
import cn.estsh.i3plus.pojo.platform.bean.SysRole;
import cn.estsh.impp.framework.base.controller.CoreBaseController;
import cn.estsh.impp.framework.boot.auth.AuthUtil;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import cn.estsh.impp.framework.boot.exception.ImppExceptionEnum;
import cn.estsh.impp.framework.boot.util.ResultBean;
import cn.estsh.impp.framework.boot.util.ValidatorBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description : 系统角色对外接口
 * @Reference :
 * @Author : wei.peng
 * @Date : 2018-10-22 16:58:43.790
 * @Modify :
 **/
@RestController
@Api(description = "系统角色服务")
@RequestMapping(PlatformConstWords.BASE_URL + "/sys-role")
public class SysRoleController extends CoreBaseController{

    public static final Logger LOGGER = LoggerFactory.getLogger(SysRoleController.class);

    @Autowired
    private ISysRoleService sysRoleService;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "新增系统角色", notes = "系统角色")
    public ResultBean insertSysRole(SysRole role) {
        try {
            //条件验证
            ValidatorBean.beginValid(role)
                    .notNull("name", role.getName());

            sysRoleService.checkSysRoleOnly(role);

            //新增初始化
            ConvertBean.modelInitialize(role, AuthUtil.getSessionUser());
            role.setRoleStatus(CommonEnumUtil.DATA_STATUS.ENABLE.getValue());
            role.setMenuNumber(0);
            role.setModuleNumber(0);

            role = sysRoleService.insertSysRole(role);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(role);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep).build();
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改系统角色", notes = "系统角色")
    public ResultBean updateSysRole(SysRole role) {
        try {
            // 数据校验
            ValidatorBean.beginValid(role)
                    .notNull("id", role.getId())
                    .notNull("name", role.getName());
            sysRoleService.checkSysRoleOnly(role);

            ConvertBean.modelUpdate(role, AuthUtil.getSessionUser());

            sysRoleService.updateSysRole(role);
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/delete/{id}")
    @ApiOperation(value = "删除系统角色", notes = "删除系统角色")
    public ResultBean deleteSysRole(@PathVariable("id") String id) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "角色id 不能为空");

            sysRoleService.deleteSysRoleById(Long.parseLong(id));
            return ResultBean.success().setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "查询所有角色", notes = "查询所有系统角色")
    public ResultBean findAll() {
        try {
            List<SysRole> list = sysRoleService.findSysRoleAll();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(list);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        }  catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/find-id-list")
    @ApiOperation(value = "查询所有角色", notes = "查询所有系统角色")
    public ResultBean findIdList(String[] ids) {
        try {
            List<SysRole> list = sysRoleService.findSysRoleAll();
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultList(list);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        }  catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/find-ref-menu/{roleId}")
    @ApiOperation(value = "查询角色的所有角色权限关系", notes = "查询角色的所有角色权限关系")
    public ResultBean findRefRoleMenu(@PathVariable("roleId") String roleId) {
        try {
            ValidatorBean.checkNotNull(roleId, "角色id 不能为空");

            List<SysRefRoleMenu> list = sysRoleService.findSysRefRoleMenuByRoleId(Long.parseLong(roleId));
            return ResultBean.success("操作成功")
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode())
                    .setResultList(list);
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value="/query")
    @ApiOperation(value="查询角色",notes="组合查询角色，外带分页功能")
    public ResultBean querySysRole(SysRole role, Pager pager){
        try{
            ListPager<SysRole> listPager = sysRoleService.querySysRole(role, pager);

            return ResultBean.success("操作成功").setListPager(listPager)
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @GetMapping(value = "/get/{id}")
    @ApiOperation(value = "查询系统角色", notes = "查询根据ID查询系统角色")
    public ResultBean getById(@PathVariable("id") String id) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "角色id 不能为空");

            SysRole role = sysRoleService.getSysRoleById(Long.parseLong(id));

            if(role != null){
                return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode()).setResultObject(role);
            }else {
                return ResultBean.fail("数据不存在").setCode(ResourceEnumUtil.MESSAGE.EMPTY.getCode());
            }
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/status")
    @ApiOperation(value = "修改角色状态", notes = "根据ID修改角色状态")
    public ResultBean updateStatus(String id, int status) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(id, "角色id 不能为空");
            ValidatorBean.checkNotZero(status, "角色状态不能为空");

            sysRoleService.updateSysRoleStatus(Long.parseLong(id), status, AuthUtil.getSessionUser());
            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch (ImppBusiException busExcep) {
            return ResultBean.fail(busExcep);
        } catch (Exception e) {
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/batch-status")
    @ApiOperation(value = "批量修改系统角色状态", notes = "根据ID修改系统角色状态")
    public ResultBean updateBatchStatus(String[] ids,int status) {
        try {
            ids = ConvertBean.modelSafeArrayNumber(ids,true);

            // 数据校验
            ValidatorBean.checkNotNull(ids, "角色id 不能为空");
            ValidatorBean.checkNotZero(status, "角色状态不能为空");

            sysRoleService.updateSysRoleStatusByIds(StringTool.getArrayLong(ids),status,AuthUtil.getSessionUser());

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/ref-menu/insert")
    @ApiOperation(value = "新增角色权限关系", notes = "新增角色权限关系")
    public ResultBean insertRefMenu(String roleId,String[] refIds) {
        try {
            // 数据校验
            ValidatorBean.checkNotNull(roleId, "角色roleId 不能为空");

            ConvertBean.modelSafeArrayNumber(refIds,true);

            sysRoleService.refreshSysRoleRef(Long.parseLong(roleId),StringTool.getArrayLong(refIds),AuthUtil.getSessionUser().getUserName());

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @PutMapping(value = "/ref-menu/batch-insert")
    @ApiOperation(value = "批量新增角色权限关系", notes = "批量新增角色权限关系")
    public ResultBean insertBatchRefMenu(String[] roleIds,String[] menuIds) {
        try {
            roleIds = ConvertBean.modelSafeArrayNumber(roleIds,true);
            menuIds = ConvertBean.modelSafeArrayNumber(menuIds,true);

            // 数据校验
            ValidatorBean.checkNotNull(roleIds, "角色roleIds 不能为空");

            if(roleIds.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请输入需要更新的角色信息。")
                        .build();
            }
            List<SysRole> roleList = sysRoleService.findSysRoleByInIdAndStatus(StringTool.getArrayLong(roleIds), CommonEnumUtil.DATA_STATUS.DISABLE.getValue());

            if(roleList != null && roleList.size() > 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                        .setErrorDetail("["+roleList.get(0).getName()+"]角色已禁用，不允许操作")
                        .setErrorSolution("请重新操作")
                        .build();
            }
            sysRoleService.refreshBatchSysRoleRef(StringTool.getArrayLong(roleIds),StringTool.getArrayLong(menuIds),
                    AuthUtil.getSessionUser().getUserName());

            return ResultBean.success("操作成功").setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        } catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }

    @DeleteMapping(value = "/batch-delete")
    @ApiOperation(value = "根据id批量删除", notes = "根据id批量删除")
    public ResultBean deleteSysRoleByIds(String[] ids){
        try{
            ids = ConvertBean.modelSafeArrayNumber(ids,true);
            if(ids.length == 0){
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.CORE.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("请选择需要删除的资源。")
                        .build();
            }
            sysRoleService.deleteSysRoleByIds(StringTool.getArrayLong(ids));
            return ResultBean.success("操作成功")
                    .setCode(ResourceEnumUtil.MESSAGE.SUCCESS.getCode());
        }catch(ImppBusiException busExcep){
            return ResultBean.fail(busExcep);
        }catch(Exception e){
            return ImppExceptionBuilder.newInstance().buildExceptionResult(e);
        }
    }
}
