package com.sqx.modules.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushChannel;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.getui.push.v2.sdk.dto.req.message.ios.Alert;
import com.getui.push.v2.sdk.dto.req.message.ios.Aps;
import com.getui.push.v2.sdk.dto.req.message.ios.IosDTO;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.MsgDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.*;
import com.sqx.modules.app.form.UpdateUserTypeForm;
import com.sqx.modules.app.service.MsgService;
import com.sqx.modules.app.service.UserBrowseService;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.app.utils.UserConstantInterface;
import com.sqx.modules.chat.entity.ChatContent;
import com.sqx.modules.chat.entity.ChatConversation;
import com.sqx.modules.chat.service.ChatContentService;
import com.sqx.modules.chat.service.ChatConversationService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.file.utils.Md5Utils;
import com.sqx.modules.interviewRecord.entity.InterviewRecord;
import com.sqx.modules.interviewRecord.service.InterviewRecordService;
import com.sqx.modules.invite.service.InviteService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.myCollection.entity.MyCollection;
import com.sqx.modules.myCollection.service.MyCollectionService;
import com.sqx.modules.resumes.entity.Company;
import com.sqx.modules.resumes.service.CompanyService;
import com.sqx.modules.sendRecord.entity.SendRecord;
import com.sqx.modules.sendRecord.service.SendRecordService;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.InvitationCodeUtil;
import com.sqx.modules.utils.excel.ExcelData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import weixin.popular.api.SnsAPI;
import weixin.popular.util.JsonUtil;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 用户
 *
 * @author fang
 * @date 2021/2/27
 */

@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private JwtUtils jwtUtils;
    private int number = 1;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private MyCollectionService collectionService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserBrowseService userBrowseService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SendRecordService sendRecordService;
    @Autowired
    private UserMoneyDetailsService detailsService;
    @Autowired
    private UserMoneyDetailsDao detailsDao;
    @Autowired
    private MsgService msgService;
    @Autowired
    private ChatConversationService chatConversationService;
    @Autowired
    private ChatContentService chatContentService;
    @Autowired
    private InterviewRecordService interviewRecordService;

    @Override
    public UserEntity queryByPhone(String phone) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("phone", phone));
    }

    @Override
    public UserEntity queryByOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("open_id", openId));
    }

    @Override
    public UserEntity queryByShopOpenId(String shopOpenId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("shop_open_id", shopOpenId));
    }

    @Override
    public UserEntity queryByWxOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("wx_open_id", openId));
    }

    @Override
    public UserEntity queryByAppleId(String appleId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("apple_id", appleId));
    }

    @Override
    public UserEntity queryByUserId(Long userId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_id", userId));
    }

    @Override
    public UserEntity queryByInvitationCode(String invitationCode) {
        UserEntity user = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("invitation_code", invitationCode));
        if (user != null) {
            if (user.getZhiRate() == null) {
                user.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue()));
            }
            if (user.getFeiRate() == null) {
                user.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue()));
            }
            baseMapper.updateById(user);
        }
        return user;
    }

    @Override
    public Result updatePhone(String phone, String msg, Long userId) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 != null) {
            UserEntity userInfo = queryByPhone(phone);
            if (userInfo != null) {
                return Result.error("手机号已经被其他账号绑定");
            } else {
                UserEntity one = baseMapper.selectById(userId);
                one.setPhone(phone);
                baseMapper.updateById(one);
                return Result.success();
            }
        }
        return Result.error("验证码不正确");
    }

    @Override
    public Result iosRegister(String appleId) {
        if (StringUtils.isEmpty(appleId)) {
            return Result.error("账号信息获取失败，请退出重试！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        UserEntity userInfo = queryByAppleId(appleId);
        if (userInfo != null) {
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被封禁，请联系客服处理！");
            }
            userInfo.setUpdateTime(date);
            baseMapper.updateById(userInfo);
            //返回用户信息
            UserEntity user = queryByAppleId(appleId);
            return getResult(user);
        } else {
            return Result.error(-200, "请先绑定手机号账号！");
        }
    }

    @Override
    public Result wxLogin(String code, Integer type) {
        try {
            String appid;
            String secret;
            //微信小程序APPID
            appid = commonInfoService.findOne(45).getValue();
            //微信小程序秘钥
            secret = commonInfoService.findOne(46).getValue();
            // 配置请求参数
            Map<String, String> param = new HashMap<>();
            param.put("appid", appid);
            param.put("secret", secret);
            param.put("js_code", code);
            param.put("grant_type", UserConstantInterface.WX_LOGIN_GRANT_TYPE);
            param.put("scope", "snsapi_userinfo");
            // 发送请求
            String wxResult = HttpClientUtil.doGet(UserConstantInterface.WX_LOGIN_URL, param);
            log.info(wxResult);
            JSONObject jsonObject = JSONObject.parseObject(wxResult);
            // 获取参数返回的
            String session_key = jsonObject.get("session_key").toString();
            //返回微信小程序openId
            String open_id = jsonObject.get("openid").toString();
            Map<String, String> map = new HashMap<>();
            //判断是否注册过
            UserEntity userEntity = queryByOpenId(open_id);
            if (userEntity != null) {
                map.put("flag", "1");
            } else {
                map.put("flag", "2");
            }

            // 封装返回小程序
            map.put("session_key", session_key);
            map.put("open_id", open_id);
            if (jsonObject.get("unionid") != null) {
                String unionid = jsonObject.get("unionid").toString();
                map.put("unionid", unionid);
            } else {
                map.put("unionid", "-1");
            }


            return Result.success("登陆成功").put("data", map);
        } catch (Exception e) {
            System.err.println(e.toString());
            return Result.success("登录失败！");
        }
    }


    @Override
    public Result wxRegister(UserEntity userInfo1) {
        if (StringUtils.isEmpty(userInfo1.getOpenId())) {
            return Result.error("账号信息获取失败，请退出重试！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sdf.format(new Date());
        // 根据返回的user实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库
        UserEntity userInfo;
        userInfo = queryByOpenId(userInfo1.getOpenId());

        if (userInfo != null) {
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被封禁，请联系客服处理！");
            }
            if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                userInfo.setPhone(userInfo1.getPhone());
            }
            userInfo.setUpdateTime(date);
            baseMapper.updateById(userInfo);
        } else {
            //判断是否在app登陆过  手机号是否有账号
            UserEntity userByMobile = queryByPhone(userInfo1.getPhone());
            if (userByMobile != null) {
                //有账号则绑定账号
                userByMobile.setOpenId(userInfo1.getOpenId());
                if (StringUtils.isBlank(userByMobile.getAvatar())) {
                    userByMobile.setAvatar(userInfo1.getAvatar());
                }
                baseMapper.updateById(userByMobile);
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("小程序账号绑定成功！");
                messageInfo.setTitle("系统通知");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(userByMobile.getUserName());
                messageInfo.setUserId(String.valueOf(userByMobile.getUserId()));
                messageInfo.setCreateAt(sdf.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);
                if (userByMobile.getStatus().equals(2)) {
                    return Result.error("账号已被封禁，请联系客服处理！");
                }
                baseMapper.updateById(userByMobile);
            } else {
                //没有则生成新账号
                userInfo1.setCreateTime(date);
                userInfo1.setPlatform("小程序");
                userInfo1.setStatus(1);
                userInfo1.setInvitationCode(InvitationCodeUtil.toSerialCode());
                if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                    userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getPhone()));
                } else {
                    userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getOpenId()));
                }
                if (StringUtils.isNotBlank(userInfo1.getInviterCode())) {
                    UserEntity userEntity = queryByInvitationCode(userInfo1.getInviterCode());
                    if (userEntity != null) {
                        userInfo1.setInviterCode(userInfo1.getInviterCode());
                        //判断邀请员是否有上级
                        UserEntity parentParentUser = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", (userEntity.getInviterCode())));
                        if (parentParentUser != null) {
                            userInfo1.setInviterInviterCode(parentParentUser.getInvitationCode());
                        }
                    } else {
                        return Result.error("邀请码不存在");
                    }
                }
                userInfo1.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue()));
                userInfo1.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue()));
                baseMapper.insert(userInfo1);
                //给用户创建钱包
                UserMoney userMoney = new UserMoney();
                userMoney.setUserId(userInfo1.getUserId());
                userMoney.setMoney(BigDecimal.valueOf(0));
                userMoney.setCustomizationMoney(BigDecimal.valueOf(0));
                userMoneyDao.insert(userMoney);
                //赠送钻石数
                String give = commonInfoService.findOne(424).getValue();
                if (StringUtils.isNotBlank(give)) {
                    userMoney.setMoney(userMoney.getMoney().add(new BigDecimal(give)));
                    userMoneyDao.updateById(userMoney);
                }
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("恭喜您，账号注册成功！");
                messageInfo.setTitle("系统通知");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(userInfo1.getUserName());
                messageInfo.setUserId(String.valueOf(userInfo1.getUserId()));
                messageInfo.setCreateAt(sdf.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);
                UserEntity userEntity = queryByInvitationCode(userInfo1.getInviterCode());
                if (userEntity != null) {
                    inviteService.saveBody(userInfo1.getUserId(), userEntity);
                }
            }
        }
        //返回用户信息
        UserEntity user;
        user = queryByOpenId(userInfo1.getOpenId());
        return getResult(user);
    }


    @Override
    public Result wxBindMobile(String phone, String code, String wxOpenId, String token, String platform, Integer sysPhone) {
        Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code);
        if (byPhoneAndCode == null) {
            return Result.error("验证码错误");
        }
        msgDao.deleteById(byPhoneAndCode.getId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            if (StringUtils.isNotEmpty(userInfo.getWxOpenId())) {
                return Result.error("当前手机号已经被其他微信绑定");
            }
            //小程序登陆过
            userInfo.setWxOpenId(wxOpenId);
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userInfo.setAvatar(user.getHeadimgurl());
                }
                userInfo.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userInfo.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            baseMapper.updateById(userInfo);
        } else {
            //小程序没有登陆过
            userInfo = new UserEntity();
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userInfo.setAvatar(user.getHeadimgurl());
                }
                userInfo.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userInfo.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            userInfo.setWxOpenId(wxOpenId);
            userInfo.setPhone(phone);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setUpdateTime(time);
            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode());
            baseMapper.insert(userInfo);
        }
        UserEntity userEntity = queryByWxOpenId(userInfo.getWxOpenId());
        return getResult(userEntity);
    }

    @Override
    public Result iosBindMobile(String phone, String code, String appleId, String platform, Integer sysPhone) {
        Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, code);
        if (byPhoneAndCode == null) {
            return Result.error("验证码错误");
        }
        msgDao.deleteById(byPhoneAndCode.getId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            if (StringUtils.isNotEmpty(userInfo.getAppleId())) {
                return Result.error("当前手机号已经被其他苹果绑定");
            }
            userInfo.setAppleId(appleId);
            userInfo.setUpdateTime(simpleDateFormat.format(new Date()));
            baseMapper.updateById(userInfo);
        } else {
            userInfo = new UserEntity();
            userInfo.setSex(0);
            userInfo.setUserName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            userInfo.setPhone(phone);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setUpdateTime(time);
            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode());
            baseMapper.insert(userInfo);
        }
        UserEntity userEntity = queryByAppleId(userInfo.getAppleId());
        return getResult(userEntity);
    }


    @Override
    public Result wxAppLogin(String wxOpenId, String token) {
        UserEntity userEntity = queryByWxOpenId(wxOpenId);
        if (userEntity != null) {
            if (userEntity.getStatus().equals(2)) {
                return Result.error("账号已被禁用，请联系客服处理！");
            }
            String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + wxOpenId);
            AppUserInfo user = JsonUtil.parseObject(s, AppUserInfo.class);
            if (user != null && user.getNickname() != null) {
                if (user.getHeadimgurl() != null) {
                    userEntity.setAvatar(user.getHeadimgurl());
                }
                userEntity.setSex(user.getSex());
                if (user.getNickname() != null) {
                    userEntity.setUserName(user.getNickname().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userEntity.setUpdateTime(sdf.format(new Date()));
            baseMapper.updateById(userEntity);
            return getResult(userEntity);
        } else {
            return Result.error(-200, "请先绑定手机号账号！");
        }
    }


    @Override
    public Result loginByOpenId(String openId) {
        UserEntity userEntity = queryByWxOpenId(openId);
        if (userEntity == null) {
            return Result.error(-200, "未注册！");
        }
        String token = jwtUtils.generateToken(userEntity.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", userEntity);
        return Result.success(map);
    }


    @Override
    public Result registerCode(String phone, String msg, String platform, Integer sysPhone, String openId, String inviterCode) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 == null) {
            return Result.error("验证码不正确");
        }
        msgDao.deleteById(msg1.getId());
        //校验手机号是否存在
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            if (userInfo.getStatus().equals(2)) {
                return Result.error("账号已被禁用，请联系客服处理！");
            }
            userInfo.setWxOpenId(openId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setUpdateTime(sdf.format(new Date()));
            baseMapper.updateById(userInfo);
            return getResult(userInfo);
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            userInfo = new UserEntity();
            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode());
            userInfo.setPhone(phone);
            if (StringUtils.isNotBlank(inviterCode)) {
                UserEntity userEntity = queryByInvitationCode(inviterCode);
                if (userEntity != null) {
                    userInfo.setInviterCode(inviterCode);
                    //判断邀请员是否有上级
                    UserEntity parentParentUser = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", (userEntity.getInviterCode())));
                    if (parentParentUser != null) {
                        userInfo.setInviterInviterCode(parentParentUser.getInvitationCode());
                    }
                } else {
                    return Result.error("邀请码不存在");
                }
            }
            userInfo.setUserName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setWxOpenId(openId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setUpdateTime(sdf.format(new Date()));
            baseMapper.insert(userInfo);
            msgDao.deleteById(msg1.getId());
            //给用户创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(BigDecimal.valueOf(0));
            userMoney.setCustomizationMoney(BigDecimal.valueOf(0));
            //赠送钻石数
            String give = commonInfoService.findOne(424).getValue();
            if (StringUtils.isNotBlank(give)) {
                userMoney.setMoney(userMoney.getMoney().add(new BigDecimal(give)));
                userMoneyDao.updateById(userMoney);
            }

            userMoneyDao.insert(userMoney);
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("恭喜您，账号注册成功！");
            messageInfo.setTitle("系统通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userInfo.getUserName());
            messageInfo.setUserId(String.valueOf(userInfo.getUserId()));
            messageInfo.setCreateAt(sdf.format(new Date()));
            messageInfo.setIsSee("0");
            messageService.saveBody(messageInfo);
            UserEntity userEntity = queryByInvitationCode(userInfo.getInviterCode());
            if (userEntity != null) {
                inviteService.saveBody(userInfo.getUserId(), userEntity);
            }
            return getResult(userInfo);
        }
    }


    @Override
    public Result login(String phone, String pwd) {
        UserEntity userEntity = queryByPhone(phone);
        if (userEntity == null) {
            return Result.error("手机号未注册！");
        }
        if (!userEntity.getPassword().equals(DigestUtils.sha256Hex(pwd))) {
            return Result.error("密码不正确！");
        }
        if (userEntity.getStatus().equals(2)) {
            return Result.error("账号已被禁用，请联系客服处理！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userEntity.setUpdateTime(sdf.format(new Date()));
        baseMapper.updateById(userEntity);
        return getResult(userEntity);
    }


    @Override
    public Result getResult(UserEntity user) {
        //生成token
        String token = jwtUtils.generateToken(user.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());
        map.put("user", user);
        return Result.success(map);
    }

    @Override
    public Result sendMsg(String phone, String state) {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        System.out.println("sendMsg code is " + code);
        SmsSingleSenderResult result = null;
        if (phone != null) {
            if ("forget".equals(state)) {
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone == null) {
                    return Result.error("手机号未注册");
                }
            } else if ("bind".equals(state)) {

            } else {
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.error("当前手机号已被其他账号绑定");
                }
            }

        }
        CommonInfo three = commonInfoService.findOne(79);
        //默认使用腾讯云
        if (three == null || "1".equals(three.getValue())) {
            //腾讯云短信发送
            return sendMsgTencent(phone, state, code);
        } else if ("2".equals(three.getValue())) {
            //阿里云短信发送
            return sendMsgAlibaba(phone, code);
        } else {
            return sendMsgDXB(phone, state, code);
        }
    }


    @Override
    public Result sendMsg(String phone, String state, Integer code) {
        CommonInfo three = commonInfoService.findOne(79);
        //默认使用腾讯云
        if (three == null || "1".equals(three.getValue())) {
            //腾讯云短信发送
            return sendMsgTencent(phone, state, code);
        } else if ("2".equals(three.getValue())) {
            //阿里云短信发送
            return sendMsgAlibaba(phone, code);
        } else {
            return sendMsgDXB(phone, state, code);
        }
    }


    private Result sendMsgAlibaba(String phone, int code) {
        //阿里云短信accessKeyId
        CommonInfo three = commonInfoService.findOne(83);
        String accessKeyId = three.getValue();
        //阿里云短信accessSecret
        CommonInfo four = commonInfoService.findOne(84);
        String accessSecret = four.getValue();
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonInfo name = commonInfoService.findOne(6);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", name.getValue());
        String value = commonInfoService.findOne(80).getValue();
        request.putQueryParameter("TemplateCode", value);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            String data = response.getData();
            JSONObject jsonObject = JSON.parseObject(data);
            if ("OK".equals(jsonObject.get("Code"))) {
                Msg byPhone = msgDao.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgDao.updateById(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgDao.insert(msg);
                }
           /*     UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.success("login");
                } else {
                    return Result.success("register");
                }*/
                return Result.success("login");
            } else {
                if (jsonObject.get("Message").toString().contains("分钟")) {
                    return Result.error("短信发送过于频繁，请一分钟后再试！");
                } else if (jsonObject.get("Message").toString().contains("小时")) {
                    return Result.error("短信发送过于频繁，请一小时后再试！");
                } else if (jsonObject.get("Message").toString().contains("天")) {
                    return Result.error("短信发送过于频繁，请明天再试！");
                }
                log.info(jsonObject.get("Message").toString());
                return Result.error("短信发送失败！");
            }
        } catch (ClientException | com.aliyuncs.exceptions.ClientException e) {
            e.printStackTrace();
        }
        return Result.error("验证码发送失败");
    }


    private Result sendMsgTencent(String phone, String state, int code) {
        SmsSingleSenderResult result = null;
        try {
            CommonInfo three = commonInfoService.findOne(31);
            String clientId = three.getValue();

            CommonInfo four = commonInfoService.findOne(32);
            String clientSecret = four.getValue();
            CommonInfo name = commonInfoService.findOne(6);
            /**
             * 发送短信验证码的状态、
             *
             * 在h5登录环境中 传的状态不是以下三种状态
             */
            SmsSingleSender ssender = new SmsSingleSender(Integer.valueOf(clientId), clientSecret);
            switch (state) {
                case "register":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "forget":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行找回密码操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "bind":
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
                case "dx":
                    result = ssender.send(0, "86", phone, "您有" + code + "条未读消息，赶快上线查看吧！", "", "");
                    break;
                default:
                    result = ssender.send(0, "86", phone, "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息", "", "");
                    break;
            }


            System.out.println(result);
            if (result.result == 0) {
                Msg byPhone = msgDao.findByPhone(phone);
                if (byPhone != null) {
                    byPhone.setCode(String.valueOf(code));
                    byPhone.setPhone(phone);
                    msgDao.updateById(byPhone);
                } else {
                    Msg msg = new Msg();
                    msg.setCode(String.valueOf(code));
                    msg.setPhone(phone);
                    msgDao.insert(msg);
                }
                UserEntity userByPhone = queryByPhone(phone);
                if (userByPhone != null) {
                    return Result.success("login");
                } else {
                    return Result.success("register");
                }
            } else {
                return Result.error(6, result.errMsg);
            }
        } catch (HTTPException | JSONException | IOException e) {
            // HTTP 响应码错误
            e.printStackTrace();
        }
        return Result.error("验证码发送失败");
    }


    private Result sendMsgDXB(String phone, String state, int code) {
        CommonInfo three = commonInfoService.findOne(164);
        CommonInfo four = commonInfoService.findOne(165);
        CommonInfo name = commonInfoService.findOne(6);
        String testUsername = three.getValue(); //在短信宝注册的用户名
        String testPassword = four.getValue(); //在短信宝注册的密码
        String value = "";
        switch (state) {
            case "register":
                value = "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "forget":
                value = "【" + name.getValue() + "】您的验证码是" + code + "。如非本人操作，请忽略本短信";
                break;
            case "bind":
                value = "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "dx":
                value = "【" + name.getValue() + "】您有" + code + "条未读消息，赶快上线查看吧！";
                break;
            default:
                value = "【" + name.getValue() + "】验证码: " + code + "，此验证码可用于登录或注册，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
        }
        StringBuilder httpArg = new StringBuilder();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(Md5Utils.md5s(testPassword)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(Md5Utils.encodeUrlString(value, "UTF-8"));
        String result = Md5Utils.request("https://api.smsbao.com/sms", httpArg.toString());
        log.error("短信包返回值：" + result);
        if ("0".equals(result)) {
            Msg byPhone = msgDao.findByPhone(phone);
            if (byPhone != null) {
                byPhone.setCode(String.valueOf(code));
                byPhone.setPhone(phone);
                msgDao.updateById(byPhone);
            } else {
                Msg msg = new Msg();
                msg.setCode(String.valueOf(code));
                msg.setPhone(phone);
                msgDao.insert(msg);
            }
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null) {
                return Result.success("login");
            } else {
                return Result.success("register");
            }
        } else {
//            return ResultUtil.error(6, result.errMsg);
            if ("30".equals(result)) {
                return Result.error("错误密码");
            } else if ("40".equals(result)) {
                return Result.error("账号不存在");
            } else if ("41".equals(result)) {
                return Result.error("余额不足");
            } else if ("43".equals(result)) {
                return Result.error("IP地址限制");
            } else if ("50".equals(result)) {
                return Result.error("内容含有敏感词");
            } else if ("51".equals(result)) {
                return Result.error("手机号码不正确");
            }
        }

        return Result.error("验证码发送失败");
    }


    @Override
    public Result getOpenId(String code, Long userId) {
        try {
            //微信appid
            CommonInfo one = commonInfoService.findOne(5);
            //微信秘钥
            CommonInfo two = commonInfoService.findOne(21);
            String openid = SnsAPI.oauth2AccessToken(one.getValue(), two.getValue(), code).getOpenid();
            if (StringUtils.isNotEmpty(openid)) {
                UserEntity userEntity = new UserEntity();
                userEntity.setUserId(userId);
                userEntity.setOpenId(openid);
                baseMapper.updateById(userEntity);
                return Result.success().put("data", openid);
            }
            return Result.error("获取失败");
        } catch (Exception e) {
            log.error("GET_OPENID_FAIL");
            return Result.error("获取失败,出错了！");
        }
    }

    @Override
    public UserEntity selectUserById(Long userId) {
        UserEntity userEntity = baseMapper.selectById(userId);
        if (userEntity != null) {
            if (userEntity.getUserType() == 2) {
                Company company = companyService.getOne(new QueryWrapper<Company>().eq("user_id", userEntity.getUserId()).eq("status",2));
                if (company != null) {
                    userEntity.setCompanyId(company.getCompanyId());
                }
            }
        }
        return userEntity;
    }


    @Override
    public PageUtils selectUserPage(Integer page, Integer limit, String startTime, String endTime, UserEntity userEntity) {
        Page<UserEntity> pages = new Page<>(page, limit);
        return new PageUtils(baseMapper.selectUserPage(pages, startTime, endTime, userEntity));
    }

    @Override
    public int queryInviterCount(String inviterCode) {
        return baseMapper.queryInviterCount(inviterCode);
    }

    @Override
    public int queryUserCount(int type, String date, Integer userType) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        if (StringUtils.isEmpty(date)) {
            date = simpleDateFormat.format(new Date());
        }
        return baseMapper.queryUserCount(type, date, userType);
    }

    @Override
    public Double queryPayMoney(int type) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        String date = simpleDateFormat.format(new Date());
        return baseMapper.queryPayMoney(type, date);
    }

    @Override
    public IPage<Map<String, Object>> queryCourseOrder(Page<Map<String, Object>> iPage, int type, String date) {
        return baseMapper.queryCourseOrder(iPage, type, date);
    }

    @Override
    public int userMessage(String date, int type) {
        return baseMapper.userMessage(date, type);
    }


    @Override
    public void pushToSingle(String title, String content, String clientId) {
        try {
            if (StringUtils.isNotEmpty(clientId)) {
                UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("clientid", clientId));
                GtApiConfiguration apiConfiguration = new GtApiConfiguration();
                //填写应用配置
                apiConfiguration.setAppId(commonInfoService.findOne(61).getValue());
                apiConfiguration.setAppKey(commonInfoService.findOne(60).getValue());
                apiConfiguration.setMasterSecret(commonInfoService.findOne(62).getValue());
                // 接口调用前缀，请查看文档: 接口调用规范 -> 接口前缀, 可不填写appId
                apiConfiguration.setDomain("https://restapi.getui.com/v2/");
                // 实例化ApiHelper对象，用于创建接口对象
                ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
                // 创建对象，建议复用。目前有PushApi、StatisticApi、UserApi
                PushApi pushApi = apiHelper.creatApi(PushApi.class);
                //根据cid进行单推
                PushDTO<Audience> pushDTO = new PushDTO<Audience>();
                // 设置推送参数
                pushDTO.setRequestId(System.currentTimeMillis() + "");
                PushMessage pushMessage = new PushMessage();
                //安卓推送
                GTNotification notification = new GTNotification();
                pushDTO.setPushMessage(pushMessage);
                // 配置通知栏图标
                notification.setLogo(commonInfoService.findOne(19).getValue() + "/logo.png"); //配置通知栏图标，需要在客户端开发时嵌入，默认为push.png
                // 配置通知栏网络图标
                notification.setLogoUrl(commonInfoService.findOne(19).getValue() + "/logo.png");
                notification.setTitle(title);
                notification.setBody(content);
                notification.setClickType("startapp");
                notification.setUrl(commonInfoService.findOne(19).getValue());
                notification.setChannelLevel("3");
                pushMessage.setNotification(notification);

                // 设置接收人信息
                Audience audience = new Audience();
                audience.addCid(clientId);
                pushDTO.setAudience(audience);
                // 进行cid单推
                ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
                if (apiResult.isSuccess()) {
                    // success
                    log.info("安卓消息推送成功：" + apiResult.getData());
                } else {
                    // failed
                    log.error("安卓消息推送失败：code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());

                    pushMessage.setTransmission(title);
                    pushDTO.setPushMessage(pushMessage);
                    PushChannel pushChannel = new PushChannel();
                    IosDTO iosDTO = new IosDTO();
                    Aps aps = new Aps();
                    Alert alert = new Alert();
                    alert.setTitle(title);
                    alert.setBody(content);
                    aps.setAlert(alert);
                    aps.setSound("default");
                    iosDTO.setAps(aps);
                    pushChannel.setIos(iosDTO);
                    pushDTO.setPushChannel(pushChannel);
                    // 进行cid单推
                    apiResult = pushApi.pushToSingleByCid(pushDTO);
                    if (apiResult.isSuccess()) {
                        // success
                        log.info("苹果消息推送成功：" + apiResult.getData());
                    } else {
                        // failed
                        log.error("苹果消息推送失败：code:" + apiResult.getCode() + ", msg: " + apiResult.getMsg());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息推送异常：" + e.getMessage(), e);
        }
    }

    @Override
    public Result loginApp(String phone, String password) {
        //md5加密
        String pwd = DigestUtils.sha256Hex(password);

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        UserEntity userEntity = baseMapper.selectOne(queryWrapper);
        if (userEntity == null) {
            return Result.error("手机号未注册！");
        }
        if (!userEntity.getPassword().equals(pwd)) {
            return Result.error("密码不正确！");
        }
        if (userEntity.getStatus().equals(2)) {
            return Result.error("账号已被禁用，请联系客服处理！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userEntity.setUpdateTime(sdf.format(new Date()));
        baseMapper.updateById(userEntity);
        return getResult(userEntity);

    }

    @Override
    public Result registApp(String userName, String phone, String password, String msg, String platform, String inviterCode) {
        Msg msg1 = msgDao.findByPhoneAndCode(phone, msg);
        //校验短信验证码
        if (msg1 == null) {
            return Result.error("验证码不正确");
        }
        msgDao.deleteById(msg1.getId());
        //校验手机号是否存在
        UserEntity userInfo = queryByPhone(phone);
        if (userInfo != null) {
            return Result.error("手机号已经被注册！");

        } else {


            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            userInfo = new UserEntity();
            userInfo.setPhone(phone);
            userInfo.setUserName(userName);
            //对密码进行MD5加密
            userInfo.setPassword(DigestUtils.sha256Hex(password));
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setStatus(1);
            UserEntity userEntity = queryByInvitationCode(inviterCode);
            if (StringUtils.isNotBlank(inviterCode)) {
                if (userEntity != null) {
                    userInfo.setInviterCode(inviterCode);
                    //判断邀请员是否有上级
                    UserEntity parentParentUser = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("invitation_code", (userEntity.getInviterCode())));
                    if (parentParentUser != null) {
                        userInfo.setInviterInviterCode(parentParentUser.getInvitationCode());
                    }
                } else {
                    return Result.error("邀请码不存在");
                }
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setCreateTime(sdf.format(new Date()));
            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode());
            baseMapper.insert(userInfo);

            //给用户创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(BigDecimal.valueOf(0));
            userMoney.setCustomizationMoney(BigDecimal.valueOf(0));
            userMoneyDao.insert(userMoney);
            //赠送钻石数
            String give = commonInfoService.findOne(424).getValue();
            if (StringUtils.isNotBlank(give)) {
                userMoney.setMoney(userMoney.getMoney().add(new BigDecimal(give)));
                userMoneyDao.updateById(userMoney);
            }
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("恭喜您，账号注册成功！");
            messageInfo.setTitle("系统通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userInfo.getUserName());
            messageInfo.setUserId(String.valueOf(userInfo.getUserId()));
            messageInfo.setCreateAt(sdf.format(new Date()));
            messageInfo.setIsSee("0");
            messageService.saveBody(messageInfo);
            if (userEntity != null) {
                inviteService.saveBody(userInfo.getUserId(), userEntity);
            }
            return getResult(userInfo);
        }

    }


    @Override
    public Result forgetPwd(String pwd, String phone, String msg) {
        try {
            Msg byPhoneAndCode = msgDao.findByPhoneAndCode(phone, msg);
            //校验短信验证码
            if (byPhoneAndCode == null) {
                return Result.error("验证码不正确");
            }
            UserEntity userByPhone = queryByPhone(phone);
            userByPhone.setPassword(DigestUtils.sha256Hex(pwd));
            msgDao.deleteById(byPhoneAndCode.getId());
            baseMapper.updateById(userByPhone);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("服务器内部错误");
        }
    }

    @Override
    public Result takingOrdersMessage(Page<Map<String, Object>> iPage, Long type, String date) {
        //接单分析
        return Result.success().put("data", new PageUtils(baseMapper.takingOrdersMessage(iPage, type, date)));
    }

    @Override
    public Result selectInviterCodeByUserIdLists(int page, int limit, String invitationCode,Integer userType,Long userId) {
        Page<UserEntity> pages = new Page<>(page, limit);
        IPage<UserEntity> userEntityIPage = baseMapper.selectInviterCodeByUserIdLists(pages, invitationCode,userType,userId);
        return Result.success().put("data", userEntityIPage);
    }


    @Override
    public HashMap<String, Object> userData(Long userId) {
        HashMap<String, Object> map = new HashMap<>();
        UserEntity userEntity = baseMapper.selectById(userId);
        QueryWrapper<UserBrowse> wrapper = new QueryWrapper<UserBrowse>().eq("user_id", userId);
        QueryWrapper<MyCollection> queryWrapper =new QueryWrapper<MyCollection>().eq("user_id",userId);
        QueryWrapper<SendRecord> queryWrapper1 =new QueryWrapper<>();
        QueryWrapper<InterviewRecord>queryWrapper2 =new QueryWrapper<>();
        //个人
        if (userEntity.getUserType() == 1) {
            wrapper.eq("browse_type", 1);
            queryWrapper.eq("type",1);
            queryWrapper1.eq("user_id",userId);
            queryWrapper2.eq("interviewer_id",userId);
            //企业
        } else {
            wrapper.eq("browse_type", 2);
            queryWrapper.eq("type",2);
            queryWrapper1.eq("company_user_id",userId);
            queryWrapper2.eq("user_id",userId);
        }
        int browseCount = userBrowseService.count(wrapper);
        int collectionCount = collectionService.count(queryWrapper);
        int deliveryCount = sendRecordService.count(queryWrapper1);
        int chatCount = chatConversationService.count(new QueryWrapper<ChatConversation>().eq("user_id",userId));
        int interviewCount = interviewRecordService.count(queryWrapper2);
        //浏览记录
        map.put("browseCount", browseCount);
        //收藏记录
        map.put("collectionCount", collectionCount);
        //投递记录
        map.put("deliveryCount", deliveryCount);
        map.put("chatCount",chatCount);
        map.put("interviewCount",interviewCount);
        return map;

    }

    @Override
    public void buyVipCallBack(Long userId, Integer userType) {
        UserEntity userEntity = baseMapper.selectById(userId);
        BigDecimal money;
        if (userType == 1) {
            CommonInfo userVipMoney = commonInfoService.findOne(331);
            money = new BigDecimal(userVipMoney.getValue());
            userEntity.setIsUserVip(1);
            userEntity.setIsUserAdd(0);
            if (userEntity.getUserMonthTime() == null || LocalDateTime.now().isAfter(userEntity.getUserMonthTime())) {
                userEntity.setUserMonthTime(LocalDateTime.now().plusDays(30));
            } else {
                userEntity.setUserMonthTime(userEntity.getUserMonthTime().plusDays(30));
            }
        } else {
            CommonInfo companyVipMoney = commonInfoService.findOne(332);
            money = new BigDecimal(companyVipMoney.getValue());
            userEntity.setIsCompanyVip(1);
            userEntity.setIsCompanyAdd(0);
            if (userEntity.getCompanyMonthTime() == null || LocalDateTime.now().isAfter(userEntity.getCompanyMonthTime())) {
                userEntity.setCompanyMonthTime(LocalDateTime.now().plusDays(30));
            } else {
                userEntity.setCompanyMonthTime(userEntity.getCompanyMonthTime().plusDays(30));
            }
        }
        CommonInfo commonInfo = commonInfoService.findOne(209);
        if ("是".equals(commonInfo.getValue())) {
            UserEntity parentEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", userEntity.getInviterCode()));
            //一级分佣
            if (parentEntity != null) {
                if (parentEntity.getZhiRate().compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal rate = money.multiply(parentEntity.getZhiRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                    parentEntity.setBalance(parentEntity.getBalance().add(rate));
                    userService.updateById(parentEntity);
                    detailsService.setParentMoneyDetails(userId, parentEntity.getUserId(), rate, 1);
                    UserEntity parentParentEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("invitation_code", parentEntity.getInviterCode()));
                    //二级分佣
                    if (parentParentEntity != null) {
                        if (parentParentEntity.getFeiRate().compareTo(BigDecimal.ZERO) > 0) {
                            rate = money.multiply(parentParentEntity.getFeiRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
                            parentParentEntity.setBalance(parentParentEntity.getBalance().add(rate));
                            userService.updateById(parentParentEntity);
                            detailsService.setParentMoneyDetails(userId, parentParentEntity.getUserId(), rate, 2);
                        }
                    }
                }
            }
        }
        baseMapper.updateById(userEntity);
    }

    @Override
    public ExcelData exportExcelUser(String startTime, String endTime, UserEntity userEntity) {
        List<UserEntity> userList = baseMapper.exportExcelUser(startTime, endTime, userEntity);
        ExcelData data = new ExcelData();
        data.setName("用户列表");
        List<String> titles = new ArrayList<>();
        titles.add("编号");
        titles.add("用户名");
        titles.add("手机号");
        titles.add("头像");
        titles.add("微信号");
        titles.add("性别");
        titles.add("年龄");
        titles.add("微信小程序openId");
        titles.add("微信AppOpenId");
        titles.add("密码");
        titles.add("创建时间");
        titles.add("更新时间");
        titles.add("状态");
        titles.add("来源");
        titles.add("邀请码");
        titles.add("邀请人邀请码");
        titles.add("支付宝名称");
        titles.add("支付宝账号");
        titles.add("微信二维码");
        titles.add("佣金");
        titles.add("直属佣金");
        titles.add("非直属佣金");
        titles.add("用户类型");
        titles.add("用户刷新次数");
        titles.add("用户是否是会员");
        titles.add("用户是否已增加次数");
        titles.add("用户月卡到期时间");
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList<>();
        for (UserEntity entity : userList) {
            List<Object> row = new ArrayList<>();
            row.add(entity.getUserId());
            row.add(entity.getUserName());
            row.add(entity.getPhone());
            row.add(entity.getAvatar());
            row.add(entity.getWeChatNum());
            if (entity.getSex() != null && entity.getSex() == 1) {
                row.add("男");
            } else {
                row.add("女");
            }
            row.add(entity.getAge());
            row.add(entity.getOpenId());
            row.add(entity.getWxOpenId());
            row.add(entity.getPassword());
            row.add(entity.getCreateTime());
            row.add(entity.getUpdateTime());
            if (entity.getStatus() != null && entity.getStatus() == 1) {
                row.add("正常");
            } else {
                row.add("禁用");
            }
            row.add(entity.getPlatform());
            row.add(entity.getInvitationCode());
            row.add(entity.getInviterCode());
            row.add(entity.getZhiFuBaoName());
            row.add(entity.getZhiFuBao());
            row.add(entity.getWxImg());
            row.add(entity.getZhiRate());
            row.add(entity.getFeiRate());
            if (entity.getUserType() != null && entity.getUserType() == 1) {
                row.add("用户");
            } else {
                row.add("企业");
            }
            row.add(entity.getUserRefreshCount());
            if (entity.getIsUserVip() == 0) {
                row.add("否");
            } else {
                row.add("是");
            }

            if (entity.getIsUserAdd() == 0) {
                row.add("否");
            } else {
                row.add("是");
            }

            if (entity.getUserMonthTime() != null) {
                row.add(df.format(entity.getUserMonthTime()));
            }

            rows.add(row);
        }
        data.setRows(rows);
        return data;
    }

    @Override
    public HashMap<String, Object> getExtensionData(Long userId) {
        UserEntity userEntity = userService.getById(userId);
        HashMap<String, Object> map = new HashMap<>();
        Integer countChildren = userService.count(new QueryWrapper<UserEntity>().eq("inviter_code", userEntity.getInvitationCode()));
        Integer countChildrenChildren = userService.count(new QueryWrapper<UserEntity>().eq("inviter_inviter_code", userEntity.getInvitationCode()));
        BigDecimal oneMoney = detailsService.getOneProfit(userId, 1);
        BigDecimal twoMoney = detailsService.getOneProfit(userId, 2);
        map.put("countChildren", countChildren);
        map.put("countChildrenChildren", countChildrenChildren);
        map.put("extensionProfit", oneMoney.add(twoMoney));
        map.put("oneMoney", oneMoney);
        map.put("twoMoney", twoMoney);
        return map;


    }

    @Override
    public IPage<UserEntity> getExtensionList(Long userId, Integer type, Integer page, Integer limit) {
        Page<UserEntity> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        UserEntity loginEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("user_id", userId));
        if (loginEntity != null) {
            if (type == 1) {
                return userService.page(pages, new QueryWrapper<UserEntity>().eq("inviter_code", loginEntity.getInvitationCode()));
            } else if (type == 2) {
                return userService.page(pages, new QueryWrapper<UserEntity>().eq("inviter_inviter_code", loginEntity.getInvitationCode()));
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public IPage<HashMap<String, Object>> getProfitList(Long userId, Integer type, Integer page, Integer limit) {


        Page<HashMap<String, Object>> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return detailsDao.getProfitList(pages, userId, type);
    }

    @Override
    public Result getUser(String tempId) {
        UserEntity user = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("temp_id", tempId));
        if (user != null) {
            return getResult(user);
        } else {
            return Result.error("未查到");
        }
    }

    @Override
    public Result bindUser(String phone, String wxOpenId, String msg) {
        Msg code = msgService.findByPhoneAndCode(phone, msg);
        if (code == null) {
            return Result.error("验证码错误");
        }
        UserEntity userEntity;
        msgService.removeById(code.getId());
        userEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("phone", phone));

        if (userEntity != null) {
            UserEntity query = userService.queryByWxOpenId(wxOpenId);
            userService.removeById(query);
        } else {
            userEntity = userService.queryByWxOpenId(wxOpenId);
            userEntity.setPhone(phone);
        }

        userEntity.setWxOpenId(wxOpenId);
        userService.updateById(userEntity);


        return getResult(userEntity);

    }

    @Override
    public IPage<UserEntity> getNotHasCompanyUserList(Integer page, Integer limit, UserEntity userEntity) {

        Page<UserEntity> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        return baseMapper.getNotHasCompanyUserList(pages, userEntity);
    }

    @Override
    public Result saveUser(UserEntity userEntity){
        userEntity.setZhiRate(new BigDecimal(commonInfoService.findOne(207).getValue()));
        userEntity.setFeiRate(new BigDecimal(commonInfoService.findOne(208).getValue()));
        userEntity.setCreateTime(DateUtils.formatDate(new Date()));
        baseMapper.insert(userEntity);
        //给用户创建钱包
        UserMoney userMoney = new UserMoney();
        userMoney.setUserId(userEntity.getUserId());
        userMoney.setMoney(BigDecimal.valueOf(0));
        userMoney.setCustomizationMoney(BigDecimal.valueOf(0));
        userMoneyDao.insert(userMoney);
        //赠送钻石数
        String give = commonInfoService.findOne(424).getValue();
        if (StringUtils.isNotBlank(give)) {
            userMoney.setMoney(userMoney.getMoney().add(new BigDecimal(give)));
            userMoneyDao.updateById(userMoney);
        }
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent("恭喜您，账号注册成功！");
        messageInfo.setTitle("系统通知");
        messageInfo.setState(String.valueOf(5));
        messageInfo.setUserName(userEntity.getUserName());
        messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
        messageInfo.setCreateAt(DateUtils.formatDate(new Date()));
        messageInfo.setIsSee("0");
        messageService.saveBody(messageInfo);
        UserEntity superUserEntity = queryByInvitationCode(userEntity.getInviterCode());
        if (superUserEntity != null) {
            inviteService.saveBody(userEntity.getUserId(), superUserEntity);
        }
        return Result.success();
    }

    @Override
    public Result updateUserType(UpdateUserTypeForm updateUserTypeForm) {
        this.update(new UserEntity(), new LambdaUpdateWrapper<UserEntity>()
                .eq(UserEntity::getUserId, updateUserTypeForm.getUserId())
                .set(UserEntity::getUserType, updateUserTypeForm.getUserType())
        );

        return Result.success();
    }

}
