package com.gree.mall.miniapp.logic.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.miniapp.bean.common.WechatOpenBean;
import com.gree.mall.miniapp.bean.settle.OrderShareBean;
import com.gree.mall.miniapp.bean.user.*;
import com.gree.mall.miniapp.bean.websit.WebsitVO;
import com.gree.mall.miniapp.commonmapper.CommonMapper;
import com.gree.mall.miniapp.commonmapper.MyProfitMapper;
import com.gree.mall.miniapp.commonmapper.OrderShareRankMapper;
import com.gree.mall.miniapp.constant.Constant;
import com.gree.mall.miniapp.enums.*;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.helper.ResponseHelper;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.SMSLogic;
import com.gree.mall.miniapp.logic.common.outside.WechatLogic;
import com.gree.mall.miniapp.logic.coupon.CouponLogic;
import com.gree.mall.miniapp.logic.order.ShoppingCartLogic;
import com.gree.mall.miniapp.plus.entity.*;
import com.gree.mall.miniapp.plus.service.*;
import com.gree.mall.miniapp.utils.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 小程序用户
 */
@Slf4j
@Service
public class UserLogic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    WechatLogic wechatLogic;
    @Autowired
    ShoppingCartLogic shoppingCartLogic;
    @Autowired
    CouponLogic couponLogic;
    //    @Autowired
//    WorkWechatLogic workWechatLogic;
    @Autowired
    RedisLockRegistry redisLockRegistry;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    CommonMapper commonMapper;
    @Autowired
    UserService userService;
    @Autowired
    OrderShareService orderShareService;
    @Autowired
    UserVisitService userVisitService;
    //    @Autowired
//    EnterpriseWechatWorkerService enterpriseWechatWorkerService;
    @Autowired
    private OrderShareRankMapper orderShareRankMapper;
    @Autowired
    private MyProfitMapper myProfitMapper;
    @Autowired
    PromotionGroupSpecUserService promotionGroupSpecUserService;
    @Autowired
    WebsitUserService websitUserService;
    @Autowired
    GoodsFavoriteService goodsFavoriteService;
    @Autowired
    UserWaitService userWaitService;
    @Autowired
    PgIncreOrderService pgIncreOrderService;

    @Autowired
    PgIncreWebsitService pgIncreWebsitService;
    @Autowired
    WorkerImgService workerImgService;
    @Autowired
    SettleMonthWagesWorkerService settleMonthWagesWorkerService;
    @Autowired
    SettleExpenseItemService settleExpenseItemService;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;

    @Autowired
    UserLogService userLogService;

    @Autowired
    PgOrderWorkerService pgOrderWorkerService;
    @Resource
    SMSLogic smsLogic;

    /**
     * 微信小程序授权
     *
     * @param code
     * @param serviceId
     * @return
     * @throws RemoteServiceException
     * @throws InterruptedException
     */
    public UserWxBean addUser(String code, String phoneCode, String serviceId, String mpOpenId, HttpServletRequest request) throws RemoteServiceException, InterruptedException, WxErrorException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        //WxMaService maService = wechatLogic.getMaService(currentCompanyWechat.getCurrentCompanyWechatId());

        //WxMaJscode2SessionResult result = maService.jsCode2SessionInfo(code);
        WechatOpenBean result = wechatLogic.getAuth(code, phoneCode);
        String openId = result.getOpenid();
        String sessionKey = result.getSessionKey();
        String unionId = result.getUnionid();

        log.info("【微信授权】：{}", JSONObject.toJSONString(result));

        String key = Constant.RedisPrefix.LOCK_AUTH + ":" + result.getOpenid();
        Lock obtain = redisLockRegistry.obtain(key);
        if (!obtain.tryLock(2, TimeUnit.SECONDS)) {
            log.error("请勿重复授权");
            return null;
        }

        String mobile = "";
        //授权手机号
        if (StringUtils.isNotBlank(phoneCode)) {
            mobile = result.getMobile();
        }

        try {
            //如果用户不存在则新注册
            User user = userService.lambdaQuery()
                    .eq(User::getOpenId, openId)
                    .eq(User::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                    .one();
            if (user == null) {

                user = new User();
                user.setUserId(IdWorker.getIdStr());
                user.setLastLoginTime(new Date());
                user.setOpenId(openId);
                user.setSessionKey(sessionKey);
                if (StringUtils.isNotBlank(serviceId)) {
                    user.setServiceId(serviceId);
                    user.setServiceTime(new Date());
                }
                user.setLastLoginTime(new Date());
                user.setCreateTime(new Date());
                if (StringUtils.isNotBlank(mpOpenId)) {
                    user.setMpOpenId(mpOpenId);
                }
                //授权手机号
                if (StringUtils.isNotBlank(mobile)) {
                    user.setMobile(mobile);
                }
                user.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
                user.setCompanyName(currentCompanyWechat.getCompanyName());
                userService.save(user);

            } else {

                //如果用户存在，则判断是否为业务员，并更新相关信息
                if (!user.getStatus()) {
                    throw new RemoteServiceException("用户已被冻结");
                }
                user.setUnionId(unionId);
                user.setSessionKey(sessionKey);
                user.setLastLoginTime(new Date());
                if (StringUtils.isBlank(user.getServiceId()) && StringUtils.isNotBlank(serviceId)) {
                    user.setServiceId(serviceId);
                    user.setServiceTime(new Date());
                }
                if (StringUtils.isNotBlank(mpOpenId)) {
                    user.setMpOpenId(mpOpenId);
                }
                //授权手机号
                if (StringUtils.isNotBlank(mobile)) {
                    user.setMobile(mobile);
                }
                user.setOpenId(openId);
                user.updateById();
            }

            //授权手机号后检查是否有预设置的师傅身份信息
            if (StringUtils.isNotBlank(mobile)) {
                userTypeInit(user);
            }

            return this.supplyUser(user);
        } finally {
            obtain.unlock();
        }
    }


    /**
     * 微信公众号授权
     *
     * @param code
     * @param serviceId
     * @return
     */
    public UserWxBean addUser(String code, String serviceId, HttpServletRequest request) throws InterruptedException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        String mpOpenId = wechatLogic.getPubAuthOpenId(code, currentCompanyWechat.getPubAppId());
        String key = Constant.RedisPrefix.LOCK_AUTH + ":" + mpOpenId;
        Lock obtain = redisLockRegistry.obtain(key);
        if (!obtain.tryLock(2, TimeUnit.SECONDS)) {
            log.error("请勿重复授权");
            return null;
        }
        try {
            //如果用户不存在则新注册
            User user = userService.lambdaQuery()
                    .eq(User::getOpenId, mpOpenId)
                    .eq(User::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                    .one();
            if (user == null) {
                user = new User();
                user.setUserId(IdWorker.getIdStr());
                user.setLastLoginTime(new Date());
                user.setOpenId(mpOpenId);
                user.setMpOpenId(mpOpenId);
                user.setServiceId(serviceId);
                user.setServiceTime(new Date());
                user.setLastLoginTime(new Date());
                user.setCreateTime(new Date());
                if (StringUtils.isNotBlank(mpOpenId)) {
                    user.setMpOpenId(mpOpenId);
                }
                user.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
                user.setCompanyName(currentCompanyWechat.getCompanyName());
                userService.save(user);
            } else {
                //如果用户存在，则判断是否为业务员，并更新相关信息
                if (!user.getStatus()) {
                    throw new RemoteServiceException("用户已被冻结");
                }
                user.setLastLoginTime(new Date());
                if (StringUtils.isBlank(user.getServiceId()) && StringUtils.isNotBlank(serviceId)) {
                    user.setServiceId(serviceId);
                    user.setServiceTime(new Date());
                }
                if (StringUtils.isNotBlank(mpOpenId)) {
                    user.setMpOpenId(mpOpenId);
                }
                user.setOpenId(mpOpenId);
                user.updateById();
            }
            //授权手机号后检查是否有预设置的师傅身份信息
            if (StringUtils.isNotBlank(user.getMobile())) {
                userTypeInit(user);
            }

            return this.supplyUser(user);
        } finally {
            obtain.unlock();
        }
    }


    /**
     * 根据初始化的师傅分销员待入驻信息，通过手机号生成用户类型
     *
     * @param user
     */
    public void userTypeInit(User user) {
        String mobile = user.getMobile();
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        List<UserWait> list = userWaitService.lambdaQuery()
                .eq(UserWait::getMobile, mobile)
                .eq(UserWait::getCompanyWechatId, currentCompanyWechat.getCurrentCompanyWechatId())
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        long count = list.stream().filter(v -> StringUtils.equals(v.getUserType(), UserTypeEnum.WORKER.getKey())).count();
        Boolean hasWorker = count > 0;

        UserTypeEnum userTypeEnum = UserTypeEnum.valueOf(user.getType());
        for (UserWait userWait : list) {
            user.setWorkerNumber(userWait.getWorkerNumber());
            user.setNickName(userWait.getName());
            if (StringUtils.isBlank(user.getIdCard())) {
                user.setIdCard(userWait.getIdcard());
            }
            //只有普通用户才需要变更为分销员
            if (userWait.getUserType().equals(UserTypeEnum.SERVICE.getKey())
                    && !hasWorker
                    && user.getType().equals(UserTypeEnum.GENERAL.getKey())
                    && userTypeEnum == UserTypeEnum.GENERAL) {
                userTypeEnum = UserTypeEnum.SERVICE;
            }
            //非师傅状态，只有有1个入驻师傅的就是师傅
            if (userWait.getUserType().equals(UserTypeEnum.WORKER.getKey())) {

                userTypeEnum = UserTypeEnum.WORKER;

                if (!user.getType().equals(UserTypeEnum.WORKER.getKey())) {
                    //新增网点师傅,先删后增
                    websitUserService.lambdaUpdate()
                            .eq(WebsitUser::getWebsitId, userWait.getWebsitId())
                            .eq(WebsitUser::getUserId, user.getUserId()).remove();

                    WebsitUser websitUser = new WebsitUser();
                    websitUser.setUserId(user.getUserId());
                    websitUser.setWebsitId(userWait.getWebsitId());
                    websitUser.setExamineStatus(ExamineStatusEnum.OK.getKey());
                    websitUser.setExamineTime(new Date());
                    websitUser.setExamineRemark("初始化");
                    websitUser.setBankAccount(userWait.getBankAccount());
                    websitUser.setWorkerNumber(userWait.getWorkerNumber());
                    websitUser.insert();
                }
            }
        }
        user.setApplyType(userTypeEnum.getKey());
        user.setType(userTypeEnum.getKey());
        user.updateById();
    }

    /**
     * 根据初始化的师傅待入驻信息，通过手机号生成用户类型
     *
     * @param user
     */
    public void userTypeInit2(User user) {
        String mobile = user.getMobile();
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        List<UserWait> list = userWaitService.lambdaQuery()
                .eq(UserWait::getMobile, mobile)
                .eq(UserWait::getCompanyWechatId, currentCompanyWechat.getCurrentCompanyWechatId())
                .eq(UserWait::getIsAdd, false)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        UserTypeEnum userTypeEnum = UserTypeEnum.valueOf(user.getType());
        for (UserWait userWait : list) {
            user.setWorkerNumber(userWait.getWorkerNumber());
            user.setNickName(userWait.getName());
            if (StringUtils.isBlank(user.getIdCard())) {
                user.setIdCard(userWait.getIdcard());
            }
            //非师傅状态，只有有1个入驻师傅的就是师傅
            if (userWait.getUserType().equals(UserTypeEnum.WORKER.getKey())) {

                userTypeEnum = UserTypeEnum.WORKER;

                if (!user.getType().equals(UserTypeEnum.WORKER.getKey())) {
                    //新增网点师傅,先删后增
                    websitUserService.lambdaUpdate()
                            .eq(WebsitUser::getWebsitId, userWait.getWebsitId())
                            .eq(WebsitUser::getUserId, user.getUserId())
                            .remove();

                    WebsitUser websitUser = new WebsitUser();
                    websitUser.setUserId(user.getUserId());
                    websitUser.setWebsitId(userWait.getWebsitId());
                    websitUser.setExamineStatus(ExamineStatusEnum.OK.getKey());
                    websitUser.setExamineTime(new Date());
                    websitUser.setExamineRemark("初始化");
                    websitUser.setBankAccount(userWait.getBankAccount());
                    websitUser.setWorkerNumber(userWait.getWorkerNumber());
                    websitUser.setCompanyWechatId(currentCompanyWechat.getCurrentCompanyWechatId());
                    websitUser.setCompanyWechatName(currentCompanyWechat.getCompanyName());
                    websitUser.insert();
                }
            }
        }
        user.setApplyType(userTypeEnum.getKey());
        user.setType(userTypeEnum.getKey());
        user.updateById();

        userWaitService.lambdaUpdate()
                .set(UserWait::getIsAdd, true)
                .in(UserWait::getId, list.stream().map(UserWait::getId).collect(Collectors.toList()))
                .update();
    }

//    public User userToService(User user,CurrentCompanyWechat currentCompanyWechat){
//        //判断该手机号是否为业务员
//        if (StringUtils.isNotBlank(user.getMobile())) {
//            List<EnterpriseWechatWorker> list = enterpriseWechatWorkerService.lambdaQuery()
//                    .eq(EnterpriseWechatWorker::getMobile, user.getMobile())
//                    .eq(EnterpriseWechatWorker::getCorpId,currentCompanyWechat.getCorpId())
//                    .list();
//
//            if (!CollectionUtils.isEmpty(list)) {
//                String workUserId = list.get(0).getWechatUserId();
//                Integer count = userService.lambdaQuery()
//                        .eq(User::getWorkUserId, workUserId)
//                        .eq(User::getType, UserTypeEnum.SERVICE.toString())
//                        .count();
//                if(count<1){
//                    user.setType(UserTypeEnum.SERVICE.toString());
//                    user.setWorkName(list.get(0).getName());
//                    user.setWorkUserId(workUserId);
//                    user.setPosition(list.get(0).getPosition());
//                    user.setWorkPhone(list.get(0).getMobile());
//                    user.setWorkQrcode(list.get(0).getQrCode());
//                    user.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
//                    user.setCompanyName(currentCompanyWechat.getCompanyName());
//                }
//            }
//        }
//        return user;
//    }

    /**
     * 企业微信里授权的场景
     *
     * @param code
     * @param serviceId
     * @return
     * @throws WxErrorException
     * @throws RemoteServiceException
     * @throws InterruptedException
     */
//    @Transactional
//    public UserWxBean addWorkUser(String code, String serviceId,HttpServletRequest request) throws RemoteServiceException, InterruptedException {
//        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
//        //企业微信里拉取微信授权
//        if (StringUtils.isNotBlank(serviceId)) {
//            User user = userService.getById(serviceId);
//            Map<String, Object> returnMap = wechatLogic.authToken(code,currentCompanyWechat);
//            String openId = (String) returnMap.get("openid");
//            String sessionKey = (String) returnMap.get("session_key");
//            //删掉可能存在的openid数据
//            userService.lambdaUpdate()
//                    .eq(User::getOpenId, openId)
//                    .eq(User::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
//                    .remove();
//            //微信授权,二次绑定微信openid
//            user.setOpenId(openId);
//            user.setSessionKey(sessionKey);
//            user.updateById();
//            return this.supplyUser(user);
//        }
//
//        //企业微信进入
//        WxCpMaJsCode2SessionResult wxCpMaJsCode2SessionResult = workWechatLogic.jsCode2Session(code,currentCompanyWechat);
//
//        String workUserId = wxCpMaJsCode2SessionResult.getUserId();
//        String sessionKey = wxCpMaJsCode2SessionResult.getSessionKey();
//
//        String key = Constant.RedisPrefix.LOCK_AUTH + ":" + workUserId;
//        Lock obtain = redisLockRegistry.obtain(key);
//        if (!obtain.tryLock(2, TimeUnit.SECONDS)) {
//            log.error("请勿重复授权");
//            return null;
//        }
//        try {
//
//            User user = userService.lambdaQuery()
//                    .eq(User::getWorkUserId, workUserId)
//                    .eq(User::getStatus,true)
//                    .eq(User::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
//                    .one();
//            if (user != null) {
//                user.setWorkSessionKey(sessionKey);
//                user.setLastLoginTime(new Date());
//                user.updateById();
//                return this.supplyUser(user);
//            }
//            //获取企业微信个人信息
//            WxCpUser wxCpUser = workWechatLogic.getUser(workUserId,currentCompanyWechat);
//            if (wxCpUser == null) {
//                List<EnterpriseWechatWorker> list = enterpriseWechatWorkerService.lambdaQuery()
//                        .eq(EnterpriseWechatWorker::getWechatUserId, workUserId)
//                        .eq(EnterpriseWechatWorker::getCorpId,currentCompanyWechat.getCorpId()).list();
//                if (list.size() > 0) {
//                    EnterpriseWechatWorker enterpriseWechatWorker = list.get(0);
//                    wxCpUser = new WxCpUser();
//                    wxCpUser.setMobile(enterpriseWechatWorker.getMobile());
//                    wxCpUser.setGender(Gender.UNDEFINED);
//                    wxCpUser.setAvatar(enterpriseWechatWorker.getQrCode());
//                    wxCpUser.setName(enterpriseWechatWorker.getName());
//                    wxCpUser.setStatus(1);
//                    wxCpUser.setQrCode(enterpriseWechatWorker.getQrCode());
//                }
//            }
//            if (wxCpUser == null) {
//                log.error("企业微信授权失败，workUserId:{}", workUserId);
//                throw new RemoteServiceException("授权失败，请联系相关人员");
//            }
//
//            //查询是否能根据手机号查询到微信用户
//            if(StringUtils.isNotBlank(wxCpUser.getMobile())){
//                user = this.getUserByMobile(wxCpUser.getMobile(),currentCompanyWechat.getCompanyWechatId());
//            }
//            Integer count = userService.lambdaQuery()
//                    .eq(User::getWorkUserId, workUserId)
//                    .eq(User::getType, UserTypeEnum.SERVICE.toString())
//                    .eq(User::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
//                    .count();
//            if (user == null) {
//                user = new User();
//                user.setMobile(wxCpUser.getMobile());
//                user.setNickName(wxCpUser.getName());
//                if(wxCpUser.getGender() != null) {
//                    user.setSex(wxCpUser.getGender().getGenderName());
//                }
//                user.setAvatar(wxCpUser.getAvatar());
//                user.setStatus(wxCpUser.getStatus() == 1);
//
//                if (count < 1) {
//                    user.setWorkName(wxCpUser.getName());
//                    user.setWorkPhone(wxCpUser.getMobile());
//                    user.setWorkUserId(workUserId);
//                    user.setType(UserTypeEnum.SERVICE.toString());
//                    user.setPosition(wxCpUser.getPosition());
//                    user.setWorkQrcode(wxCpUser.getQrCode());
//                    user.setWorkSessionKey(sessionKey);
//                }
//                user.setLastLoginTime(new Date());
//                user.setCreateTime(new Date());
//                user.setCompanyWechatId(currentCompanyWechat.getCompanyWechatId());
//                user.setCompanyName(currentCompanyWechat.getCompanyName());
//                user.insert();
//            } else {
//                if (!user.getStatus()) {
//                    throw new RemoteServiceException("用户已被冻结");
//                }
//                if (count < 1) {
//                    user.setWorkUserId(workUserId);
//                    user.setWorkName(wxCpUser.getName());
//                    user.setWorkPhone(wxCpUser.getMobile());
//                    user.setWorkQrcode(wxCpUser.getQrCode());
//                    user.setType(UserTypeEnum.SERVICE.toString());
//                    user.setWorkSessionKey(sessionKey);
//                }
//                user.setLastLoginTime(new Date());
//                user.updateById();
//            }
//            return this.supplyUser(user);
//        } finally {
//            obtain.unlock();
//        }
//    }


    /**
     * 返回小程序用户登录需要的信息
     *
     * @param user
     * @return
     */
    private UserWxBean supplyUser(User user) {
        UserWxBean userWxBean = new UserWxBean();
        String name = user.getNickName();
        if (StringUtils.isBlank(name)) {
            name = "小程序用户";
        }
        String token = JwtUtils.createJWT(user.getUserId(), name, 7 * 24 * 60 * 60 * 1000);
        BeanUtils.copyProperties(user, userWxBean);
        userWxBean.setToken(token);
        userWxBean.setShoppingCartNums(shoppingCartLogic.total(userWxBean.getUserId()));
        redisUtil.set(Constant.RedisPrefix.TOKEN_WX + token, userWxBean.getUserId(), 7 * 24 * 60 * 60 * 1000);
        return userWxBean;
    }

    private UserWxBean appUser(User user) {
        UserWxBean userWxBean = new UserWxBean();
        String token = JwtUtils.createJWT(user.getUserId(), user.getNickName(), 7 * 24 * 60 * 60);
        BeanUtils.copyProperties(user, userWxBean);
        userWxBean.setToken(token);
        redisUtil.set(Constant.RedisPrefix.TOKEN_WX + token, userWxBean.getUserId(), 7 * 24 * 60 * 60);
        redisUtil.set(Constant.RedisPrefix.TOKEN_APP_USER + token, user, 7 * 24 * 60 * 60);
        return userWxBean;
    }

    /**
     * 绑定业务员
     */
    public void bind(String userId, String serviceId, String serviceOpenId) {
        if (StringUtils.isBlank(serviceId) && StringUtils.isBlank(serviceOpenId)) {
            return;
        }
        User user = userService.getById(userId);
        User service = null;
        if (StringUtils.isNotBlank(serviceId)) {
            service = userService.getById(serviceId);
        } else {
            service = userService.lambdaQuery().eq(User::getMiniOpenId, serviceOpenId).last("limit 1").one();
        }
        if (service == null) {
            return;
        }
        //绑定业务员
        if (user.getType().equals(UserTypeEnum.GENERAL.toString())
                && (service.getType().equals(UserTypeEnum.SERVICE.toString()) || service.getType().equals(UserTypeEnum.WORKER.toString()))) {
            user.setServiceId(serviceId);
            user.setServiceTime(new Date());
        }
        //第一个业务员
//        if(StringUtils.isBlank(user.getFirstServiceId())){
//            user.setFirstServiceId(serviceId);
//            user.setFirstServiceTime(new Date());
//        }

        //判断是否为团长
        if (!user.getPromotionGroupLeader()) {
            if (service.getPromotionGroupLeader()) {
                user.setPromotionGroupUserId(serviceId);
            } else {
                String promotionGroupUserId = service.getPromotionGroupUserId();
                user.setPromotionGroupUserId(promotionGroupUserId);
            }
        }

        user.updateById();

    }

    public User getUserByMobile(String mobile, String companyWechatId) {
        return userService.lambdaQuery()
                .eq(User::getMobile, mobile)
                .eq(User::getStatus, true)
                .eq(User::getCompanyWechatId, companyWechatId).one();
    }

    /**
     * 获取绑定业务员小程序码
     */
    public String bindQrCode(HttpServletRequest request) throws RemoteServiceException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        String userId = CommonUtils.getUserId(request);
        User user = userService.lambdaQuery()
                .eq(User::getUserId, userId)
                .eq(User::getStatus, true)
                .one();
        if (user == null) {
            throw new RemoteServiceException("用户不存在");
        }
        if (StringUtils.isNotBlank(user.getBindQrcode())) {
            return user.getBindQrcode();
        }
        String qrcode = null;
        try {
            qrcode = wechatLogic.getQrcode(QrCodeEnum.BIND.toString().toLowerCase(Locale.ROOT),
                    user.getUserId(), user.getUserId(), currentCompanyWechat.getCompanyWechatId());
            if (StringUtils.isNotBlank(qrcode)) {
                user.setBindQrcode(qrcode);
                userService.updateById(user);
            }
        } catch (Exception e) {
            log.error("获取绑定业务员小程序码失败", e);
        }
        return qrcode;

    }


    public RankBean rank(HttpServletRequest request) throws RemoteServiceException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        String userId = CommonUtils.getUserId(request);
        User user = userService.lambdaQuery()
                .eq(User::getUserId, userId)
                .eq(User::getStatus, true)
                .one();
        if (user == null || StringUtils.equals(user.getType(), UserTypeEnum.GENERAL.getKey())) {
            throw new RemoteServiceException("业务员不存在");
        }

        Date now = new Date();
        Date endTime = DateConputeUtils.getCurrentMonthStart(now);
        Date startTime = DateConputeUtils.getLastMonthStart(now);
        Date endTimeDay = DateConputeUtils.getCurrentDayStart(now);
        RankBean rankBean = new RankBean();
        List<RankItemBean> rankItemBeans = getRankList(orderShareRankMapper.queryRankList(null, endTime, endTimeDay, currentCompanyWechat.getCompanyWechatId()));

        List<RankItemBean> myRanks = null;
        if (rankItemBeans != null && rankItemBeans.size() > 0) {
            rankBean.setRankList(rankItemBeans.size() > 10 ? rankItemBeans.subList(0, 10) : rankItemBeans);
            //此处的workUserId就是userId
            myRanks = rankItemBeans.stream()
                    .filter(o -> o.getWorkUserId() != null && o.getWorkUserId().equals(user.getUserId()))
                    .limit(1)
                    .collect(Collectors.toList());
        }
        RankItemBean myrank = myRanks != null && myRanks.size() > 0 ? myRanks.get(0) : orderShareRankMapper.queryWorkerInfo(user.getUserId(), currentCompanyWechat.getCompanyWechatId());
        rankBean.setMyRank(myrank);

        BigDecimal previousIncome = new BigDecimal("0.00");
        BigDecimal currentIncome = new BigDecimal("0.00");
        List<RankItemBean> previous = getRankList(orderShareRankMapper.queryRankList(user.getUserId(), startTime, endTime, currentCompanyWechat.getCompanyWechatId()));
        List<RankItemBean> current = getRankList(orderShareRankMapper.queryRankList(user.getUserId(), endTime, endTimeDay, currentCompanyWechat.getCompanyWechatId()));
        if (previous != null && previous.size() > 0) {
            previousIncome = previous.get(0).getTotal();
        }
        if (current != null && current.size() > 0) {
            currentIncome = current.get(0).getTotal();
        }

        rankBean.setUpOrDown(currentIncome.compareTo(previousIncome) > 0 ? true : false);
        rankBean.setIncome(currentIncome);
        Calendar date = Calendar.getInstance();
        date.setTime(endTimeDay);
        //date.add(Calendar.SECOND, -1);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        rankBean.setStartPeriod(simpleDateFormat.format(endTime));
        rankBean.setEndPeriod(simpleDateFormat.format(date.getTime()));
        return rankBean;
    }


    public List<RankItemBean> getRankList(List<RankItemBean> list) {
        for (int i = 1; i <= list.size(); i++) {
            list.get(0).setRanking(i);
        }
        return list;
    }


    /**
     * 解除绑定
     */
    public void unBind() {
        //满30天自动解绑
        Date timeByDay = DateUtils.getTimeByDay(new Date(), -30);
        userService.lambdaUpdate().set(User::getServiceId, "").set(User::getServiceTime, null)
                .ne(User::getServiceId, "")
                .lt(User::getServiceTime, timeByDay)
                .eq(User::getType, UserTypeEnum.GENERAL.toString())
                .update();
    }


    //手机号码授权
//    @Transactional
//    public UserWxBean getWxMobile(String iv, String encryptedData, String userId,HttpServletRequest request) throws Exception {
//        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
//        UserWxBean userWxBean = new UserWxBean();
//        User user = this.userService.getById(userId);
//        if (null == user) {
//            throw new RemoteServiceException("用户信息为空" + userId);
//        }
//        WxMaService maService = wechatLogic.getMaService(currentCompanyWechat.getCompanyWechatId());
//        WxMaPhoneNumberInfo phoneNoInfo = maService.getUserService().getPhoneNoInfo(user.getSessionKey(), encryptedData, iv);
//        String mobile = phoneNoInfo.getPhoneNumber();
//        if(StringUtils.isBlank(mobile)){
//            throw new RemoteServiceException("手机号授权失败");
//        }
////        byte[] resultByte = AesCbcUtil.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(user.getSessionKey()), Base64.decodeBase64(iv));
////        if (null == resultByte || resultByte.length < 0) {
////            throw new RemoteServiceException("手机号授权失败");
////        }
////        String userInfo = new String(resultByte, "UTF-8");
////        Map<String, Object> map = Utils.stringToMap(userInfo);
////        log.info("授权手机号response:{}", JSONObject.toJSONString(map));
////        //获取手机号码
////        String mobile = String.valueOf(map.get("phoneNumber"));
//
//        //判断该手机号是否为业务员
////        List<EnterpriseWechatWorker> list = enterpriseWechatWorkerService.lambdaQuery()
////                .eq(EnterpriseWechatWorker::getMobile, mobile)
////                .eq(EnterpriseWechatWorker::getCorpId,currentCompanyWechat.getCorpId())
////                .list();
//
//        //根据手机号查询是否存在企业微信用户
//        User workUser = this.getUserByMobile(mobile,currentCompanyWechat.getCompanyWechatId());
//        if (workUser == null) {
//            //企业微信用户为空，则直接授权手机号。并根据手机号判断是否存在于微信成员表如果存在则为业务员
//            user.setMobile(mobile);
//            if (list.size() > 0) {
//                String workUserId = list.get(0).getWechatUserId();
//                Integer count = userService.lambdaQuery()
//                        .eq(User::getWorkUserId, workUserId)
//                        .eq(User::getType, UserTypeEnum.SERVICE.toString())
//                        .eq(User::getCompanyWechatId,currentCompanyWechat.getCompanyWechatId())
//                        .count();
//                if (count < 1) {
//                    user.setType(UserTypeEnum.SERVICE.toString());
//                    user.setWorkName(list.get(0).getName());
//                    user.setWorkUserId(workUserId);
//                    user.setWorkPhone(list.get(0).getMobile());
//                    user.setWorkQrcode(list.get(0).getQrCode());
//                    user.setPosition(list.get(0).getPosition());
//                }
//            }
//            user.updateById();
//
//            String token = JwtUtils.createJWT(user.getUserId(), user.getOpenId(), 7 * 24 * 60 * 60 * 1000);
//            BeanUtils.copyProperties(user, userWxBean);
//            userWxBean.setToken(token);
//
//        } else {
//            //企业微信不为空，则将数据绑定到企业微信,并删除授权openid的用户数据
//            workUser.setOpenId(user.getOpenId());
//            workUser.updateById();
//            user.deleteById();
//
//            String token = JwtUtils.createJWT(workUser.getUserId(), workUser.getOpenId(), 7 * 24 * 60 * 60 * 1000);
//            BeanUtils.copyProperties(workUser, userWxBean);
//            userWxBean.setToken(token);
//        }
//        return userWxBean;
//    }


    //保存用户信息
    public User saveUserInfo(String userId, String nickName, String sex, String avatarUrl, String country, String province, String city) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        if (Objects.nonNull(currentCompanyWechat.getUser()) && currentCompanyWechat.getUser().getType().equals(UserTypeEnum.WORKER.getKey())) {
            nickName = null;
        }
        User user = new User();
        user.setUserId(userId);
        user.setNickName(nickName);
        user.setSex(sex);
        user.setAvatar(avatarUrl);
        user.setCountry(country);
        user.setProvince(province);
        user.setCity(city);
        user.updateById();
        return user;
    }


    /**
     * 个人信息
     */
    public UserWxBean userDetail(String userId, HttpServletRequest request) throws RemoteServiceException {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        User user = userService.getById(userId);
        if (user == null) {
            throw new RemoteServiceException(ResponseHelper.ResponseCode_AUTH_ERROR, "请求不合法");
        }
        //授权手机号后检查是否有预设置的师傅身份信息
        if (StringUtils.isNotBlank(user.getMobile())) {
            userTypeInit(user);
        }
        UserWxBean userWxBean = new UserWxBean();
        BeanUtils.copyProperties(user, userWxBean);
        userWxBean.setShoppingCartNums(shoppingCartLogic.total(userWxBean.getUserId()));
        //userWxBean.setServiceWorkerBean(userInfoMapper.queryWebsit(user.getUserId()));
        userWxBean.setCompanyWechatMobile(currentCompanyWechat.getLinkPhone());
        userWxBean.setModuleMaterialPart(currentCompanyWechat.getModuleMaterialPart());
        userWxBean.setModuleWb(currentCompanyWechat.getModuleWb());
        userWxBean.setModuleYb(currentCompanyWechat.getModuleYb());
        userWxBean.setModuleEs(currentCompanyWechat.getModuleEs());
        userWxBean.setStorePay(currentCompanyWechat.getStorePay());
        final AdminCompanyWechat companyWechat = adminCompanyWechatService.getById(userWxBean.getCompanyWechatId());
        if (Objects.nonNull(companyWechat)) {
            userWxBean.setIsShowLease(companyWechat.getModuleZl());
            userWxBean.setCompanyType(companyWechat.getCompanyType());
            userWxBean.setAppModuleJson(companyWechat.getAppModuleJson());
        }


        return userWxBean;
    }

    public void addUserLog(User user) {


        if (userLogService.lambdaQuery().eq(UserLog::getUserId, user.getUserId())
                .between(UserLog::getCreateTime, DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date())).eq(UserLog::getType, "LOGIN").count() < 1
        ) {
            UserLog userLog = new UserLog();
            userLog.setType("LOGIN");
            userLog.setCompanyWechatId(user.getCompanyWechatId());
            userLog.setCompanyName(user.getCompanyName());
            userLog.setUserId(user.getUserId());
            userLog.setLoginType(IsYesNoEnum.NO.getKey());
            userLog.setMiniType(user.getType());

            userLog.insert();
        }


        if (userLogService.lambdaQuery().eq(UserLog::getUserId, user.getUserId())
                .eq(UserLog::getCreateTime, new Date()).eq(UserLog::getType, "SEE").count() < 1
        ) {

            UserLog userLog = new UserLog();
            userLog.setType("SEE");
            userLog.setCompanyWechatId(user.getCompanyWechatId());
            userLog.setCompanyName(user.getCompanyName());
            userLog.setUserId(user.getUserId());
            userLog.setLoginType(IsYesNoEnum.NO.getKey());
            userLog.setMiniType(user.getType());
            userLog.insert();

        }

    }

    /**
     * 我的收益
     */
    public MyProfitBean myProfit(String userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return null;
        }
        MyProfitBean myProfitBean = myProfitMapper.queryProfitSum(user.getUserId());
        if (myProfitBean != null) {
            myProfitBean.setTotalAmount(myProfitBean.getPaidAmount().add(myProfitBean.getWaitingAmount()));
        } else {
            myProfitBean = new MyProfitBean();
            BigDecimal zero = new BigDecimal("0.00");
            myProfitBean.setPaidAmount(zero);
            myProfitBean.setWaitingAmount(zero);
            myProfitBean.setTotalAmount(zero);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //今日收益
        BigDecimal today = myProfitMapper.queryProfitSumByTime(user.getUserId(), sdf.format(DateUtil.beginOfDay(new Date())), sdf.format(new Date()));
        ///本月收益
        BigDecimal toMonth = myProfitMapper.queryProfitSumByTime(user.getUserId(), sdf.format(DateUtil.beginOfMonth(new Date())), sdf.format(new Date()));

        myProfitBean.setToday(today);
        myProfitBean.setToMonth(toMonth);
        return myProfitBean;
    }


    public IPage<OrderShareBean> myProfitList(String userId, String status, Integer pageNum, Integer pageSize) {
        User user = userService.getById(userId);
        if (user == null) {
            return null;
        }
//        return orderShareService.lambdaQuery()
//                .eq(OrderShare::getOpenId,user.getOpenId())
//                .ne(OrderShare::getWorkUserId,"")
//                .eq(StringUtils.isNotBlank(status),OrderShare::getStatus,status)
//                .eq(OrderShare::getCompanyWechatId,user.getCompanyWechatId())
//                .orderByDesc(OrderShare::getCreateTime)
//                .page(new Page<>(pageNum, pageSize));
        return myProfitMapper.queryOrderShareList(new Page<>(pageNum, pageSize), user.getUserId(), status);
    }

    /**
     * 总收益
     */
    public BigDecimal totalProfit(String userId) {
        User user = userService.getById(userId);
        if (user == null || StringUtils.equals(user.getType(), UserTypeEnum.GENERAL.getKey())) {
            return null;
        }
        //商城商品收益
        List<OrderShare> list1 = orderShareService.lambdaQuery()
                .eq(OrderShare::getOpenId, user.getOpenId())
                .eq(OrderShare::getCompanyWechatId, user.getCompanyWechatId())
                .and(v -> v.eq(OrderShare::getWorkUserId, user.getUserId()))
                .eq(OrderShare::getStatus, OrderShareStatusEnum.OVER.toString())
                .list();
        //延保订单收益
        List<PgIncreOrder> list2 = pgIncreOrderService.lambdaQuery()
                .eq(PgIncreOrder::getWorkerId, user.getUserId())
                .eq(PgIncreOrder::getSettleStatus, OrderShareStatusEnum.OVER.toString())
                .eq(PgIncreOrder::getPayStatus, PayStatusEnum.PAID.getKey())
                .list();
        if (list1.size() == 0 && list2.size() == 0) {
            return new BigDecimal(0);
        }

        BigDecimal sum1 = list1.stream().map(OrderShare::getAmount).reduce(BigDecimal::add).orElse(new BigDecimal(0));
        BigDecimal sum2 = list2.stream().map(PgIncreOrder::getWorkerAmount).reduce(BigDecimal::add).orElse(new BigDecimal(0));
        return sum1.add(sum2);
    }


    /**
     * 我的客户
     */
    public IPage<User> customerList(String userId, Integer pageNum, Integer pageSize) {
        IPage<User> page = userService.lambdaQuery().eq(User::getServiceId, userId).page(new Page<>(pageNum, pageSize));
        return page;
    }

    /**
     * 我的经理
     */
    public User parentUser(String userId) {
        User user = userService.getById(userId);
        if (StringUtils.isNotBlank(user.getServiceId())) {
            User parentUser = userService.getById(user.getServiceId());
            return parentUser;
        }
        return null;
    }

    /**
     * 新增用户访问记录
     */
    public void addVisit(HttpServletRequest request, String userId) {
        try {
            CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
            UserVisit userVisit = new UserVisit();
            userVisit.setUserId(userId);
            userVisit.setVisitTime(new Date());
            userVisit.setCompanyWechatId(currentCompanyWechat.getCurrentCompanyWechatId());
            userVisit.setCompanyName(currentCompanyWechat.getCurrentCompanyName());
            userVisit.insert();
        } catch (Exception e) {
            log.error("新增用户访问记录失败", e);
        }
    }

    /**
     * 设置为默认网点
     *
     * @param websitId
     */
    public void defaultWebsit(String websitId) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        userService.lambdaUpdate()
                .set(User::getDefaultWebsitId, websitId)
                .eq(User::getUserId, currentCompanyWechat.getUserId()).update();
    }

    /**
     * 入驻的网点列表
     *
     * @return
     */
    public List<AdminWebsitApplyBean> websitList(Boolean isAll, String increId, Boolean isIncre, String lng, String lat) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
//        List<AdminWebsit> list = adminWebsitService.lambdaQuery()
//                .eq(AdminWebsit::getCompanyWechatId, currentCompanyWechat.getCurrentCompanyWechatId())
//                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
//                .list();
        lng = StringUtils.isBlank(lng) ? "0" : lng;
        lat = StringUtils.isBlank(lat) ? "0" : lat;

        User user = userService.getById(currentCompanyWechat.getUserId());

        List<WebsitUser> websitUserList = websitUserService.lambdaQuery()
                .eq(WebsitUser::getUserId, currentCompanyWechat.getUserId())
                .list();

        Map<String, WebsitUser> websitUserMap = websitUserList.stream().collect(Collectors.toMap(v -> v.getWebsitId(), Function.identity()));

        //非查询所有，只取已入驻成功的网点
        List<String> websitIds = null;
        if (isAll == null || !isAll) {
            websitIds = websitUserList.stream()
                    .filter(v -> StringUtils.equals(v.getExamineStatus(), ExamineStatusEnum.OK.getKey()))
                    .map(WebsitUser::getWebsitId).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(websitIds)) {
                return new ArrayList<>();
            }
        }

        //延保筛选对应网点
        if (!StringUtil.isEmpty(increId)) {
            List<String> websitIncre = pgIncreWebsitService.lambdaQuery().eq(PgIncreWebsit::getPgIncreId, increId)
                    .select(PgIncreWebsit::getWebsitId).list().stream().map(PgIncreWebsit::getWebsitId).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(websitIncre) || CollectionUtils.isEmpty(websitIds)) {
                return new ArrayList<>();
            }
            websitIds = websitIds.stream()
                    .filter(v -> websitIncre.contains(v))
                    .collect(Collectors.toList());

        }

        List<WebsitVO> list = commonMapper.websitList(lng, lat, websitIds, isIncre, currentCompanyWechat.getCompanyWechatId());

        List<AdminWebsitApplyBean> adminWebsitApplyBeans = BeanUtil.copyToList(list, AdminWebsitApplyBean.class);
        for (AdminWebsitApplyBean bean : adminWebsitApplyBeans) {
            WebsitUser websitUser = websitUserMap.get(bean.getWebsitId());
            if (websitUser == null) {
                //未申请也未入驻
                bean.setExamineStatus("N");
            } else {
                bean.setExamineStatus(websitUser.getExamineStatus());
            }
            bean.setIsDefaultWebsit(StringUtils.equals(bean.getWebsitId(), user.getDefaultWebsitId()));
        }
        return adminWebsitApplyBeans;
    }


    /**
     * 入驻
     *
     * @param userApplyBean
     */
    @Transactional
    public void apply(UserApplyBean userApplyBean) {

        String name = userApplyBean.getName();
        String type = userApplyBean.getType().getKey();
        String websitId = userApplyBean.getWebsitId();
        String idCard = userApplyBean.getIdCard();
        String idCardImg = userApplyBean.getIdCardImg();
        String bankAccount = userApplyBean.getBankAccount();
        List<WorkerImg> workerImgs = userApplyBean.getWorkerImgs();

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        User user = userService.getById(currentCompanyWechat.getUserId());
        if (StringUtils.isAnyBlank(name, type)) {
            throw new RemoteServiceException("缺乏必填的参数");
        }

        //入驻分销员
        if (type.equals(UserTypeEnum.SERVICE.getKey())) {
            if (!user.getType().equals(UserTypeEnum.GENERAL.toString())) {
                throw new RemoteServiceException("当前用户类型不可申请成为分销员");
            }
            if (StringUtils.equals(user.getType(), UserTypeEnum.SERVICE.getKey())) {
                throw new RemoteServiceException("请勿重复入驻分销员");
            }
            //判断是否存在待审批入驻师傅的记录
            Integer count1 = websitUserService.lambdaQuery()
                    .eq(WebsitUser::getUserId, user.getUserId())
                    .eq(WebsitUser::getExamineStatus, OrderExamineEnum.WAIT.toString())
                    .count();
            if (count1 > 0) {
                throw new RemoteServiceException("已存在入驻师傅待审批的信息，请等待处理");
            }
            user.setExamineStatus(OrderExamineEnum.WAIT.toString());
            user.setExamineRemark("");
            user.setExamineBy("");
        }
        //入驻师傅
        if (type.equals(UserTypeEnum.WORKER.getKey())) {
            if (StringUtils.isAnyBlank(idCard, idCardImg)) {
                throw new RemoteServiceException("缺乏必填的参数");
            }
            if (StringUtils.isBlank(websitId)) {
                throw new RemoteServiceException("请选择网点入驻");
            }
            if (user.getExamineStatus().equals(OrderExamineEnum.WAIT.toString())) {
                throw new RemoteServiceException("已存在入驻分销员待审批的信息，请等待处理");
            }
            //判断是否已入驻
            Integer count = websitUserService.lambdaQuery()
                    .eq(WebsitUser::getUserId, user.getUserId())
                    .eq(WebsitUser::getWebsitId, websitId)
                    .ne(WebsitUser::getExamineStatus, OrderExamineEnum.FAIL.toString())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException("您已入驻当前网点");
            }

            websitUserService.lambdaUpdate().eq(WebsitUser::getUserId, user.getUserId()).eq(WebsitUser::getWebsitId, websitId).remove();

            WebsitUser websitUser = new WebsitUser();
            websitUser.setWebsitId(websitId);
            websitUser.setUserId(user.getUserId());
            websitUser.setCompanyWechatId(user.getCompanyWechatId());
            websitUser.setCompanyWechatName(user.getCompanyName());
            websitUser.setCreateTime(new Date());
            websitUser.setExamineStatus(OrderExamineEnum.WAIT.toString());
            websitUser.setBankAccount(bankAccount);
            websitUser.insert();
        }

        if (StringUtils.isNotBlank(idCard) && idCard.length() != 18) {
            throw new RemoteServiceException("请输入正确的身份证号");
        }
        user.setNickName(name);
        user.setIdCard(idCard);
        user.setIdCardImg(idCardImg);
        //user.setWebsitId(websitId);
        user.setApplyType(type);
        user.setApplyWebsitId(websitId);
        user.setApplyTime(new Date());
        user.updateById();

        if (CollectionUtils.isNotEmpty(workerImgs)) {
            for (WorkerImg workerImg : workerImgs) {
                workerImg.setWebsitId(websitId);
                workerImg.setWorkerId(currentCompanyWechat.getUserId());
            }
            workerImgService.saveBatch(workerImgs);
        }

    }


    /**
     * 我的统计
     */
    public MyCountBean myCount(String userId) {
        //收藏数量
        Integer count = goodsFavoriteService.lambdaQuery().eq(GoodsFavorite::getUserId, userId).count();
        //我的优惠券
        List<UserCoupon> userCoupons = couponLogic.myCoupon(userId);
        MyCountBean myCountBean = new MyCountBean();
        myCountBean.setAmount(this.totalProfit(userId));
        myCountBean.setCollect(count);
        myCountBean.setCoupon(userCoupons.size());
        return myCountBean;
    }

    public IPage<SettleMonthWagesWorkerBean> mySettle(Integer pageNum, Integer pageSize) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        User user = userService.getById(currentCompanyWechat.getUserId());
        IPage<SettleMonthWagesWorkerBean> workerPage = commonMapper.queryUserSettle(new Page(pageNum, pageSize), user.getCompanyWechatId(), user.getNickName());

        return workerPage;
    }

    public List<SettleExpenseItem> mySettleItem(String settleMonthWagesId) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        User user = userService.getById(currentCompanyWechat.getUserId());
        final List<SettleExpenseItem> expenseItemList = settleExpenseItemService.lambdaQuery()
                .eq(SettleExpenseItem::getCompanyWechatId, user.getCompanyWechatId())
                .eq(SettleExpenseItem::getSettleMonthWagesId, settleMonthWagesId)
                .and(v -> v.eq(SettleExpenseItem::getWorkerName1, user.getNickName())
                        .or()
                        .eq(SettleExpenseItem::getWorkerName2, user.getNickName())
                )
                .list();
        for (SettleExpenseItem item : expenseItemList) {
            if (StringUtils.isNotBlank(item.getUserName())) {
                item.setUserName(item.getUserName().charAt(0) + "**");
            }
            if (StringUtils.isNotBlank(item.getUserMobile())) {
                item.setUserMobile(item.getUserMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            }
            if (StringUtils.isNotBlank(item.getUserAddress()) && item.getUserAddress().length() > 9) {
                item.setUserAddress("******" + item.getUserAddress().substring(item.getUserAddress().length() - 9));
            }
        }
        return expenseItemList;
    }

    public SettleExpenseItem mySettleItemDetail(String id) {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();
        User user = userService.getById(currentCompanyWechat.getUserId());
        return settleExpenseItemService.lambdaQuery()
                .eq(SettleExpenseItem::getCompanyWechatId, user.getCompanyWechatId())
                .eq(SettleExpenseItem::getId, id)
                .one();
    }

    public void getUserLog() {
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        if (StringUtil.isEmpty(currentCompanyWechat.getUserId()))
            return;

        User user = userService.getById(currentCompanyWechat.getUserId());

        this.addUserLog(user);
    }

    public void sendMessageCode(String mobile, String key, String vrifyCode) throws Exception {
        if (StringUtils.isEmpty(mobile) || mobile.length() < 11) {
            throw new RemoteServiceException("请输入正确手机号");
        }

        // 查询师傅手机号
        UserWait userWait = userWaitService.lambdaQuery()
                .eq(UserWait::getMobile, mobile)
                .eq(UserWait::getUserType, UserTypeEnum.WORKER.getKey())
                .last("limit 1")
                .one();
        if (Objects.isNull(userWait)) {
            final User user = userService.lambdaQuery().eq(User::getMobile, mobile)
                    .eq(User::getType, UserTypeEnum.WORKER.getKey())
                    .last("limit 1")
                    .one();

            if (Objects.isNull(user)) {
                throw new RemoteServiceException("请输入正确师傅手机号");
            }
        }

        // 向手机号发送验证码
        smsLogic.sendSms2(mobile, key, vrifyCode);
    }

    public UserWxBean workerMobileLogin(String mobile, String messageCode) throws Exception {
        Object validMessageCode = redisUtil.get(Constant.RedisPrefix.SMS + ":" + mobile);
        if (Objects.isNull(validMessageCode)) {
            throw new RemoteServiceException("短信验证码过期");
        }

        if (!messageCode.equals(validMessageCode)) {
            throw new RemoteServiceException("短信验证码错误");
        }

        final AdminCompanyWechat wechat = adminCompanyWechatService.lambdaQuery()
                .last("limit 1")
                .one();

        User user = this.initAppUser(wechat, mobile);

        return this.appUser(user);
    }

    private User initAppUser(AdminCompanyWechat wechat, String mobile) throws Exception {
        User user = userService.lambdaQuery()
                .eq(User::getMobile, mobile)
                .eq(User::getType, UserTypeEnum.WORKER.getKey())
                .last("limit 1")
                .one();;
        if (Objects.isNull(user)) {
            UserWait userWait = userWaitService.lambdaQuery()
                    .eq(UserWait::getMobile, mobile)
                    .eq(UserWait::getUserType, UserTypeEnum.WORKER.getKey())
                    .last("limit 1")
                    .one();

            if (Objects.isNull(userWait)) {
                throw new RemoteServiceException("无师傅信息");
            }
        }

        String key = Constant.RedisPrefix.LOCK_AUTH + ":" + mobile;
        Lock obtain = redisLockRegistry.obtain(key);
        if (!obtain.tryLock(2, TimeUnit.SECONDS)) {
            log.error("请勿重复登录");
            return null;
        }

        try {
            //如果用户不存在则新注册
            if (Objects.isNull(user) ) {
                user = new User();
                user.setUserId(IdWorker.getIdStr());
                user.setLastLoginTime(new Date());
                user.setCreateTime(new Date());
                user.setMobile(mobile);
                user.setCompanyWechatId(wechat.getCompanyWechatId());
                user.setCompanyName(wechat.getCompanyName());
                userService.save(user);
            } else {
                //如果用户存在，并更新相关信息
                if (!user.getStatus()) {
                    throw new RemoteServiceException("用户已被冻结");
                }
                user.setLastLoginTime(new Date());
                //授权手机号
                user.updateById();
            }

            this.userTypeInit2(user);

            return user;
        } finally {
            obtain.unlock();
        }
    }

    public void addVisit(UserWxBean userWxBean) {
        UserVisit userVisit = new UserVisit();
        userVisit.setUserId(userWxBean.getUserId());
        userVisit.setVisitTime(new Date());
        userVisit.setCompanyWechatId(userWxBean.getCompanyWechatId());
        userVisit.setCompanyName(userWxBean.getCompanyName());
        userVisit.insert();
    }

    public void workerMobileLogout(HttpServletRequest request) {
        String token = CommonUtils.getToken(request);
        redisUtil.del(Constant.RedisPrefix.TOKEN_WX + token, Constant.RedisPrefix.TOKEN_APP_USER + token);
    }
}
