package com.xhpc.activity.service.impl;

import com.xhpc.activity.domain.SysUserRoleDomain;
import com.xhpc.activity.domain.XhpcWorkDeptDomain;
import com.xhpc.activity.domain.XhpcWorkUserDomain;
import com.xhpc.activity.mapper.SysUserMapper;
import com.xhpc.activity.mapper.SysUserRoleMapper;
import com.xhpc.activity.mapper.XhpcWorkDeptMapper;
import com.xhpc.activity.mapper.XhpcWorkUserMapper;
import com.xhpc.activity.service.WorkUserService;
import com.xhpc.activity.vo.SysUserResetPasswordVo;
import com.xhpc.common.core.exception.CustomException;
import com.xhpc.common.core.utils.SecurityUtils;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.system.api.domain.SysUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class WorkUserServiceImpl implements WorkUserService {

    @Resource
    XhpcWorkUserMapper workUserMapper;

    @Resource
    XhpcWorkDeptMapper deptMapper;

    @Resource
    SysUserMapper userMapper;
    @Resource
    SysUserRoleMapper roleMapper;


    @Override
    public Boolean insertUser(String userName, String phone){
        XhpcWorkUserDomain domain = new XhpcWorkUserDomain();
        domain.setUserName(userName);
        domain.setPhone(phone);
        return workUserMapper.insert(domain) > 0;
    }


    @Override
    public XhpcWorkUserDomain insertUserReturnDomain(String userName, String phone){
        insertUser(userName, phone);

        return workUserMapper.selectByUserNameAndPhone(userName, phone);
    }


    @Override
    public List<Map<String, Object>> getDeptAndUserByMap(Map<String, Object> params){
        List<Map<String, Object>> deptDomains = deptMapper.selectMapListByParams(params);
        for(Map<String, Object> deptMap: deptDomains){
            String deptId = deptMap.get("id") + "";
            if(StringUtils.isNotEmpty(deptId)){
                deptId = deptId.replaceAll("d_", "");
            }

            List<Map<String, Object>> users = workUserMapper.selectMapListByDeptId(deptId);
            if(users.size() > 0){
                deptMap.put("users", users);
            }
        }
        return deptDomains;
    }


    @Override
    public XhpcWorkUserDomain findByPk(Long pk){
        return workUserMapper.selectByPrimaryKey(pk);
    }


    @Override
    public   List<XhpcWorkUserDomain> findByOrderId(Long orderId){
        return workUserMapper.selectByOrderId(orderId);
    }


    @Override
    public List<XhpcWorkUserDomain> getPage(Map<String, Object> params){
        Map<String, Object> deptParams = new HashMap<>();
        deptParams.put("tenantId", params.get("tenantId"));
        if (params.get("deptId") != null){
            String deptIds = params.get("deptId") + "";
            for(int i=0; i< 3;i++){
                deptParams.put("parentDeptIds", deptIds);
                List<XhpcWorkDeptDomain> deptDomainList = deptMapper.selectListByParams(deptParams);
                for(XhpcWorkDeptDomain workDeptDomain: deptDomainList){
                    deptIds = deptIds + "," + workDeptDomain.getWorkDeptId();
                }
            }
            params.put("deptIds", deptIds);
        }
        if(params.get("deptIds") != null){
            params.put("deptId", null);
        }
        return workUserMapper.selectPage(params);
    }


    @Override
    public List<Map<String, Object>> getList(Map<String, Object> params){
        return workUserMapper.selectMapList(params);
    }

    @Override
    public List<Map<String, Object>> getTree(Map<String, Object> params){
        return workUserMapper.selectMapList(params);
    }

    @Override
    public Boolean insertDomain(XhpcWorkUserDomain domain){

        // todo 需要再sys_user中增加相关信息
        if(domain.getRoleIds().length==0){
            throw new CustomException("请选择角色");
        }
        int count = userMapper.checkUserNameUnique(domain.getLoginName(), domain.getTenantId());
        if(count > 0){
            throw new CustomException("新增用户'" + domain.getLoginName() + "'失败，登录账号已存在");
        }

        SysUser sysUser = userMapper.checkPhoneUnique(domain.getPhone(), domain.getTenantId());
        if(StringUtils.isNotNull(sysUser)){
            throw new CustomException("新增用户'" + domain.getUserName() + "'失败，手机号码已存在");
        }

        XhpcWorkDeptDomain deptDomain = deptMapper.selectByPrimaryKey(domain.getDeptId());
        if (deptDomain == null || !deptDomain.getType().equals(domain.getType())){
            throw new CustomException("所属部门不存在或部门类型与人员不一致");
        }

        workUserMapper.insert(domain);

        SysUser user = new SysUser();
        getUserConvert(user, domain);
        userMapper.insertUser(user);

        Long[] roles = domain.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRoleDomain> list = new ArrayList<SysUserRoleDomain>();
            for (Long roleId : roles)
            {
                SysUserRoleDomain ur = new SysUserRoleDomain();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                roleMapper.batchUserRole(list);
            }
        }
        return true;
    }

    @Override
    public Boolean updateDomain(XhpcWorkUserDomain domain){

        SysUser user =  userMapper.selectUserByUserName(domain.getLoginName(), domain.getTenantId());
//        SysUser sysUser = userMapper.checkPhoneUnique(domain.getPhone(), domain.getTenantId());
//        if(StringUtils.isNotNull(sysUser)){
//            throw new CustomException("更新用户'" + domain.getUserName() + "'失败，手机号码已存在");
//        }

        user.setPhonenumber(domain.getPhone());
        user.setEmail(domain.getEmail());

        workUserMapper.updateByPrimaryKey(domain);
        userMapper.updateUser(user);
        return true;
    }


    @Override
    public Boolean updateDomainStatus(XhpcWorkUserDomain domain){
        SysUser user =  userMapper.selectUserByWorkUserId(domain.getWorkUserId().toString(), domain.getTenantId());
        if(StringUtils.isNull(user)){
            throw new CustomException("系统用户不存在");
        }
        switch (domain.getStatus()){
            case 0:
                user.setStatus("1"); break;
            case 1:
                user.setStatus("0"); break;
            default:break;
        }
        userMapper.updateUserStatus(user);
        return workUserMapper.updateDomainStatusByPrimaryKey(domain) > 0;
    }

    @Override
    public Boolean resetPassword(SysUserResetPasswordVo vo){
        SysUser user =  userMapper.selectUserByUserName(vo.getLoginName(), vo.getTenantId());
        if(StringUtils.isNull(user)){
            throw new CustomException("用户不存在");
        }

        userMapper.resetUserPwd(vo.getLoginName(), SecurityUtils.encryptPassword(vo.getPassword()));
        return true;
    }



    @Override
    public Boolean deleteDomain(Long userId){
        XhpcWorkUserDomain workUserDomain = workUserMapper.selectByPrimaryKey(userId);
        if(StringUtils.isNull(workUserDomain)){
            throw new CustomException("用户不存在");
        }
        SysUser user =  userMapper.selectUserByUserName(workUserDomain.getLoginName(), workUserDomain.getTenantId());
        if(StringUtils.isNotNull(user)){
            userMapper.deleteUserById(user.getUserId());
        }

        return workUserMapper.deleteLogicByPrimaryKey(userId) > 0;
    }


    @Override
    public String getPhoneListByUserIds(String userIds){
        if(StringUtils.isEmpty(userIds)){
            return "";
        }

        return workUserMapper.selectPhoneListByIds(userIds);
    }


    @Override
    public List<XhpcWorkUserDomain> getUserListByDeptId(Long deptId){
        return workUserMapper.selectListByDeptId(deptId);
    }


    private void getUserConvert(SysUser user, XhpcWorkUserDomain domain){
        user.setUserName(domain.getLoginName());
        user.setNickName(domain.getUserName());
        user.setUserType("04");
        user.setEmail(domain.getEmail());
        user.setPhonenumber(domain.getPhone());
        user.setDataPowerType(0);
        switch (domain.getStatus()){
            case 0: user.setStatus("1"); break;
            case 1: user.setStatus("0"); break;
            default: user.setStatus("0");break;
        }
        user.setAvatar("https://xhpc-bucket1.oss-cn-hangzhou.aliyuncs.com/avatar/logo.png");
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(domain.getLoginPassword()));
        user.setTenantId(domain.getTenantId());
        user.setCreateBy(domain.getCreateBy());
        user.setCreateTime(new Date());
        user.setUpdateBy(domain.getUpdateBy());
        user.setUpdateTime(new Date());
    }

}
