package com.reyun.saas.mob.openapi.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.reyun.saas.common.constants.RoleEnumType;
import com.reyun.saas.common.exception.CustomException;
import com.reyun.saas.common.model.Constant;
import com.reyun.saas.common.restResult.ResultCode;
import com.reyun.saas.common.util.DingDingSendMsgUtil;
import com.reyun.saas.mob.openapi.dao.CollaborativeProjectUserMapper;
import com.reyun.saas.mob.openapi.domain.CollaborativeProject;
import com.reyun.saas.mob.openapi.domain.CollaborativeProjectUser;
import com.reyun.saas.mob.openapi.dto.SignupDTO;
import com.reyun.saas.mob.openapi.service.OpenApiUserService;
import com.reyun.saas.mob.user.dao.UserAndRoleMapper;
import com.reyun.saas.mob.user.dao.UserCoreConfigMapper;
import com.reyun.saas.mob.user.dao.UserMapper;
import com.reyun.saas.mob.user.domain.User;
import com.reyun.saas.mob.user.domain.UserAndRole;
import com.reyun.saas.mob.user.domain.UserCoreConfig;
import com.reyun.saas.mob.util.IPAddrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: hanzepeng
 * @Date: 2022/02/09/13:56
 * @Description: openApi用户业务层
 */
@Slf4j
@Service
@Transactional
public class OpenApiUserServiceImpl implements OpenApiUserService {

    @Autowired
    private CollaborativeProjectUserMapper projectUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserCoreConfigMapper coreConfigMapper;

    @Autowired
    private UserAndRoleMapper userAndRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value("${spring.profiles.active}")
    private String env;

    /**
     * openApi注册用户
     */
    @Override
    public User signup(SignupDTO signupDTO, CollaborativeProject project, HttpServletRequest request) {

            //校验邮箱是否存在
            Example example = new Example(User.class);
            example.and().andEqualTo("username", signupDTO.getUsername());
            example.and().andEqualTo("delFlag", false);
            User userName = userMapper.selectOneByExample(example);
            if (userName != null) {
                throw new CustomException(ResultCode.OPENAPI_EMAIL_ALREADY_EXISTED);
            }

            User user = new User();
            if (!StringUtils.isEmpty(signupDTO.getPhone())) {
                user.setPhone(signupDTO.getPhone());//手机号
            }
            if (!StringUtils.isEmpty(signupDTO.getQq())) {
                user.setQq(signupDTO.getQq());//QQ
            }
            if (!StringUtils.isEmpty(signupDTO.getWechat())) {
                user.setWechat(signupDTO.getWechat());//微信
            }
            if (!StringUtils.isEmpty(signupDTO.getActualName())) {
                user.setActualName(signupDTO.getActualName());//昵称
            }
            user.setUsername(signupDTO.getUsername());//邮箱(唯一的)
            user.setPassword(passwordEncoder.encode(signupDTO.getPassword()));
            user.setCreateUser(-1L);//创建人
            user.setCreateTime(new Date());//创建时间
            user.setOid(SecureUtil.md5(user.getUsername() + user.getCreateTime().getTime()));//oid
            user.setSex(1);//性别
            user.setCompany(signupDTO.getCompany());//公司
            user.setHeadPortrait("avatar" + RandomUtil.randomInt(1, 27));//随机生存头像  头像在数据库中格式: avater+ 1 ~ 26数字
            user.setStatus(Constant.STATUS_ENABLE);//通过改接口创建的用户是已审核的状态
            user.setRootParent(0L);//主账号id
            user.setRoleCategory(RoleEnumType.SUPER_USER.getKey());//用户角色
            user.setIsCreateApp(true);//创建app的权限
            user.setAuthConfig(true);//是否拥有权限
            user.setDelFlag(false);//删除表示
            user.setLeaderParent(0L);//父用户id
            user.setUserSource(project.getProjectName());//用户来源
            userMapper.insertSelective(user);

            //保存合作项目与用户关系
            CollaborativeProjectUser projectUser = new CollaborativeProjectUser();
            projectUser.setUserId(user.getId());
            projectUser.setProjectId(project.getId());
            projectUserMapper.insertSelective(projectUser);
            //保存用户配置
            saveUserConfig(user);
            //保存成功之后发送钉钉
            pushUserInfo(user,project,request);

        return user;
    }

    /**
     * 保存用户配置
     */
    private void saveUserConfig(User user){
        UserCoreConfig coreConfig = new UserCoreConfig();
        coreConfig.setRtaipNum(20);//rta白名单上限
        coreConfig.setCreateTime(DateUtil.now());//创建时间
        coreConfig.setRootParent(user.getId());//主用户id
        coreConfig.setCreateUser(-1L); //创建人
        coreConfig.setPackageLevelId(100); //用户套餐
        coreConfig.setPubDate(DateUtil.today());//开通时间
        coreConfig.setTrackFlow(0L);//自定义流量上限
        coreConfig.setAppNum(0);//自定义最大app数量上限

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.YEAR,10);
        coreConfig.setPastDate(DateUtil.format(instance.getTime(),"yyyy-MM-dd")); //到期时间
        coreConfigMapper.insertSelective(coreConfig);

        //保存用户与角色对应关系
        UserAndRole userAndRole = new UserAndRole();
        userAndRole.setRoleId(0L);
        userAndRole.setUserId(user.getId());
        userAndRoleMapper.insertSelective(userAndRole);
    }

    /**
     * 将用户注册信息推送钉钉
     */
    @Async
    public void pushUserInfo(User user,CollaborativeProject project,HttpServletRequest request) {
        if (env.equals("pro")) {//生产环境生效
            StringBuilder sb = new StringBuilder("公司：");
            sb.append(user.getCompany()).append("\n")
                    .append("用户来源: ").append(project.getProjectName()).append("\n")
                    .append("邮箱：").append(user.getUsername()).append("\n")
                    .append("姓名：").append(user.getActualName()).append("\n")
                    .append("电话：").append(user.getPhone()).append("\n")
                    .append("微信：").append(user.getWechat()).append("\n")
                    .append("QQ：").append(user.getQq()).append("\n")
                    .append("IP归属地：").append(IPAddrUtil.getLocationFromIpAddr(request));
//            sb.append("开发测试 无视即可");
            DingDingSendMsgUtil dingDingSendMsgUtil = new DingDingSendMsgUtil(DingDingSendMsgUtil.TOKEN_USER_REG_MSG, DingDingSendMsgUtil.KEY_USER_REG_MSG);
            dingDingSendMsgUtil.sendMsg(sb.toString());
        }
    }


    /**
     * 查询合作项目创建的用户
     */
    @Override
    public List<User> findUsers(CollaborativeProject project) {
        List<User> result = null;
        //查询合作项目与用户对应关系表
        Example example = new Example(CollaborativeProjectUser.class);
        example.and().orEqualTo("projectId",project.getId());
        List<CollaborativeProjectUser> projectUsers = projectUserMapper.selectByExample(example);
        if(!CollectionUtils.isEmpty(projectUsers)){
            List<Long> userIds =
                    projectUsers.stream().map(CollaborativeProjectUser::getUserId).collect(Collectors.toList());
            //查询用户
            Example userExample = new Example(User.class);
            userExample.and().andIn("id",userIds);
            userExample.and().orEqualTo("delFlag",false);
            userExample.and().orEqualTo("roleCategory",RoleEnumType.SUPER_USER.getKey());
            result = userMapper.selectByExample(userExample);
        }
        return result;
    }

}
