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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.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.SmsSingleSenderResult;
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.entity.*;
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.artificer.dao.UserRechargeDao;
import com.sqx.modules.artificer.entity.Artificer;
import com.sqx.modules.artificer.service.ArtificerService;
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.invite.service.InviteService;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.InvitationCodeUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weixin.popular.api.MessageAPI;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;
import weixin.popular.util.JsonUtil;

import javax.websocket.SendResult;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.sqx.modules.utils.PeriodUtil.obtainCycle;

/**
 * 用户
 *
 * @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;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ArtificerService artificerService;
    @Autowired
    private UserRechargeDao userRechargeDao;

    @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 queryByArtificerOpenId(String openId) {
        return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("artificer_open_id", openId));
    }

    @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) {
        UserEntity userEntity = baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("user_id", userId));
        return userEntity;
    }

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

    @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 userType) {
        try {
            //微信小程序APPID
            String appid;
            //微信小程序秘钥
            String secret;
            if(userType==null || userType==1){
                appid = commonInfoService.findOne(45).getValue();
                secret = commonInfoService.findOne(46).getValue();
            }else{
                appid = commonInfoService.findOne(243).getValue();
                secret = commonInfoService.findOne(244).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();
            UserEntity userEntity;
            //判断是否注册过
            if(userType==null || userType==1){
                userEntity = queryByOpenId(open_id);
            }else{
                userEntity = queryByArtificerOpenId(open_id);
            }
            Map<String, String> map = new HashMap<>();
            // 封装返回小程序
            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");
            }

            if (userEntity == null) {
                map.put("flag", "1");
            } else {
                if(StringUtils.isEmpty(userEntity.getPhone())){
                    map.put("flag", "1");
                }else{
                    map.put("flag", userEntity.getPhone());
                }

            }
            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实体类，判断用户是否是新用户，不是的话，更新最新登录时间，是的话，将用户信息存到数据库

        //判断是否在app登陆过  手机号是否有账号
        UserEntity userByMobile = queryByPhone(userInfo1.getPhone());
        if (userByMobile != null) {
            //有账号则绑定账号
            if(userInfo1.getType()!=null && userInfo1.getType()==2){
                userByMobile.setArtificerOpenId(userInfo1.getOpenId());
                userInfo1.setArtificerOpenId(userInfo1.getOpenId());
            }else{
                userByMobile.setOpenId(userInfo1.getOpenId());
            }
            baseMapper.updateById(userByMobile);
            if (userByMobile.getStatus().equals(2)) {
                return Result.error("账号已被封禁，请联系客服处理！");
            }
            if(userInfo1.getType()!=null && userInfo1.getType()==2){
                Artificer artificer = artificerService.selectArtificerByUserId(userByMobile.getUserId());
                if(artificer==null){
                    artificer=new Artificer();
                    artificer.setStatus(2);
                    artificer.setUserId(userByMobile.getUserId());
                    artificer.setArtificerName(userByMobile.getUserName());
                    artificer.setArtificerImg(userByMobile.getAvatar());
                    artificer.setArtificerSales(0);
                    artificer.setCreateTime(sdf.format(new Date()));
                    artificer.setCreditScore(BigDecimal.valueOf(100));
                    artificer.setTripWay(1);
                    artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                    artificerService.save(artificer);
                }
            }
        } else {
            UserEntity userInfo;
            if(userInfo1.getType()!=null && userInfo1.getType()==2){
                userInfo1.setArtificerOpenId(userInfo1.getOpenId());
                userInfo1.setOpenId(null);
                userInfo = queryByArtificerOpenId(userInfo1.getArtificerOpenId());
            }else{
                userInfo = queryByOpenId(userInfo1.getOpenId());
            }

            if (userInfo != null) {
                if (userInfo.getStatus().equals(2)) {
                    return Result.error("账号已被封禁，请联系客服处理！");
                }
                if (StringUtils.isBlank(userInfo1.getUserName()) || "微信用户".equals(userInfo1.getUserName())) {
                    if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                        userInfo1.setUserName(userInfo1.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                    }
                }
                userInfo.setUpdateTime(date);
                baseMapper.updateById(userInfo);
                if(userInfo1.getType()!=null && userInfo1.getType()==2){
                    Artificer artificer = artificerService.selectArtificerByUserId(userInfo.getUserId());
                    if(artificer==null){
                        artificer=new Artificer();
                        artificer.setStatus(2);
                        artificer.setUserId(userInfo.getUserId());
                        artificer.setArtificerName(userInfo.getUserName());
                        artificer.setArtificerImg(userInfo.getAvatar());
                        artificer.setArtificerSales(0);
                        artificer.setCreateTime(sdf.format(new Date()));
                        artificer.setCreditScore(BigDecimal.valueOf(100));
                        artificer.setTripWay(1);
                        artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                        artificerService.save(artificer);
                    }
                }
            } else {

                if (StringUtils.isEmpty(userInfo1.getInviterCode())) {
                    userInfo1.setInviterCode(commonInfoService.findOne(88).getValue());
                }
                if (StringUtils.isBlank(userInfo1.getUserName()) || "微信用户".equals(userInfo1.getUserName())) {
                    if (StringUtils.isNotEmpty(userInfo1.getPhone())) {
                        userInfo1.setUserName(userInfo1.getPhone().replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
                    }
                }
                //没有则生成新账号
                userInfo1.setCreateTime(date);
                userInfo1.setUserRate(new BigDecimal(commonInfoService.findOne(295).getValue()));
                userInfo1.setShopRate(new BigDecimal(commonInfoService.findOne(296).getValue()));
                userInfo1.setPlatform("小程序");
                userInfo1.setStatus(1);
                if(StringUtils.isNotEmpty(userInfo1.getPhone())){
                    userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getPhone()));
                }else{
                    if(userInfo1.getType()!=null && userInfo1.getType()==2){
                        userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getArtificerOpenId()));
                    }else{
                        userInfo1.setPassword(DigestUtils.sha256Hex(userInfo1.getOpenId()));
                    }
                }
                userInfo1.setType(userInfo1.getType()==null?1:userInfo1.getType());
                baseMapper.insertUser(userInfo1);
                userInfo1.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo1.getUserId()));
                baseMapper.updateById(userInfo1);
                //给用户创建钱包
                UserMoney userMoney = new UserMoney();
                userMoney.setUserId(userInfo1.getUserId());
                userMoney.setMoney(BigDecimal.valueOf(0));
                userMoney.setCashDeposit(BigDecimal.valueOf(0));
                userMoneyDao.insert(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);
                if(userInfo1.getType()!=null && userInfo1.getType()==2){
                    Artificer artificer=new Artificer();
                    artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                    artificer.setStatus(2);
                    artificer.setUserId(userInfo1.getUserId());
                    artificer.setArtificerName(userInfo1.getUserName());
                    artificer.setArtificerImg(userInfo1.getAvatar());
                    artificer.setArtificerSales(0);
                    artificer.setCreateTime(sdf.format(new Date()));
                    artificer.setCreditScore(BigDecimal.valueOf(100));
                    artificer.setTripWay(1);
                    artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                    artificerService.save(artificer);
                }
            }
        }
        UserEntity user;
        //返回用户信息
        if(userInfo1.getType()!=null && userInfo1.getType()==2){
            user = queryByArtificerOpenId(userInfo1.getArtificerOpenId());
        }else{
            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.setUserRate(new BigDecimal(commonInfoService.findOne(295).getValue()));
            userInfo.setShopRate(new BigDecimal(commonInfoService.findOne(296).getValue()));
            userInfo.setWxOpenId(wxOpenId);
            userInfo.setPhone(phone);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setUpdateTime(time);
            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);
            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, String bindingConsortiaId, String password, String userName, String avatar, String scanningChannel) {
        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("账号已被禁用，请联系客服处理！");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setWxOpenId(openId);
            if(StringUtils.isNotEmpty(password)){
                userInfo.setPassword(DigestUtils.sha256Hex(password));
            }
            userInfo.setUpdateTime(sdf.format(new Date()));
            baseMapper.updateById(userInfo);
            return getResult(userInfo);
        } else {
            if (StringUtils.isEmpty(inviterCode)) {
                inviterCode=commonInfoService.findOne(88).getValue();
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = simpleDateFormat.format(new Date());
            userInfo = new UserEntity();
            if(StringUtils.isNotEmpty(userName)){
                userInfo.setUserName(userName);
            }else{
                userInfo.setUserName(phone.replaceAll("(\\d{3})\\d*([0-9a-zA-Z]{4})", "$1****$2"));
            }
            if(StringUtils.isNotEmpty(avatar)){
                userInfo.setAvatar(avatar);
            }
            userInfo.setUserRate(new BigDecimal(commonInfoService.findOne(295).getValue()));
            userInfo.setShopRate(new BigDecimal(commonInfoService.findOne(296).getValue()));
            userInfo.setPhone(phone);
            userInfo.setInviterCode(inviterCode);
            userInfo.setBindingConsortiaId(bindingConsortiaId);//绑定注册用户的商户ID
            userInfo.setScanningChannel(scanningChannel);
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setSysPhone(sysPhone);
            userInfo.setStatus(1);
            userInfo.setWxOpenId(openId);
            if(StringUtils.isNotEmpty(password)){
                userInfo.setPassword(DigestUtils.sha256Hex(password));
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setUpdateTime(sdf.format(new Date()));
            baseMapper.insertUser(userInfo);


            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo.getUserId()));
            baseMapper.updateById(userInfo);
            if(userInfo.getType()!=null && userInfo.getType()==2){
                Artificer artificer=new Artificer();
                artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                artificer.setStatus(2);
                artificer.setUserId(userInfo.getUserId());
                artificer.setArtificerName(userInfo.getUserName());
                artificer.setArtificerImg(userInfo.getAvatar());
                artificer.setArtificerSales(0);
                artificer.setCreateTime(sdf.format(new Date()));
                artificer.setCreditScore(BigDecimal.valueOf(100));
                artificer.setTripWay(1);
                artificer.setRate(new BigDecimal(commonInfoService.findOne(381).getValue()));
                artificerService.save(artificer);
            }
            msgDao.deleteById(msg1.getId());
            //给用户创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(BigDecimal.valueOf(0));
            userMoney.setCashDeposit(BigDecimal.valueOf(0));
            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);
            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 ("bindWx".equals(state)) {
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getWxOpenId())) {
                return Result.error("当前手机号已被其他微信账号绑定");
            }
        } else if ("bindIos".equals(state)) {
            UserEntity userByPhone = queryByPhone(phone);
            if (userByPhone != null && StringUtils.isNotEmpty(userByPhone.getAppleId())) {
                return Result.error("当前手机号已被其他苹果账号绑定");
            }
        }*/
        try{
            if (phone != null) {
                if("forget".equals(state)){
                    UserEntity userByPhone = queryByPhone(phone);
                    if (userByPhone == null) {
                        return Result.error("手机号未注册");
                    }
                }else if("gzg".equals(state) || "fh".equals(state) || "touSu".equals(state) || "send".equals(state) || "end".equals(state)|| "qtsx".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);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("短信推送失败！");
        }
        return Result.success();
    }


    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;

        CommonInfo three = commonInfoService.findOne(31);
        String clientId = three.getValue();
        CommonInfo four = commonInfoService.findOne(32);
        String clientSecret = four.getValue();
        try {
            String secretId = commonInfoService.findOne(397).getValue();
            String secretKey = commonInfoService.findOne(398).getValue();
            // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {phone};
            req.setPhoneNumberSet(phoneNumberSet1);

            req.setSmsSdkAppId(clientId);
            CommonInfo one = commonInfoService.findOne(6);
            req.setSignName(one.getValue());
            switch (state) {
                case "register":
                    req.setTemplateId(commonInfoService.findOne(399).getValue());
                    break;
                case "forget":
                    req.setTemplateId(commonInfoService.findOne(400).getValue());
                    break;
                case "bind":
                    req.setTemplateId(commonInfoService.findOne(401).getValue());
                    break;
                case "send":
                    req.setTemplateId(commonInfoService.findOne(402).getValue());
                    break;
                case "end":
                    req.setTemplateId(commonInfoService.findOne(403).getValue());
                    break;
                case "fh":
                    req.setTemplateId(commonInfoService.findOne(404).getValue());
                    break;
                case "qtsx":
                    req.setTemplateId(commonInfoService.findOne(453).getValue());
                    break;
                case "touSu":
                    req.setTemplateId(commonInfoService.findOne(453).getValue());
                    break;
                default:
                    req.setTemplateId(commonInfoService.findOne(399).getValue());
                    break;
            }
            String[] templateParamSet1 = {String.valueOf(code)};
            req.setTemplateParamSet(templateParamSet1);
            switch (state) {
                case "send":
                    req.setTemplateParamSet(null);
                    break;
                case "end":
                    req.setTemplateParamSet(null);
                    break;
                case "fh":
                    req.setTemplateParamSet(null);
                    break;
                case "touSu":
                    req.setTemplateParamSet(null);
                    break;
                case "qtsx":
                    req.setTemplateParamSet(null);
                    break;
                default:
                    req.setTemplateId(commonInfoService.findOne(399).getValue());
                    break;
            }
            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            JSONObject jsonObject = JSONObject.parseObject(SendSmsResponse.toJsonString(resp));
            JSONArray sendStatusSet = jsonObject.getJSONArray("SendStatusSet");
            JSONObject jsonObject1 = sendStatusSet.getJSONObject(0);
            if ("Ok".equals(jsonObject1.getString("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");
                }
            }
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        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 + "，您正在执行找回密码操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "bind":
                value = "【" + name.getValue() + "】验证码: " + code + "，您正在执行绑定手机号操作，10分钟内有效，如非您本人操作，可忽略本条消息";
                break;
            case "send":
                value = "【" + name.getValue() + "】有用户下单了，赶快上线查看吧！";
                break;
            case "end":
                value = "【" + name.getValue() + "】订单即将结束，请与客户进行确认！";
                break;
            case "fh":
                value = "【" + name.getValue() + "】您的账号存在违规，已被封禁。如有疑问，请联系客服！";
                break;
            case "touSu":
                value = "【" + name.getValue() + "】您好，客户对您进行了投诉，平台对您的信誉分进行了扣除，请规范您的服务！";
                break;
            case "qtsx":
                value = "【" + name.getValue() + "】您好，有客户请您上线！";
                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) {
        return baseMapper.selectById(userId);
    }


    @Override
    public PageUtils selectUserPage(Integer page, Integer limit, String search, Integer sex, String platform,
                                    Integer isAuthentication,String sysPhone, Integer status,
                                    String userName,String invitationCode,String inviterCode,
                                    Integer member,Integer ordersUser,Integer isAgency,Integer isShop,String artificerName) {
        Page<UserEntity> pages = new Page<>(page, limit);
        return new PageUtils(baseMapper.selectUserPage(pages,search,sex,platform,isAuthentication,
                sysPhone,status,userName,invitationCode,inviterCode,member,ordersUser,isAgency,isShop,artificerName));
    }

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

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

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


    @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();
                if (userEntity == null || userEntity.getSysPhone() == null || userEntity.getSysPhone() == 1) {
                    //安卓推送
                    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);
                } else {
                    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);
                }
                // 设置接收人信息
                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());
                }
            }
        } 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("账号已被禁用，请联系客服处理！");
        }
        if (userEntity.getStatus().equals(3)) {
            return Result.error("账号已被停牌禁用，请联系客服处理！");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userEntity.setUpdateTime(sdf.format(new Date()));
        baseMapper.updateById(userEntity);


        Artificer artificer = artificerService.selectArtificerByUserId(userEntity.getUserId());
        if(artificer!=null){
            userEntity.setArtificerId(artificer.getArtificerId());
        }

        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 {
            if(StringUtils.isEmpty(inviterCode)){
                inviterCode=commonInfoService.findOne(88).getValue();
            }
            UserEntity userEntity = queryByInvitationCode(inviterCode);
            if(userEntity==null){
                return Result.error("邀请码不正确");
            }
            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);
            userInfo.setUserRate(new BigDecimal(commonInfoService.findOne(295).getValue()));
            userInfo.setShopRate(new BigDecimal(commonInfoService.findOne(296).getValue()));
            //对密码进行MD5加密
            userInfo.setPassword(DigestUtils.sha256Hex(password));
            userInfo.setPlatform(platform);
            userInfo.setCreateTime(time);
            userInfo.setStatus(1);
            userInfo.setInviterCode(inviterCode);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userInfo.setCreateTime(sdf.format(new Date()));
            baseMapper.insertUser(userInfo);
            userInfo.setInvitationCode(InvitationCodeUtil.toSerialCode(userInfo.getUserId()));
            //设置自己邀请码
            baseMapper.updateById(userInfo);
            //给用户创建钱包
            UserMoney userMoney = new UserMoney();
            userMoney.setUserId(userInfo.getUserId());
            userMoney.setMoney(BigDecimal.valueOf(0));
            userMoney.setCashDeposit(BigDecimal.valueOf(0));
            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);
            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 void sendWxMessage(String templateId, LinkedHashMap<String, TemplateMessageItem> data, String openid) {
        String url=commonInfoService.findOne(19).getValue();
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setTouser(openid);
        templateMessage.setTemplate_id(templateId);
        templateMessage.setData(data);
        templateMessage.setUrl(url);
        TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(getWxToken(), templateMessage);
        if (templateMessageResult.isSuccess()) {
            new SendResult();
        } else {
            new SendResult();
        }
    }

    private String getWxToken() {
        String appid = commonInfoService.findOne(5).getValue();
        String secret = commonInfoService.findOne(21).getValue();
        String jsonResult = HttpClientUtil.doPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret);
        JSONObject parseObject = JSON.parseObject(jsonResult);
        log.info("=========accessTokenOut--gzh========="+parseObject.toJSONString());

        String errcode = parseObject.getString("errcode");
        return parseObject.getString("access_token");
    }

    @Override
    public int updateUserClientIdIsNull(String clientid){
        return baseMapper.updateUserClientIdIsNull(clientid);
    }

    @Override
    public int updateUserConsortiaIdIsNull(Long userId){
        return baseMapper.updateUserConsortiaIdIsNull(userId);
    }

    @Override
    public int updateUserClientIdIsNullByClientId(Long consortiaId){
        return baseMapper.updateUserClientIdIsNullByClientId(consortiaId);
    }

    @Override
    public Result selectAgencyOrdersMoneyList(Integer page,Integer limit,String userName,String phone,String startTime,String endTime){
        return Result.success().put("data",new PageUtils(baseMapper.selectAgencyOrdersMoneyList(new Page<>(page,limit),userName,phone,startTime,endTime)));
    }

    @Override
    public Result integral(String type, Integer current, Integer size, String date,String artificerId) throws ParseException {
        if (org.apache.commons.lang3.StringUtils.isEmpty(date)) {
            date = DateUtil.formatDate(DateUtil.date());
        }
        String startDate = DateUtil.formatDateTime(obtainCycle(DateUtil.parse(date)).getStartFundData());
        String endDate = DateUtil.formatDate(obtainCycle(DateUtil.parse(date)).getEndFundData()) + " 23:59:59";
        return Result.success().put("data", userRechargeDao.integralArtificerId(new Page<>(current, size), type, startDate, endDate, artificerId));
    }

    @Override
    public IPage<UserEntity> merchantPromotion(UserEntity userEntity,Integer page, Integer limit) {
        IPage<UserEntity> pages = new Page<>(page, limit);
        return baseMapper.merchantPromotion(pages,userEntity);
    }
}
