package cn.wisenergy.service.impl;


import cn.wisenergy.common.utils.Md5Util;
import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.mapper.WorkRoleMapper;
import cn.wisenergy.mapper.WorkUserMapper;
import cn.wisenergy.mapper.WorkUserRoleMapper;
import cn.wisenergy.model.app.WorkRole;
import cn.wisenergy.model.app.WorkSubmitAdopt;
import cn.wisenergy.model.app.WorkUser;
import cn.wisenergy.model.dto.*;
import cn.wisenergy.model.enums.LevelEnum;
import cn.wisenergy.model.enums.ManagerEnum;
import cn.wisenergy.service.WorkDeptService;
import cn.wisenergy.service.WorkSubmitAdoptService;
import cn.wisenergy.service.WorkUserService;
import cn.wisenergy.service.utils.UserRoleLevelUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 *
 * @author chenqi
 * @since 2021-01-19
 */
@Service
@Slf4j
public class WorkUserServiceImpl implements WorkUserService {
    @Autowired
    private WorkUserMapper workUserMapper;

    @Autowired
    private WorkSubmitAdoptService workSubmitAdoptService;

    @Autowired
    private WorkDeptService workDeptService;

    @Autowired
    private WorkRoleMapper workRoleMapper;

    @Autowired
    private WorkUserRoleMapper workUserRoleMapper;

    private static final String LOGIN_SOURCE = "PC";

    // 用户在职状态码
    private static final Integer ON_THE_JOB_STATUS = 1;


    @Override
    public WorkUser getById(Integer id) {
        log.info("WorkUserServiceImpl[]getById[]input.param.id:{}" + id);
        if (null == id) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkUser workUser = workUserMapper.selectById(id);
        if (null == workUser) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_USER_INFO_FAIL);
        }
        return workUser;
    }

    @Override
    public WorkUser getDeptManagerByIds(List<Integer> ids) {
        log.info("WorkUserServiceImpl[]getDeptManagerByIds[]input.param.ids:{}" + ids);
        if (CollectionUtils.isEmpty(ids)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        QueryWrapper<WorkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("level", 2);
        wrapper.in("id", ids);
        return workUserMapper.selectOne(wrapper);

    }

    @Override
    public ResultUser changePassword(Integer userId, String oldPassword, String newPassword) {
        log.info("WorkUserServiceImpl[]changePassword[]input.param{}" + userId + oldPassword + newPassword);
        if (userId == null || StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }

        //新密码与旧密码相同
        if (oldPassword.equals(newPassword)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.NEW_PASSWORD_IS_HTE_SAME_OLD_PASSWORD);
        }
        //根据主键和密码查找
        Map<String, Object> map = new HashMap<>();
        map.put("id", userId);
        map.put("password", Md5Util.digestMD5(oldPassword));
        WorkUser user = workUserMapper.getUserInfo(map);
        if (user == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.UPDATE_PASSWORD_FAIL_OLD_PASSWORD_ERROR);
        }
        //更新信息
        user.setPassword(Md5Util.digestMD5(newPassword));
        Integer count = workUserMapper.updateUserInfo(user);
        if (count == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.USER_UPDATE_PASSWORD_FAIL);
        }
        return getResultUser(user);
    }

    @Override
    public List<OrganizationStructureDto> getOrganizationStructure() {
        log.info("WorkUserServiceImpl[]getOrganizationStructure[]");
        List<OrganizationStructureDto> allDeptByAllCentreId = workDeptService.getAllDeptByAllCentreId();
        QueryWrapper<WorkUser> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        List<WorkUser> workUsers = workUserMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(workUsers)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.DEPT_NOT_HAVE_USER);
        }

        ResultUser resultUser;
        for (OrganizationStructureDto organizationStructureDto : allDeptByAllCentreId) {
            List<DeptUserDto> deptUserDtos = organizationStructureDto.getDeptUserDtos();
            for (DeptUserDto deptUserDto : deptUserDtos) {
                List<ResultUser> ResultUsers = new ArrayList<>();
                for (WorkUser workUser : workUsers) {
                    if (workUser.getDeptId().equals(deptUserDto.getDeptId())) {
                        resultUser = getResultUser(workUser);
                        ResultUsers.add(resultUser);
                    }
                }
                deptUserDto.setResultUsers(ResultUsers);
            }
        }
        return allDeptByAllCentreId;
    }

    @Override
    public AllRoleAndUserRoleDto getUserRoleDto(Integer userId,Integer page, Integer pageSize) {
        log.info("WorkUserServiceImpl[]getUserRoleDto[]input.param.userId:{},page:{},pageSize:{}" + userId, page, pageSize);
        if (!UserRoleLevelUtils.isManagerLevel(userId, LevelEnum.ACCOUNTMANAGEMENT.getLevelName())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
        }
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        Page<UserRoleDto> startPage = PageHelper.startPage(page, pageSize);
        List<UserRoleDto> userRoleDtos = workUserMapper.getUserRoleDto();
        if (CollectionUtils.isEmpty(userRoleDtos)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_DATA_IS_NULL);
        }
        List<WorkRole> workRoles = new ArrayList<>();
        WorkRole workRole = workRoleMapper.selectById(0);
        workRoles.add(workRole);
        for (UserRoleDto userRoleDto : userRoleDtos) {
            if (CollectionUtils.isEmpty(userRoleDto.getWorkRoles())) {
                userRoleDto.setWorkRoles(workRoles);
            }
        }
        PageInfo<UserRoleDto> pageInfo = startPage.toPageInfo();
        pageInfo.setList(userRoleDtos);
        List<WorkRole> allWorkRole = UserRoleLevelUtils.getAllWorkRole();
        if (CollectionUtils.isEmpty(allWorkRole)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_DATA_IS_NULL);
        }

        PageHelper.startPage(page, pageSize);
        AllRoleAndUserRoleDto allRoleAndUserRoleDto = new AllRoleAndUserRoleDto();
        allRoleAndUserRoleDto.setPageInfo(pageInfo);
        allRoleAndUserRoleDto.setWorkRoles(allWorkRole);
        return allRoleAndUserRoleDto;
    }

    @Transactional
    @Override
    public Boolean modifyRole(Integer userId, List<Integer> roleIds) {
        log.info("WorkUserServiceImpl[]modifyRole[].input.param.userId:{},roleIds:{}" + userId, roleIds);
        WorkUser workUser = workUserMapper.selectById(userId);
        if (null == workUser) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_DATA_IS_NULL);
        }
        workUserRoleMapper.deleteByUserId(userId);
        if (1 == roleIds.size() && 0 == roleIds.get(0)) {
            return true;
        }
        if (roleIds.size() > 1) {
            for (Integer roleId : roleIds) {
                if (roleId == 0) {
                    throw new BaseCustomException(BASE_RESP_CODE_ENUM.ORDINARY_MEMBERS_ARE_MANAGEMENT);
                }
            }
        }

        workUserRoleMapper.insertBatch(userId, roleIds);
        return true;
    }

    @Override
    public ResultUser login(String loginName, String password, String source) {
        log.info("WorkUserServiceImpl[]login[].input.param" + loginName + password + source);
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        //MD5加密
        String md5Password = Md5Util.digestMD5(password);

        HashMap<String, Object> map = new HashMap<>();
        map.put("loginName", loginName);
        map.put("password", md5Password);
        WorkUser user = workUserMapper.getUserInfo(map);
        if (null == user) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.USER_LOGIN_NAME_OR_PASSWORD_IS_ERROR);
        }
        // 是否离职状态
        if (user.getStatus() != ON_THE_JOB_STATUS) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.LEAVE_JOB_USER);
        }

        // 如果登录来源是PC,判断用户是不是管理员
        List<Integer> roles = UserRoleLevelUtils.getRole(user.getId());
        if (LOGIN_SOURCE.equals(source)) {
            if (roles.contains(ManagerEnum.NOT_MANAGER.getCode())) {
                throw new BaseCustomException(BASE_RESP_CODE_ENUM.THE_USER_NOT_MANAGER_PLASE_MANAGER_LOGIN);
            }
        }
        // 限制审核的天数
        WorkSubmitAdopt byId = workSubmitAdoptService.getById(1);

        //将用户对象转换为dto
        ResultUser resultUser = getResultUser(user);
        resultUser.setDay(byId.getSubmitTime());
        List<Integer> levelIds = UserRoleLevelUtils.getlevelIds(roles);
        resultUser.setWorkLevels(UserRoleLevelUtils.getlevelByIds(levelIds));
        return resultUser;
    }

    @Override
    public ResultUser getResultUserById(Integer userId) {
        log.info("UserServiceImpl[]getUserById[]input.param.userId" + userId);
        if (null == userId) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
        }
        WorkUser user = workUserMapper.getUserById(userId);
        //查询失败
        if (null == user) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_USER_INFO_FAIL);
        }
        ResultUser resultUser = getResultUser(user);
        log.info("UserServiceImpl[]getUserById[]get.user.info.success");
        return resultUser;
    }

    //获取用户传输实体
    private ResultUser getResultUser(WorkUser workUser) {
        log.info("WorkUSerServiceImpl[]getResultUser[]input.method");
        ResultUser resultUser = new ResultUser();
        try {
            BeanUtils.copyProperties(resultUser, workUser);
        } catch (Exception e) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.QUERY_USER_INFO_FAIL);
        }
        return resultUser;
    }
}
