package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.MallRole;
import com.iformall.domain.po.MallRolePermission;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.MallUserRole;
import com.iformall.enums.EnumUserAdmin;
import com.iformall.service.MallRolePermissionService;
import com.iformall.service.MallRoleService;
import com.iformall.service.MallUserInfoService;
import com.iformall.service.MallUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
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 MallUserInfoService mallUserInfoService;

    @Autowired
    private MallUserRoleService mallUserRoleService;

    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    public ResultData list(MallRole sysRole, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] MallRoleController::list");
        String tenantId = getTenantId();
        sysRole.setTenantId(tenantId);
        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);
            PageInfo<MallRolePermission> pers = sysRolePermissionService.listAsPage(p, 1, 1000);
            String menus = "";
            for (MallRolePermission rp : pers.getList()) {
                menus += rp.getPermissionId() + ",";
            }
            if (menus.length() > 1) {
                menus = menus.substring(0, menus.length() - 1);
            }
            r.setMenus(menus);
        }
        return new ResultData(page);
    }


    @PostMapping("saveOrUpdate")
    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);
//    	SysRolePermissionService.deleteById(id);
        if (StringUtils.isNoneBlank(sysRole.getMenus())) {
            List<Long> mIds = new ArrayList<>();
            for (String mId : sysRole.getMenus().split(",")) {
                mIds.add(Long.valueOf(mId));
            }
            sysRolePermissionService.savePermissions(tenantId, sysRole.getId(), mIds.toArray(new Long[]{}));
        }
        return new ResultData();
    }


    @PostMapping("add")
    public ResultData add(MallRole sysRole) {
        logger.debug("[" + getIpAddr() + "] MallRoleController::add");
        MallUserInfo currentUser = getUser();
        if(currentUser.getIsAdmin().equals(EnumUserAdmin.Normal.getCode())) {
            return new ResultData(ErrorCode.USER_NOT_ADMIN.getCode(), "只有超级管理员才能添加角色");
        }
        Assert.notNull(sysRole.getName(), "角色名不能为空");
        Assert.isTrue(checkUnique(sysRole.getName(), currentUser.getTenantId())>0, "重复的角色名");
        sysRoleService.saveOrUpdate(sysRole);
        return new ResultData();
    }

    @PostMapping("update")
    public ResultData update(MallRole sysRole) {
        logger.debug("[" + getIpAddr() + "] MallRoleController::update");
        MallUserInfo currentUser = getUser();
        if(currentUser.getIsAdmin().equals(EnumUserAdmin.Normal.getCode())) {
            return new ResultData(ErrorCode.USER_NOT_ADMIN.getCode(), "只有超级管理员才能更新角色");
        }
        if (sysRole.getName() != null) {
            Assert.isTrue(checkUnique(sysRole.getName(), currentUser.getTenantId())>1, "角色名已存在");
        }
        sysRoleService.saveOrUpdate(sysRole);
//		Assert.notNull(sysRole.getName(), "角色名不能为空");
        return new ResultData();
    }


    @PostMapping("/del")
    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);
    }

}
