package com.iformall.controller.sys;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.*;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.enums.EnumUserAdmin;
import com.iformall.service.MallRolePermissionService;
import com.iformall.service.MallRoleService;
import com.iformall.service.MallUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("role")
@Api(description = "角色相关接口")
public class MallRoleController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MallRoleService sysRoleService;

    @Autowired
    private MallRolePermissionService sysRolePermissionService;

    @Autowired
    private MallUserRoleService mallUserRoleService;

    @ApiOperation("角色列表")
    @GetMapping("list")
    //@RequiresPermissions("sys:role:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    @SystemControllerLog(description = "用户管理-role列表")
    public ResultData list(MallRole sysRole, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] MallRoleController::list");
        String tenantId = getTenantId();
        sysRole.setTenantId(tenantId);
        sysRole.setSortColumns(BaseEntity.SortField.Id_DESC);
        final PageInfo<MallRole> page = sysRoleService.listAsPage(sysRole, pageNum, pageSize);
        for (MallRole r : page.getList()) {
            MallRolePermission p = new MallRolePermission();
            p.setRoleId(r.getId());
            p.setTenantId(tenantId);
            List<MallRolePermission> pers = sysRolePermissionService.getList(p);
            String menus = "";
            for (MallRolePermission rp : pers) {
                menus += rp.getPermissionId() + ",";
            }
            if (menus.length() > 1) {
                menus = menus.substring(0, menus.length() - 1);
            }
            r.setMenus(menus);
        }
        return new ResultData(page);
    }

    @ApiOperation("角色详情")
    @GetMapping("findById")
    //@RequiresPermissions("sys:role:get")
    @SystemControllerLog(description = "用户管理-role信息")
    public ResultData findById(MallRole sysRole) {
        logger.debug("[" + getIpAddr() + "] MallRoleController::list");
        if (sysRole.getId() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        MallRole role = sysRoleService.getById(sysRole.getId());
        MallRolePermission p = new MallRolePermission();
        p.setRoleId(role.getId());
        p.setTenantId(getTenantId());
        List<MallRolePermission> pers = sysRolePermissionService.getList(p);
        String menus = "";
        for (MallRolePermission rp : pers) {
            menus += rp.getPermissionId() + ",";
        }
        if (menus.length() > 1) {
            menus = menus.substring(0, menus.length() - 1);
        }
        role.setMenus(menus);
        return new ResultData(role);
    }


    @ApiOperation("角色保存")
    @PostMapping("saveOrUpdate")
    //@RequiresPermissions("sys:role:save")
    @SystemControllerLog(description = "用户管理-rule保存")
    public ResultData saveOrUpdate(@RequestBody MallRole sysRole) {
        logger.debug("[" + getIpAddr() + "] MallRoleController::saveOrUpdate");
        MallUserInfo currentUser = getUser();
        if (currentUser.getIsAdmin().equals(EnumUserAdmin.Normal.getCode())) {
            return new ResultData(ErrorCode.USER_NOT_ADMIN.getCode(), "只有系统管理员才能保存角色");
        }
        String tenantId = currentUser.getTenantId();
        int count = checkUnique(sysRole.getName(), tenantId);
        if (sysRole.getId() == null && count > 0) {
            return new ResultData(ResultData.ERROR, "角色名已存在");
        }
        sysRole.setTenantId(tenantId);
        sysRoleService.saveOrUpdate(sysRole);
        if (StringUtils.isNoneBlank(sysRole.getMenus())) {
            String[] menuIds = sysRole.getMenus().split(",");
            List<Long> mIds = new ArrayList<>();
            for (String mId : menuIds) {
                mIds.add(Long.valueOf(mId));
            }
            sysRolePermissionService.savePermissions(tenantId, sysRole.getId(), mIds.toArray(new Long[]{}));
        }
        return new ResultData();
    }

    @ApiOperation("角色删除")
    @PostMapping("/del")
    //@RequiresPermissions("sys:role:del")
    @SystemControllerLog(description = "用户管理-rule删除")
    public ResultData delete(@RequestBody MallRole sysRole) {
        logger.debug("[" + getIpAddr() + "] MallRoleController::delete");
        MallUserInfo currentUser = getUser();
        if (currentUser.getIsAdmin().equals(EnumUserAdmin.Normal.getCode())) {
            return new ResultData(ErrorCode.USER_NOT_ADMIN.getCode(), "只有系统管理员才能删除角色");
        }
        MallUserRole record = new MallUserRole();
        record.setRoleId(sysRole.getId());
        int count = mallUserRoleService.cntUserList(record);
        if (count > 0) {
            return new ResultData(ErrorCode.USER_USE_ROLE.getCode(), "有用户使用此角色，请先删除相应的用户！！");
        }
        sysRoleService.deleteById(sysRole.getId());
        sysRolePermissionService.deleteByRoleId(sysRole.getId());
        return new ResultData(Result.SUCCESS, "删除成功", null);
    }

    private int checkUnique(String name, String tenantId) {
        MallRole role = new MallRole();
        role.setName(name);
        role.setTenantId(tenantId);
        return sysRoleService.countList(role);
    }

}
