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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.listvo.User2VO;
import com.gree.mall.manager.bean.listvo.UserCustomerVO;
import com.gree.mall.manager.bean.listvo.UserVO;
import com.gree.mall.manager.bean.listvo.workorder.UserWaitVO;
import com.gree.mall.manager.bean.member.MemberSortBean;
import com.gree.mall.manager.bean.member.UserApplyBean;
import com.gree.mall.manager.bean.user.UserApplyWorkerBean;
import com.gree.mall.manager.bean.user.UserDetailBean;
import com.gree.mall.manager.bean.user.UserWxBean;
import com.gree.mall.manager.bean.user.UserWxCustomerBean;
import com.gree.mall.manager.commonmapper.*;
import com.gree.mall.manager.enums.ExamineStatusEnum;
import com.gree.mall.manager.enums.UserTypeEnum;
import com.gree.mall.manager.enums.admin.AdminWebsitTypeEnum;
import com.gree.mall.manager.enums.base.BaseEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.activity.PromotionGroupLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.WechatLogic;
import com.gree.mall.manager.logic.coupon.CouponLogic;
import com.gree.mall.manager.logic.order.OrderShareLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.RedisUtil;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.utils.excel.ExcelUtils;
import com.gree.mall.manager.zfire.bean.WorkerParamBean;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

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

    private final UserService userService;
    private final UserAddressService userAddressService;
    private final GoodsFavoriteService goodsFavoriteService;
    private final GoodsVisitService goodsVisitService;
    private final CustomGoodsMapper customGoodsMapper;
    private final WxCustomerMapper wxCustomerMapper;
    private final CustomMemberMapper customMemberMapper;
//    private final EnterpriseWechatWorkerService enterpriseWechatWorkerService;
    private final CustomWebsitMapper customWebsitMapper;
    private final WebsitUserService websitUserService;
    private final CommonMapper commonMapper;
    private final AdminWebsitService adminWebsitService;
    private final UserWaitService userWaitService;
    private final WorkerImgService workerImgService;
//    private final WorkWechatLogic workWechatLogic;
    private final CouponLogic couponLogic;
    private final OrderShareLogic orderShareLogic;
    private final RedisUtil redisUtil;
    private final WechatLogic wechatLogic;
    private final PromotionGroupLogic promotionGroupLogic;
    private final CommonLogic commonLogic;
    private final AdminCompanyWechatService adminCompanyWechatService;
    private final PgOrderBaseService pgOrderBaseService;
    private final PgOrderWorkerService pgOrderWorkerService;
    private final SettleDailyBankAccountService settleDailyBankAccountService;


    /**
     * 客户列表-v2
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<UserCustomerVO> userCustomerList(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean.setCompanyWechatId(adminUser.getCompanyWechatId());
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean, UserCustomerVO.class);

        IPage<UserCustomerVO> userVOIPage = commonMapper.userCustomerList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return userVOIPage;
    }


    /**
     * 师傅列表-v2
     *
     * @param userZfireParamBean
     * @return
     */
    public IPage<UserVO> page2(WorkerParamBean userZfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        boolean isOK = false;
        if (CollectionUtils.isNotEmpty(userZfireParamBean.getParams())) {
            final long count = userZfireParamBean.getParams().stream()
                    .filter(v -> v.getParam().equals("b.examine_status") && v.getValue().equals(ExamineStatusEnum.OK.getKey()))
                    .count();
            isOK = count > 0;
        }

        ZfireParamBean zfireParamBean = FieldUtils.supplyParam(userZfireParamBean, UserVO.class, adminUser);

        IPage<UserVO> userVOIPage = commonMapper.userList(new Page(userZfireParamBean.getPageNum(), userZfireParamBean.getPageSize()), userZfireParamBean, null, isOK);
        return userVOIPage;
    }

    /**
     * 分销员列表-v2
     *
     * @param userZfireParamBean
     * @return
     */
    public IPage<User2VO> userServiceList(ZfireParamBean userZfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        ZfireParamBean zfireParamBean = FieldUtils.supplyParam(userZfireParamBean, User2VO.class, adminUser);

        IPage<User2VO> userVOIPage = commonMapper.userServiceList(new Page(userZfireParamBean.getPageNum(), userZfireParamBean.getPageSize()), zfireParamBean);
        return userVOIPage;
    }

    /**
     * 待入驻用户信息列表-v2
     *
     * @param zfireParamBean
     * @return
     */
    public IPage<UserWaitVO> userWaitList(ZfireParamBean zfireParamBean) {
        FieldUtils.supplyParam(zfireParamBean, UserWaitVO.class, commonLogic.getAdminUser());
        IPage<UserWaitVO> page = commonMapper.userWaitList(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
        return page;
    }


    /**
     * 待入驻用户信息-删除
     *
     * @param id
     */
    public void userWaitDel(String id) {
        userWaitService.removeById(id);
    }


    /**
     * 修改师傅资料
     *  @param userId
     * @param websitId
     * @param name
     * @param idCard
     * @param idCardImg
     * @param bankAccount
     * @param workerNumber
     */
    @Transactional
    public void updateWorker(String userId, String websitId, String name, String idCard, String idCardImg, String bankAccount, Boolean isEs, String workerNumber) {
        WebsitUser websitUser = websitUserService.lambdaQuery()
                .eq(WebsitUser::getUserId, userId)
                .eq(WebsitUser::getWebsitId, websitId).last("limit 1").one();
        websitUser.setBankAccount(bankAccount);
        websitUser.setWorkerNumber(workerNumber);
        websitUser.updateById();

        User user = userService.getById(userId);
        user.setNickName(name);
        user.setIdCard(idCard);
        user.setIdCardImg(idCardImg);
        user.setBankAccount(bankAccount);
        user.setIsEs(isEs);
        user.updateById();

        pgOrderWorkerService.lambdaUpdate().eq(PgOrderWorker::getWorkerNumber,workerNumber)
                .set(PgOrderWorker::getWorkerId,user.getUserId())
                .set(!StringUtil.isEmpty(user.getMobile()),PgOrderWorker::getWorkerMobile,user.getMobile())
                .update();

        pgOrderBaseService.lambdaUpdate()
                .eq(PgOrderBase::getWorkerNumber,workerNumber)
                .set(PgOrderBase::getWorkerId,user.getUserId())
                .set(!StringUtil.isEmpty(user.getMobile()),PgOrderBase::getWorkerMobile,user.getMobile())
                .update();
    }

    /**
     * 导入待入驻用户信息
     */
    @Transactional
    public void importData(List<Object> datas) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<AdminWebsit> list = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.C.getKey())
                .list();
        Map<String, AdminWebsit> websitMap = list.stream().collect(Collectors.toMap(AdminWebsit::getName, Function.identity()));
        int index = 0;
        //先删除
        userWaitService.lambdaUpdate()
                .eq(UserWait::getCompanyWechatId, adminUser.getCompanyWechatId())
                .remove();

        List<UserWait> userWaits = new ArrayList<>();
        for (Object o : datas) {
            index++;
            String errPrefix = "第" + index + "行";
            List<Object> row = (List<Object>) o;
            CommonUtils.initList2(row, 10);
            String name = (String) row.get(0);
            String idcard = (String) row.get(1);
            String mobile = (String) row.get(2);
            String userType = (String) row.get(3);
            String websitName = (String) row.get(4);
            String bankAccount = (String) row.get(5);
            String workerNumber = (String) row.get(6);
            if (StringUtils.isAnyBlank(name, mobile, userType)) {
                throw new RemoteServiceException(errPrefix + "黄色区域为必填项");
            }
            if (mobile.length() != 11) {
                throw new RemoteServiceException(errPrefix + "手机号格式不正确");
            }
            UserTypeEnum userTypeEnum = BaseEnum.valueToEnum(UserTypeEnum.class, userType);
            if (Objects.isNull(userTypeEnum) || userTypeEnum == UserTypeEnum.GENERAL) {
                throw new RemoteServiceException(errPrefix + "用户类型填写不合规，请填写【师傅】或者【分销员】");
            }
            AdminWebsit adminWebsit = null;
            if (userTypeEnum == UserTypeEnum.WORKER) {
                if (StringUtils.isBlank(websitName)) {
                    throw new RemoteServiceException(errPrefix + "网点名称不能为空");
                }
                adminWebsit = websitMap.get(websitName);
                if (Objects.isNull(adminWebsit)) {
                    throw new RemoteServiceException(errPrefix + "网点不存在");
                }
            }
            if (StringUtils.isBlank(workerNumber)) {
                throw new RemoteServiceException(errPrefix + "师傅编号不能为空");
            }
            UserWait userWait = new UserWait();
            userWait.setUserType(userTypeEnum.getKey());
            userWait.setMobile(mobile);
            if (Objects.nonNull(adminWebsit)) {
                userWait.setWebsitId(adminWebsit.getWebsitId());
                userWait.setWebsitName(adminWebsit.getName());
                //入驻已存在的师傅到网点
                User worker = userService.lambdaQuery()
                        .eq(User::getMobile, mobile)
                        .eq(User::getType, UserTypeEnum.WORKER.getKey())
                        .last("limit 1")
                        .one();
                if (Objects.nonNull(worker)) {
                    this.saveWebsitUser(adminWebsit.getWebsitId(), worker, bankAccount, workerNumber, "系统导入初始化");
                }
            }

            userWait.setName(name);
            userWait.setIdcard(idcard);
            userWait.setCompanyWechatId(adminUser.getCompanyWechatId());
            userWait.setCompanyWechatName(adminUser.getCompanyName());
            userWait.setBankAccount(bankAccount);
            userWait.setWorkerNumber(workerNumber);
            userWaits.add(userWait);
        }
        userWaitService.saveBatch(userWaits);
    }


    /**
     * 师傅审核详情
     *
     * @param id
     * @return
     */
    public UserApplyWorkerBean workerExamineDetail(String id) {
        WebsitUser websitUser = websitUserService.getById(id);
        User user = userService.getById(websitUser.getUserId());
        user.setExamineStatus(websitUser.getExamineStatus());
        user.setExamineRemark(websitUser.getExamineRemark());
        user.setApplyWebsitId(websitUser.getWebsitId());

        AdminWebsit adminWebsit = adminWebsitService.getById(user.getApplyWebsitId());
        if (adminWebsit == null) {
            throw new RemoteServiceException("申请入驻的网点不存在");
        }

        UserApplyWorkerBean bean = new UserApplyWorkerBean();
        bean.setId(id);
        bean.setUserId(user.getUserId());
        bean.setNickName(user.getNickName());
        bean.setWorkerNumber(websitUser.getWorkerNumber());
        bean.setMobile(user.getMobile());
        bean.setIdCard(user.getIdCard());
        bean.setIdCardImg(user.getIdCardImg());
        bean.setCompanyName(user.getCompanyName());
        bean.setWebsitId(adminWebsit.getWebsitId());
        bean.setWebsitName(adminWebsit.getName());
        bean.setExamineRemark(websitUser.getExamineRemark());
        bean.setExamineStatus(websitUser.getExamineStatus());
        bean.setExamineBy(websitUser.getExamineBy());
        bean.setBankAccount(websitUser.getBankAccount());
        bean.setIsEs(user.getIsEs());
        List<WorkerImg> list = workerImgService.lambdaQuery()
                .eq(WorkerImg::getWebsitId, websitUser.getWebsitId())
                .eq(WorkerImg::getWorkerId, websitUser.getUserId()).list();
        bean.setWorkerImgList(list);

        return bean;
    }

    /**
     * 审批
     *
     * @param id
     * @param examineStatus
     * @Param examineRemark 审核备注
     */
    @Transactional
    public void examine(String id, String examineStatus, String examineRemark) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        WebsitUser websitUser = websitUserService.getById(id);
        if (!StringUtils.equals(websitUser.getExamineStatus(), ExamineStatusEnum.WAIT.getKey())) {
            throw new RemoteServiceException("非待审批状态不可审批");
        }
        if (StringUtils.isBlank(websitUser.getWorkerNumber())) {
            throw new RemoteServiceException("师傅编号不能为空");
        }
        final Integer count = websitUserService.lambdaQuery()
                .eq(WebsitUser::getWebsitId, websitUser.getWebsitId())
                .eq(WebsitUser::getWorkerNumber, websitUser.getWorkerNumber())
                .eq(WebsitUser::getExamineStatus, ExamineStatusEnum.OK.getKey())
                .count();
        if (count > 0) {
            throw new RemoteServiceException(websitUser.getWebsitId() + "网点编号下已存在" + websitUser.getWorkerNumber() + "师傅编号");
        }
        websitUser.setExamineStatus(examineStatus);
        websitUser.setExamineTime(new Date());
        websitUser.setExamineBy(adminUser.getNickName());
        websitUser.setExamineRemark(examineRemark);
        websitUser.updateById();

        User user = userService.getById(websitUser.getUserId());
        if (examineStatus.equals(ExamineStatusEnum.OK.getKey())) {
            user.setType(UserTypeEnum.WORKER.getKey());
            user.setWorkerNumber(websitUser.getWorkerNumber());
        }
        user.updateById();
    }


    /**
     * 分销员审核
     *
     * @param userId
     * @param examineStatus
     * @param examineRemark
     */
    public void shareExamine(String userId, ExamineStatusEnum examineStatus, String examineRemark) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        User user = userService.getById(userId);
        if (!user.getType().equals(UserTypeEnum.GENERAL.getKey())) {
            throw new RemoteServiceException("当前用户类型不可审批");
        }
        user.setExamineStatus(examineStatus.getKey());
        user.setExamineRemark(examineRemark);
        user.setExamineBy(adminUser.getNickName());
        user.setExamineTime(new Date());
        if (user.getExamineStatus().equals(ExamineStatusEnum.OK.getKey())) {
            user.setType(UserTypeEnum.SERVICE.getKey());
        }
        user.updateById();
    }


    /**
     * 批量设置取消内部分销员
     *
     * @param userIds
     * @param innerr
     */
    public void batchInner(List<String> userIds, Boolean innerr) {
        userService.lambdaUpdate().set(User::getInnerr, innerr).in(User::getUserId, userIds).update();
    }


    /**
     * 批量设置二手商品发布权限
     *
     * @param userIds
     */
    public void batchEs(List<String> userIds, Boolean isEs) {
        userService.lambdaUpdate().set(User::getIsEs, isEs).in(User::getUserId, userIds).update();
    }


    @Transactional
    public void batchType(UserApplyBean userApplyBean) {

        String userId = userApplyBean.getUserId();
        UserTypeEnum type = userApplyBean.getType();
        String websitId = userApplyBean.getWebsitId();
        String idCard = userApplyBean.getIdCard();
        String idCardImg = userApplyBean.getIdCardImg();

        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (StringUtils.equals(type.getKey(), UserTypeEnum.WORKER.getKey())) {
            if (StringUtils.isBlank(websitId)) {
                throw new RemoteServiceException("请为师傅选择网点");
            }
        }

        //非入驻网点，则删除当前用户的所有网点
        if (StringUtils.isBlank(websitId)) {
            websitUserService.lambdaUpdate().eq(WebsitUser::getUserId, userId).remove();
        }
        //否则重新生成当前网点的入驻信息
        if (StringUtils.isNotBlank(websitId)) {

            User user = userService.getById(userId);
            this.saveWebsitUser(websitId, user, userApplyBean.getBankAccount(), userApplyBean.getWorkerNumber(), "系统手动设置");
        }

        userService.lambdaUpdate()
                .set(StringUtils.isNotBlank(userApplyBean.getName()), User::getNickName, userApplyBean.getName())
                .set(StringUtils.isNotBlank(userApplyBean.getBankAccount()), User::getBankAccount, userApplyBean.getBankAccount())
                .set(User::getExamineStatus, ExamineStatusEnum.OK.getKey())
                .set(User::getExamineTime, new Date())
                .set(User::getExamineBy, adminUser.getNickName())
                .set(User::getExamineRemark, "系统手动配置")
                .set(User::getApplyType, type.getKey())
                .set(User::getType, type.getKey())
                .set(StringUtils.isNotBlank(idCard), User::getIdCard, idCard)
                .set(StringUtils.isNotBlank(idCardImg), User::getIdCardImg, idCardImg)
                .set(!StringUtils.equals(type.getKey(), UserTypeEnum.WORKER.getKey()), User::getWorkerNumber, null)
                .in(User::getUserId, userId)
                .update();

        //其他图片
        if (CollectionUtils.isNotEmpty(userApplyBean.getWorkerImgs())) {
            workerImgService.lambdaUpdate().eq(WorkerImg::getWebsitId, websitId).eq(WorkerImg::getWorkerId, userId).remove();
            for (WorkerImg workerImg : userApplyBean.getWorkerImgs()) {
                workerImg.setWebsitId(websitId);
                workerImg.setWorkerId(userId);
            }
            workerImgService.saveBatch(userApplyBean.getWorkerImgs());
        }

    }

    @Transactional
    public void saveWebsitUser(String websitId, User user, String bankAccount, String workerNumber, String remark) {
        // 用户师傅编号不为空并且师傅编号与传入师傅编号不一致，抛错
        if (StringUtils.isNotBlank(user.getWorkerNumber())
                && !StringUtils.equals(user.getWorkerNumber(), workerNumber)) {
            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.setExamineStatus(ExamineStatusEnum.OK.toString());
        websitUser.setExamineRemark(remark);
        websitUser.setBankAccount(bankAccount);
        websitUser.setWorkerNumber(workerNumber);
        websitUser.insert();

        if (StringUtils.isBlank(user.getWorkerNumber())) {
            user.setWorkerNumber(workerNumber)
                    .updateById();
        }
    }


    /**
     * 用户详情-v2
     *
     * @param userId
     * @return
     */
    public UserDetailBean detailV2(String userId) {
        User user = userService.getById(userId);
        UserDetailBean userDetailBean = BeanUtil.copyProperties(user, UserDetailBean.class);
        //网点对应关系
        List<WebsitUser> list = websitUserService.lambdaQuery()
                .eq(WebsitUser::getCompanyWechatId, user.getCompanyWechatId())
                .eq(WebsitUser::getUserId, user.getUserId()).list();
        userDetailBean.setWebsitUsers(list);
        return userDetailBean;
    }


    /**
     * 会员列表
     *
     * @param keyword
     * @param startTime
     * @param endTime
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<User> page(HttpServletRequest request, String keyword, String type, Boolean promotionGroupLeader,
                            Boolean innerr, String startTime, String endTime, String sortJson, String websitId, Boolean isExchangeCode,
                            Integer pageNum, Integer pageSize) {

        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        LambdaQueryWrapper<User> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        memberLambdaQueryWrapper
                .in(CollectionUtils.isNotEmpty(companyWechatIds), User::getCompanyWechatId, companyWechatIds)
                .eq(isExchangeCode != null, User::getIsExchangeCode, isExchangeCode)
                .eq(promotionGroupLeader != null, User::getPromotionGroupLeader, promotionGroupLeader)
                .eq(StringUtils.isNotBlank(type), User::getType, type)
                .eq(innerr != null, User::getInnerr, innerr)
                // .in(!(adminWebsitBean.getType() && org.apache.commons.lang3.StringUtils.isBlank(websitId)), User::getWebsitNumber, websitNoList)
                .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), User::getCreateTime, startTime, endTime)
                .and(v -> v.ne(User::getMobile, ""))
                .and(StringUtils.isNotBlank(keyword),
                        memberLambdaQueryWrapper1 -> memberLambdaQueryWrapper1.like(User::getNickName, keyword)
                                .or()
                                .like(User::getMobile, keyword));
        if (sortJson != null && !sortJson.trim().equals("")) {
            JSONArray goodsSortBeanArray = JSON.parseArray(StringEscapeUtils.unescapeJava(sortJson));
            MemberSortBean.convertColumn(goodsSortBeanArray, memberLambdaQueryWrapper);
        } else {
            memberLambdaQueryWrapper.orderByDesc(User::getCreateTime);
        }

        return userService.page(new Page(pageNum, pageSize), memberLambdaQueryWrapper);
    }


    public void export(HttpServletRequest request, HttpServletResponse response, String keyword, String type, String websitId, String startTime, String endTime) throws Exception {

//        List<String> websitNoList = new ArrayList<>();
//        if(org.apache.commons.lang3.StringUtils.isNotBlank(websitId)){
//            websitNoList = customWebsitMapper.queryById(websitId);
//        }

      /*  List<String> websitNoList = new ArrayList<>();
        AdminWebsitBean adminWebsitBean = CommonUtils.getAdminUser(request);
        if (adminWebsitBean.getType()) {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(websitId)) {
                websitNoList = customWebsitMapper.queryById(websitId);
            }else {
                websitNoList = null;
            }
        } else {
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(adminWebsitBean.getWeidsitIds())) {
                websitNoList = adminWebsitBean.getWeidsitIds().stream().map(WebsitZone::getWebsitNumber).collect(Collectors.toList());
                if (org.apache.commons.lang3.StringUtils.isNotBlank(websitId)) {
                    List<String> websitNoListFilter = customWebsitMapper.queryById(websitId);
                    final List<String> websitNo = websitNoList;
                    websitNoList = websitNoListFilter.stream().filter(o -> websitNo.contains(o)).collect(Collectors.toList());
                }
                if(CollectionUtils.isEmpty(websitNoList)){
                    return;
                }
            }else{
                return ;
            }
        }*/

        //获取当前登录企业微信id
//        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        List<String> companyWechatIds = adminUser.getCompanyWechatIds();
//
//        List<MemberBean> userList = customMemberMapper.queryUser(type, keyword, null, startTime, endTime, companyWechatIds);
//
//        log.info("会员导出请求参数{},{},{},{}", type, keyword, startTime, endTime);
//        log.info("会员导出数据条数{}", userList == null ? 0 : userList.size());
//        String[] titles = {"序号", "微信手机号", "微信昵称", "企微名称", "企微手机号", "用户类型", "所属网点", "成为业务员时间", "所在地区"};
//        ExcelData excelData = new ExcelData();
//        List<List<Object>> rows = new ArrayList<>();
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        for (int i = 0; i < userList.size(); i++) {
//            MemberBean bean = userList.get(i);
//            List<Object> row = new ArrayList<>();
//            row.add(i + 1);
//            row.add(bean.getMobile());
//            row.add(bean.getNickName());
//            row.add(bean.getWorkName());
//            row.add(bean.getWorkPhone());
//            row.add(bean.getType().equals(UserTypeEnum.GENERAL.toString()) ? "普通用户" : "业务员");
//            row.add("");
//            row.add(bean.getCreateTime() == null ? "" : simpleDateFormat.format(bean.getCreateTime()));
//            String city = "";
//            row.add(city);
//            rows.add(row);
//        }
//        String fileName = String.format("用户信息导出_%s.xlsx", simpleDateFormat.format(new Date()));
//        excelData.setTitles(Arrays.asList(titles));
//        excelData.setName("用户信息");
//        excelData.setRows(rows);
//        ExcelUtils.exportExcel(request, response, fileName, excelData, -1, null);
    }

    /**
     * 更改会员状态
     *
     * @param userId
     * @param status
     */
    public void updateState(String userId, Boolean status) {
        userService.lambdaUpdate()
                .eq(User::getUserId, userId)
                .set(User::getStatus, status)
                .update();
    }


    /**
     * 绑定师傅的辅助师傅
     *
     * @param websitId
     * @param userId
     * @param slaveUserId
     */
    public void bindSlaveWorker(String websitId, String userId, String slaveUserId) {
        User user = userService.getById(userId);
        if (!user.getType().equals(UserTypeEnum.WORKER.getKey())) {
            throw new RemoteServiceException("非师傅身份不可绑定辅助师傅");
        }
        Integer count = websitUserService.lambdaQuery()
                .eq(WebsitUser::getWebsitId, websitId)
                .in(WebsitUser::getUserId, userId, slaveUserId).count();
        if (count != 2) {
            throw new RemoteServiceException("请选择同网点有效的辅助师傅");
        }
        websitUserService.lambdaUpdate()
                .set(WebsitUser::getSlaveWorkerId, slaveUserId)
                .eq(WebsitUser::getWebsitId, websitId)
                .eq(WebsitUser::getUserId, userId)
                .update();


    }


    /**
     * 会员资料修改
     *
     * @param user
     */
    public void update(User user) {
        user.updateById();
    }

    /**
     * 修改会员内部人员状态
     */
    public void updateUserInnerStatus(String userId, Boolean inner) {
        Integer count = userService.lambdaQuery()
                .eq(User::getUserId, userId)
                .eq(User::getType, UserTypeEnum.SERVICE)
                .count();
        if (count == 0) {
            throw new RemoteServiceException("只有业务员才能成为内部人员");
        }
        userService.lambdaUpdate()
                .set(User::getInnerr, inner)
                .eq(User::getUserId, userId)
                .eq(User::getType, UserTypeEnum.SERVICE)
                .update();
    }

    /**
     * 导入跟新内部人员状态
     */
    public void localUpdateInner(HttpServletRequest request, MultipartFile multipartFile) throws IOException {
        String loginCompanyWechatId = commonLogic.getAdminUser(request).getCompanyWechatId();
        if (StringUtils.isBlank(loginCompanyWechatId)) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }

        List<Object> objects = ExcelUtils.importExcel(multipartFile);
        List<String> phoneList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            phoneList.add(((List<String>) objects.get(i)).get(0));
        }

        userService.lambdaUpdate()
                .set(User::getInnerr, true)
                .in(User::getMobile, phoneList)
                .eq(User::getCompanyWechatId, loginCompanyWechatId)
                .eq(User::getType, UserTypeEnum.SERVICE)
                .update();
    }


    /**
     * 设置/取消团长
     */
    @Transactional
    public void groupleader(String userId, Boolean promotionGroupLeader) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new RemoteServiceException("用户不存在");
        }
        user.setUserId(userId);
        user.setPromotionGroupLeader(promotionGroupLeader);
        user.setPromotionGroupUserId(userId);
        user.updateById();
        //添加到所有团购活动里
        if (promotionGroupLeader) {

            //    promotionGroupLogic.addGroupUser(user);
        } else {
            promotionGroupLogic.deleteGroupUser(user);
        }
    }

    /**
     * 用户详情
     */
    public UserWxBean detail(String userId) {
        User user = userService.getById(userId);

        UserWxBean userWxBean = new UserWxBean();
        BeanUtils.copyProperties(user, userWxBean);

//        AdminCompanyWechat adminCompanyWechat = commonLogic.getAdminCompanyWechat(user.getCompanyWechatId());

        //查询客户数
        Integer count = userService.lambdaQuery().eq(User::getServiceId, userId).count();

        userWxBean.setCustomerNums(count);
        userWxBean.setTotalAmount(orderShareLogic.totalAmount(userId));

//        if (user.getType().equals(UserTypeEnum.SERVICE.toString())) {
//            EnterpriseWechatWorker worker = enterpriseWechatWorkerService.lambdaQuery()
//                    .eq(EnterpriseWechatWorker::getWechatUserId, userWxBean.getWorkUserId())
//                    .eq(EnterpriseWechatWorker::getCorpId,adminCompanyWechat.getCorpId())
//                    .one();
//            if (worker != null) {
//                userWxBean.setPosition(worker.getPosition());
//                userWxBean.setWorkerName(worker.getName());
//                userWxBean.setWorkerPhone(worker.getMobile());
//            }
//        }
        if (StringUtils.isNotBlank(user.getServiceId())) {
            User service = userService.getById(user.getServiceId());
            if (service != null) {
                userWxBean.setServiceName(service.getNickName());
                userWxBean.setServicePhone(service.getMobile());
            }
        }


        return userWxBean;
    }


    /**
     * 修改用户昵称
     */
    public void updateUserNickName(String userId, String newNickName) {

        userService.lambdaUpdate().set(User::getNickName, newNickName).eq(User::getUserId, userId).update();

    }

    /**
     * 用户地址
     */
    public IPage<UserAddress> addressList(String userId, Integer pageNo, Integer pageSize) {
        IPage<UserAddress> page = userAddressService.lambdaQuery().eq(UserAddress::getUserId, userId)
                .orderByDesc(UserAddress::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
        return page;
    }

    /**
     * 我的收藏
     */
    public IPage<Goods> goodsFavoriteList(String userId, Integer pageNo, Integer pageSize) {
        IPage<Goods> goodsIPage = customGoodsMapper.myGoodsFavorite(new Page(pageNo, pageSize), userId);
        return goodsIPage;
    }

    /**
     * 我的浏览记录
     */
    public IPage<GoodsVisit> goodsVisitList(String userId, Integer pageNo, Integer pageSize) {
        return goodsVisitService.lambdaQuery()
                .eq(GoodsVisit::getUserId, userId)
                .orderByDesc(GoodsVisit::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
    }

    /**
     * 我的优惠券
     */
    public IPage<UserCoupon> couponList(String userId, Integer pageNo, Integer pageSize) {
        return couponLogic.userCouponList(userId, pageNo, pageSize);
    }

    /**
     * 我的客户
     */
    public List<UserWxCustomerBean> wxCustomerList(HttpServletRequest request, String userId) throws WxErrorException {

        User user = userService.lambdaQuery()
                .eq(User::getUserId, userId)
                .one();
//        if (user == null || StringUtils.isBlank(user.getWorkUserId())) {
//            return null;
//        }
//
//        AdminCompanyWechat adminCompanyWechat = commonLogic.getAdminCompanyWechat(user.getCompanyWechatId());
//        if (adminCompanyWechat == null) {
//            throw new RemoteServiceException("非租户账号不可操作当前信息:" + user.getCompanyWechatId());
//        }
//        List<UserWxCustomerBean> respList = new ArrayList<>();
//
//        List<WxCpExternalContactBatchInfo.ExternalContactInfo> externalContactList = workWechatLogic.
//                getCustomerByExternalUserId(user.getWorkUserId(), null, 100,adminCompanyWechat);
//        for (WxCpExternalContactBatchInfo.ExternalContactInfo data:externalContactList) {
//            UserWxCustomerBean respMsg = new UserWxCustomerBean();
//            respList.add(respMsg);
//
//            //企业微信联系人信息
//            FollowedUser followInfo = data.getFollowInfo();
//            ExternalContact externalContact = data.getExternalContact();
//
//            respMsg.setMobile(Arrays.toString(followInfo.getRemarkMobiles()));
//            respMsg.setNickName(followInfo.getRemark());
//            respMsg.setCreateTime(new Date(followInfo.getCreateTime()*1000));
//            respMsg.setUserTagId(Arrays.toString(followInfo.getTagIds()));
//            respMsg.setUnionId(externalContact.getUnionId());
//        }

        return null;
    }

    /**
     * 用户降级
     */
//    public void demotion(List<String> workUserIds) {
//        List<User> list = userService.lambdaQuery().in(User::getWorkUserId, workUserIds).list();
//        if (list.size() == 0) {
//            return;
//        }
//        List<String> userIds = list.stream().map(User::getUserId).collect(Collectors.toList());
//        //1.将用户设为普通用户
//        userService.lambdaUpdate()
//                .set(User::getType, UserTypeEnum.GENERAL.toString())
//                .in(User::getWorkUserId, workUserIds).update();
//
//        //2.禁止用户分享优惠券
//        couponLogic.updateUserCouponTransfer(userIds, false);
//    }


    /**
     * 用户升级
     */
//    public void userLevelUp(List<String> workUserIds) {
//        List<User> list = userService.lambdaQuery().in(User::getWorkUserId, workUserIds).list();
//        if (list.size() == 0) {
//            return;
//        }
//        List<String> userIds = list.stream().map(User::getUserId).collect(Collectors.toList());
//        //1.将用户设为普通用户
//        userService.lambdaUpdate()
//                .set(User::getType, UserTypeEnum.SERVICE.toString())
//                .in(User::getWorkUserId, workUserIds).update();
//
//        //2.禁止用户分享优惠券
//        couponLogic.updateUserCouponTransfer(userIds, true);
//    }
    public User getById(String userId) {
        return userService.getById(userId);
    }

    public List<User> getById(List<String> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return new ArrayList<>();
        }
        return userService.lambdaQuery().in(User::getUserId, userIds).orderByDesc(User::getCreateTime).list();
    }

    public List<User> getByMobile(List<String> mobiles) {
        if (CollectionUtils.isEmpty(mobiles)) {
            return new ArrayList<>();
        }
        return userService.lambdaQuery().in(User::getMobile, mobiles).orderByDesc(User::getCreateTime).list();
    }


    @Transactional(rollbackFor = Exception.class)
    public void userWaitUpdate(UserWait userWait) {
        userService.lambdaUpdate()
                .ne(User::getMobile,userWait.getMobile())
                .eq(User::getWorkerNumber,userWait.getWorkerNumber())
                .set(User::getType,"GENERAL")
                .set(User::getWorkerNumber,null)
                .update();

        userWait.updateById();

        userWaitService.lambdaUpdate()
                .eq(UserWait::getWorkerNumber,userWait.getWorkerNumber())
                .set(UserWait::getMobile,userWait.getMobile()).update();
    }
}
