package cn.com.countrygarden.bi.main.service.impl;


import cn.com.countrygarden.bi.main.dao.AccessTokenMapper;
import cn.com.countrygarden.bi.main.dao.sys.MacRoleMapMapper;
import cn.com.countrygarden.bi.main.dao.sys.RoleMapper;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysUserRoleMapper;
import cn.com.countrygarden.bi.main.model.sys.MacRoleMap;
import cn.com.countrygarden.bi.main.model.sys.Role;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.sys.UserWhiteUrl;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUserRole;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections4.MultiMapUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

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

@Service
@Transactional
public class UserRoleServiceImpl implements UserRoleService {
    private final Logger logger = LoggerFactory.getLogger(UserRoleServiceImpl.class);

    @Autowired
    private AccessTokenMapper accessTokenMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TbSysUserRoleMapper tbSysUserRoleMapper;


    @Autowired
    private MacRoleMapMapper macRoleMapMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Override
    public List<Role> findUserRoles(String userCode) {
        List<Role> result = new ArrayList<Role>();
        result = roleMapper.findByUserCode(userCode);
        if (result.size() == 0) {
            List<MacRoleMap> mapList = macRoleMapMapper.selectAll();
            if (mapList.size() == 0) {
                return result;
            }
            MultiValuedMap<String, MacRoleMap> macRoleMap = new ArrayListValuedHashMap<String, MacRoleMap>();
            for (MacRoleMap map : mapList) {
                macRoleMap.put(map.getErpRoleCode(), map);
            }
            List<TbSysUserRole> tbRoles = tbSysUserRoleMapper.findByUserCode(userCode);
            List<UserRoles> generateRoles = new ArrayList<UserRoles>();
            for (TbSysUserRole tbRole : tbRoles) {
                List<MacRoleMap> macRoleMaps = MultiMapUtils.getValuesAsList(macRoleMap, tbRole.getRoleCode());
                if (macRoleMaps != null && macRoleMaps.size() > 0) {
                    for (MacRoleMap roleMap : macRoleMaps) {
                        UserRoles role = new UserRoles();
                        role.setRoleCode(roleMap.getMcaRoleCode());
                        role.setCreatedBy("sys");
                        role.setUpdatedBy("sys");
                        role.setCreatedDate(new Date());
                        role.setUpdatedDate(role.getCreatedDate());
                        role.setUserCode(userCode);
                        generateRoles.add(role);
                    }
                }
            }
            if (generateRoles.size() > 0) {

                userRolesMapper.insertList(generateRoles);
            }

            result = roleMapper.findByUserCode(userCode);
        }

        return result;
    }

    public List<Role> listRoles() {
        Role query = new Role();
        query.setEnable(true);
        List<Role> result = roleMapper.select(query);
        return result;
    }

    public void addUserToRole(String currentUser, String userCode, String roleCode) {
        UserRoles query = new UserRoles();
        query.setUserCode(userCode);
        query.setRoleCode(roleCode);
        int count = userRolesMapper.selectCount(query);
        if (count > 0) {
            return;
        }
        UserRoles role = new UserRoles();
        role.setRoleCode(roleCode);
        role.setCreatedBy(currentUser);
        role.setUpdatedBy(currentUser);
        role.setCreatedDate(new Date());
        role.setUpdatedDate(role.getCreatedDate());
        role.setUserCode(userCode);
        logger.info("添加授权"+"，授权人："+currentUser+",授权角色编码："+roleCode+",授权时间："+new Date()+"，用户userCode"+userCode);
        System.out.println("添加授权"+"，授权人："+currentUser+",授权角色编码："+roleCode+",授权时间："+new Date()+"，用户userCode"+userCode);
        userRolesMapper.insert(role);
    }

    public List<UserRoles> searchByUserCodes(String roleCode, List<String> userCodes) {
        return userRolesMapper.searchByUserCodes(roleCode, userCodes);
    }

    public Page<UserRoles> searchByRoleCode(String roleCode, int page, int size, List<String> userCodes) {
        Page<UserRoles> pageData = PageHelper.startPage(page, size, true).doSelectPage(
                new ISelect() {
                    @Override
                    public void doSelect() {
                        Condition condition = new Condition(UserRoles.class);
                        Example.Criteria criteria = condition.createCriteria()
                                .andEqualTo("roleCode", roleCode);
                        // 不包含ERP中删除的用户
                        if (userCodes!= null && userCodes.size()>0) {
                            criteria.andNotIn("userCode", userCodes);
                        }
                        condition.setOrderByClause("user_code asc");

                        userRolesMapper.selectByCondition(condition);
                    }
                }
        );

        return pageData;
    }

    public void deleteUserRoles(String userCode, String roleCode,String accessToken) {
        Condition condition = new Condition(UserRoles.class);
        condition.createCriteria()
                .andEqualTo("roleCode", roleCode)
                .andEqualTo("userCode", userCode);
        logger.info("删除授权"+"，授权人："+accessToken+",角色编码："+roleCode+",授权时间："+new Date()+"用户userCode"+userCode);
        System.out.println("删除授权"+"，授权人："+accessToken+",角色编码："+roleCode+",授权时间："+new Date()+"用户userCode"+userCode);
        userRolesMapper.deleteByCondition(condition);
    }

    @Override
    public int judgeRole(String userCode) {
        List<UserRoles> roleCodeList = userRolesMapper.searchByUserCode(userCode);
        String roleCode = null;
        for (UserRoles userRoles : roleCodeList) {
            roleCode = userRoles.getRoleCode();
            if (roleCode.contains("NCFinancial_HeadQuarters")) {      //判断有无总部
                return 0;
            } else if (roleCode.contains("NCFinancial_Region")) {      //判断有无区域
                return 1;
            } else if (roleCode.contains("NCFinancial_Project")) {      //判断有无项目
                return 2;
            }
        }
        return 3;
    }

    public int judgeRoleExContract(String userCode) {
        List<UserRoles> roleCodeList = userRolesMapper.searchByUserCode(userCode);
        String roleCode = null;
        for (UserRoles userRoles : roleCodeList) {
            roleCode = userRoles.getRoleCode();
            if (roleCode.contains("ExContract_HeadQuarters")) {      //判断是否为总部角色
                return 0;
            } else if (roleCode.contains("ExContract_Region")) {      //判断是否为区域角色
                return 1;
            }
        }
        return 3;
    }

    @Override
    public List<String> selectperformanceCenter() {
        return userRolesMapper.selectperformanceCenter();
    }
    @Override
    public List<String> selectUserCodes(String roleCode) {
        return userRolesMapper.selectUserCodes(roleCode);
    }

    @Override
    public Integer countByUserCodeAndRoleCode(String userCode, String admin) {
        return userRolesMapper.countByUserCodeAndoleCode(userCode, admin);
    }

	@Override
	@Cacheable(value = "userRole", key = "#roleCode")
	public List<UserWhiteUrl> getUserWhiteUrlByUserCode(String roleCode) {
		return roleMapper.getUserWhiteUrlByRoleCode(roleCode);
	}
}
