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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
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.ExcelData;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.member.GoodsVisitDetail;
import com.gree.mall.manager.bean.member.MemberBean;
import com.gree.mall.manager.bean.member.MemberSortBean;
import com.gree.mall.manager.bean.user.UserApplyBean;
import com.gree.mall.manager.bean.user.UserWxBean;
import com.gree.mall.manager.commonmapper.CustomGoodsMapper;
import com.gree.mall.manager.commonmapper.CustomMemberMapper;
import com.gree.mall.manager.commonmapper.CustomWebsitMapper;
import com.gree.mall.manager.commonmapper.WxCustomerMapper;
import com.gree.mall.manager.enums.UserTypeEnum;
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 lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Autowired;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

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

    @Autowired
    UserService userService;
    @Autowired
    UserAddressService userAddressService;
    @Autowired
    GoodsFavoriteService goodsFavoriteService;
    @Autowired
    GoodsVisitService goodsVisitService;
    @Autowired
    CustomGoodsMapper customGoodsMapper;
    @Autowired
    private WxCustomerMapper wxCustomerMapper;
    @Autowired
    private CustomMemberMapper customMemberMapper;
    @Autowired
    private EnterpriseWechatWorkerService enterpriseWechatWorkerService;
    @Autowired
    private CustomWebsitMapper customWebsitMapper;

    @Autowired
    CouponLogic couponLogic;
    @Autowired
    OrderShareLogic orderShareLogic;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    WechatLogic wechatLogic;
    @Autowired
    PromotionGroupLogic promotionGroupLogic;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    UserServiceApplyService userServiceApplyService;
    @Autowired
    UserServiceWaitService userServiceWaitService;
    @Autowired
    GoodsService goodsService;


    /**
     * 会员列表
     *
     * @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,List<String> websitIds,List<String> companyIds) {

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

        LambdaQueryWrapper<User> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        memberLambdaQueryWrapper
                .in(CollectionUtils.isNotEmpty(companyWechatIds), User::getCompanyId, companyWechatIds)
                .in(CollectionUtils.isNotEmpty(adminWebsitIds), User::getWebsitId, adminWebsitIds)
                .in(CollectionUtils.isNotEmpty(companyIds), User::getCompanyId, companyIds)
                .in(CollectionUtils.isNotEmpty(websitIds), User::getWebsitId, websitIds)
                .eq(isExchangeCode != null,User::getIsExchangeCode,isExchangeCode)
                .eq(promotionGroupLeader != null, User::getPromotionGroupLeader, promotionGroupLeader)
                .eq(StringUtils.isNotEmpty(type), User::getType, type)
                .eq(innerr != null,User::getInnerr,innerr)
                // .in(!(adminWebsitBean.getType() && org.apache.commons.lang3.StringUtils.isEmpty(websitId)), User::getWebsitNumber, websitNoList)
                .between(StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime), User::getCreateTime, startTime, endTime)
                .and(v -> v.ne(User::getMobile, "").or().ne(User::getWorkPhone, ""))
                .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.isNotEmpty(websitId)){
//            websitNoList = customWebsitMapper.queryById(websitId);
//        }

      /*  List<String> websitNoList = new ArrayList<>();
        AdminWebsitBean adminWebsitBean = CommonUtils.getAdminUser(request);
        if (adminWebsitBean.getType()) {
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(websitId)) {
                websitNoList = customWebsitMapper.queryById(websitId);
            }else {
                websitNoList = null;
            }
        } else {
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(adminWebsitBean.getWeidsitIds())) {
                websitNoList = adminWebsitBean.getWeidsitIds().stream().map(WebsitZone::getWebsitNumber).collect(Collectors.toList());
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(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.getAdminCompanyIds();
        List<String> websitIds = adminUser.getAdminWebsitIds();

        List<MemberBean> userList = customMemberMapper.queryUser(type, keyword, null, startTime, endTime, companyWechatIds,websitIds);

        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 user
     */
    public void update(User user) {
        user.updateById();
    }

    /**
     * 修改会员业务状态
     */
    @Transactional
    public void changeServiceUser(String userId, String websitId, String websitName, String workUserId, String workName,
                                  String position, String mobile, Boolean isService) {
        User user = userService.getById(userId);
        if (user.getInnerr()) {
            throw new RemoteServiceException("请先取消内部人员");
        }

        if (StringUtil.isEmpty(websitId) && isService) {
            throw new RemoteServiceException("必须要有所属网点");
        }

        final List<String> userIds = Collections.singletonList(userId);
        this.batchChangeServiceUser(userIds, isService);

        if (isService) {
            if (StringUtils.isBlank(workUserId) || StringUtils.isBlank(workName) || StringUtils.isBlank(position) ||
                    StringUtils.isBlank(mobile)) {
                throw new RemoteServiceException("请填写关键信息");
            }
            userService.lambdaUpdate()
                    .set(User::getWorkUserId, workUserId)
                    .set(User::getWebsitId, websitId)
                    .set(User::getWebsitName, websitName)
                    .set(User::getWorkName, workName)
                    .set(User::getPosition, position)
                    .set(User::getWorkPhone, mobile)
                    .set(User::getWorkCreateTime, new Date())
                    .eq(User::getUserId, user.getUserId())
                    .update();
        }
    }

    private void batchChangeServiceUser(List<String> userIds, Boolean isService) {
        // 1.将用户设为业务员或非业务员
        userService.lambdaUpdate()
                .set(User::getType, isService ? UserTypeEnum.SERVICE.toString() : UserTypeEnum.GENERAL.toString())
                .set(isService, User::getWorkCreateTime, DateUtil.date())
                .set(!isService, User::getWorkCreateTime, null)
                .in(User::getUserId, userIds)
                .update();

        // 2.启用或禁用 用户分享优惠券
        couponLogic.updateUserCouponTransfer(userIds, isService);
    }

    /**
     * 修改会员内部人员状态
     */
    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();
    }

    /**
     * 导入跟新内部人员状态
     */
    @Transactional
    public void localUpdateInner(HttpServletRequest request, MultipartFile multipartFile) throws IOException {
        final AdminUserCom adminUser = commonLogic.getAdminUser(request);

        List<Object> objects = ExcelUtils.importExcel(multipartFile);
        List<User> phoneList = new ArrayList<>();
        List<User> innerPhoneList = new ArrayList<>();
        for (int i = 0; i < objects.size(); i++) {
            List<String> rows = (List<String>) objects.get(i);
            CommonUtils.initList(rows, 7);
            String typeStr = Objects.isNull(rows.get(1)) ? "业务员" : rows.get(1);
            boolean isInner = typeStr.equals("内部人员");
            User user = new User();
            user.setMobile(rows.get(0));
            user.setWebsitId(StringUtils.isNotBlank(rows.get(2)) ? rows.get(2).trim() : null);
            user.setWebsitName(StringUtils.isNotBlank(rows.get(3)) ? rows.get(3).trim() : null);
            user.setPosition(StringUtils.isNotBlank(rows.get(4)) ? rows.get(4).trim() : null);
            user.setWorkName(StringUtils.isNotBlank(rows.get(5)) ? rows.get(5).trim() : null);
            user.setWorkUserId(StringUtils.isNotBlank(rows.get(6)) ? rows.get(6).trim() : null);
            user.setWorkPhone(user.getMobile());
            user.setInnerr(isInner);
            if (!isInner) {
                if (StringUtils.isBlank(user.getWorkUserId())) {
                    throw new RemoteServiceException(user.getMobile() + "账号必填");
                }
                if (StringUtils.isBlank(user.getWorkName())) {
                    throw new RemoteServiceException(user.getMobile() + "姓名必填");
                }
                if (StringUtils.isBlank(user.getPosition())) {
                    throw new RemoteServiceException(user.getMobile() + "职位必填");
                }
                phoneList.add(user);
            } else {
                innerPhoneList.add(user);
            }
        }

        // 检查业务员手机号是否有重复的
        final Map<String, List<User>> UserGroupMap = phoneList.stream().collect(Collectors.groupingBy(User::getMobile));
        for (Map.Entry<String, List<User>> entry : UserGroupMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                throw new RemoteServiceException("文档“业务员”有重复手机号 " + entry.getKey());
            }
        }

        List<User> userList = userService.lambdaQuery()
                .in(User::getMobile, phoneList.stream()
                        .map(User::getMobile)
                        .collect(Collectors.toList()))
                .eq(User::getType, UserTypeEnum.GENERAL)
                .eq(User::getStatus, true)
                .list();

        // 变成业务员
        final List<String> userIds = userList.stream().map(User::getUserId).collect(Collectors.toList());
        List<User> upUserList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(userIds)) {
            this.batchChangeServiceUser(userIds, true);

            // 更新会员资料
            final Map<String, User> importUserMap = phoneList.stream().collect(Collectors.toMap(User::getMobile, Function.identity()));
            for (User user : userList) {
                if (importUserMap.containsKey(user.getMobile())) {
                    User newUser = new User();
                    User importUser = importUserMap.get(user.getMobile());
                    newUser.setUserId(user.getUserId())
                            .setMobile(user.getMobile())
                            .setWorkUserId(importUser.getWorkUserId())
                            .setWorkName(importUser.getWorkName())
                            .setWorkPhone(user.getMobile())
                            .setWorkCreateTime(new Date())
                            .setPosition(importUser.getPosition())
                            .setWebsitId(importUser.getWebsitId())
                            .setWebsitName(importUser.getWebsitName());
                    upUserList.add(newUser);

                }
            }
            if (CollectionUtil.isNotEmpty(upUserList)) {
                userService.saveOrUpdateBatch(upUserList);
            }

        }

        // 获取已存在记录
        final List<UserServiceWait> existWaits = userServiceWaitService.lambdaQuery()
                .in(UserServiceWait::getMobile, phoneList.stream().map(User::getMobile).collect(Collectors.toList()))
                .list();
        Map<String, UserServiceWait> waitMap = existWaits.stream().collect(Collectors.toMap(UserServiceWait::getMobile, Function.identity()));

        // 遍历产生待处理记录
        List<UserServiceWait> waitList = new ArrayList<>();
        final Map<String, User> upUserMap = upUserList.stream().collect(Collectors.toMap(User::getMobile, Function.identity()));
        final DateTime curDate = DateUtil.date();
        for (User waitUser : phoneList) {
            if (waitMap.containsKey(waitUser.getMobile())) {
                // 如果存在记录忽略生成此手机号对象
                waitList.add(waitMap.get(waitUser.getMobile()));
                continue;
            }
            User user = userService.lambdaQuery()
                    .in(User::getMobile, waitUser.getMobile()).last("limit 1")
                    .one();

            if (user == null )
                throw new RemoteServiceException("手机号"+waitUser.getMobile()+"未找到用户");

            UserServiceWait wait = new UserServiceWait();
            wait.setMobile(waitUser.getMobile())
                    .setWebsitId(user.getWebsitId())
                    .setWebsitName(user.getWebsitName())
                    .setCompanyId(user.getCompanyId())
                    .setCompanyName(user.getCompanyName())
                    .setPosition(waitUser.getPosition())
                    .setName(waitUser.getWorkName())
                    .setWorkerId(waitUser.getWorkUserId())
                    .setCreateTime(curDate)
                    .setCreateBy(adminUser.getNickName())
                    .setCompanyName(user.getCompanyName());
            waitList.add(wait);
        }
        // 待处理记录不为空批量插入
        if (CollectionUtil.isNotEmpty(waitList)) {
            for (UserServiceWait serviceWait : waitList) {
                // 本次更新用户资料在历史等待处理记录匹配到手机号
                if (upUserMap.containsKey(serviceWait.getMobile())) {
                    final User upUser = upUserMap.get(serviceWait.getMobile());
                    serviceWait.setUserId(upUser.getUserId())
                            .setIsBind(true)
                            .setUpdateTime(new Date());
                }
            }

            userServiceWaitService.saveOrUpdateBatch(waitList);
        }

        if (CollectionUtil.isNotEmpty(innerPhoneList)) {
            // 升级为内部业务员
            userService.lambdaUpdate()
                    .set(User::getInnerr, true)
                    .in(User::getMobile, innerPhoneList.stream()
                            .map(User::getMobile)
                            .collect(Collectors.toList()))
                    .eq(User::getType, UserTypeEnum.SERVICE)
                    .eq(User::getStatus, true)
                    .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.getCompanyId());

        //查询客户数
        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())
                    .one();
            if (worker != null) {
                userWxBean.setPosition(worker.getPosition());
                userWxBean.setWorkerName(worker.getName());
                userWxBean.setWorkerPhone(worker.getMobile());
            }
        }
        if (StringUtils.isNotEmpty(user.getServiceId())) {
            User service = userService.getById(user.getServiceId());
            if (service != null) {
                userWxBean.setServiceName(service.getWorkName());
                userWxBean.setServicePhone(service.getWorkPhone());
            }
        }

        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<GoodsVisitDetail> goodsVisitList(String userId, Integer pageNo, Integer pageSize) {
        Page<GoodsVisit> page = goodsVisitService.lambdaQuery().eq(GoodsVisit::getUserId, userId).page(new Page<>(pageNo, pageSize));

        if (CollectionUtils.isEmpty(page.getRecords()))
            return new Page<>();

        Page<GoodsVisitDetail> goodsVisitDetailPage = new Page<>();

        List<GoodsVisitDetail> goodsVisitDetails = new ArrayList<>();

        for (GoodsVisit record : page.getRecords()) {
            GoodsVisitDetail goodsVisitDetail = BeanUtil.toBean(record, GoodsVisitDetail.class);
            Goods goods = goodsService.getById(goodsVisitDetail.getGoodsId());
            if (goods != null)
                goodsVisitDetail.setStatus(goods.getStatus());

            goodsVisitDetails.add(goodsVisitDetail);
        }
        goodsVisitDetailPage.setRecords(goodsVisitDetails);
        goodsVisitDetailPage.setTotal(page.getTotal());
        goodsVisitDetailPage.setCurrent(page.getCurrent());
        goodsVisitDetailPage.setSize(page.getSize());
        goodsVisitDetailPage.setPages(page.getPages());
        return goodsVisitDetailPage;
    }

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

    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();
    }

    public IPage<UserApplyBean> applyPage(HttpServletRequest request, String keyword, String status, Integer pageNum, Integer pageSize) {
        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getAdminCompanyIds();
        List<String> adminWebsitIds = adminUser.getAdminWebsitIds();
        IPage<UserApplyBean> page = wxCustomerMapper.queryServiceApplyList(new Page<>(pageNum, pageSize), companyWechatIds, keyword, status,adminWebsitIds);
        return page;
    }

    @Transactional
    public void examineApply(String id, String websitId, String websitName, String workUserId, String workName, String position, String mobile, Boolean isOK) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        UserServiceApply apply = userServiceApplyService.getById(id);

        if (StringUtils.isBlank(workUserId)) {
            throw new RemoteServiceException("账号必填");
        }
        if (StringUtils.isBlank(workName)) {
            throw new RemoteServiceException("姓名必填");
        }
        if (StringUtils.isBlank(position)) {
            throw new RemoteServiceException("职位必填");
        }
        if (StringUtils.isBlank(mobile)) {
            throw new RemoteServiceException("手机号必填");
        }

        apply.setStatus(isOK ? "OK" : "FAIL")
                .setUpdateTime(DateUtil.date())
                .setUpdateBy(adminUser.getNickName())
                .updateById();

        // 通过更新用户为业务员并注入手机号
        if (isOK) {
            final List<String> userIds = Collections.singletonList(apply.getUserId());
            this.batchChangeServiceUser(userIds, true);

            userService.lambdaUpdate()
                    .set(User::getWorkUserId, workUserId)
                    .set(User::getWebsitId, websitId)
                    .set(User::getWebsitName, websitName)
                    .set(User::getWorkName, workName)
                    .set(User::getPosition, position)
                    .set(User::getWorkPhone, mobile)
                    .set(User::getWorkCreateTime, new Date())
                    .set(User::getMobile, apply.getMobile())
                    .eq(User::getUserId, apply.getUserId())
                    .update();
        }
    }

    public IPage<UserServiceWait> importMemberList(String websitId, String websitName, String workUserId, String workName,
                                                   String position, String mobile, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        return userServiceWaitService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminCompanyIds()), UserServiceWait::getCompanyId, adminUser.getAdminCompanyIds())
                .in(CollectionUtils.isNotEmpty(adminUser.getAdminWebsitIds()), UserServiceWait::getWebsitId, adminUser.getAdminWebsitIds())
                .like(StringUtils.isNotBlank(websitId), UserServiceWait::getWebsitId, websitId)
                .like(StringUtils.isNotBlank(websitName), UserServiceWait::getWebsitName, websitName)
                .like(StringUtils.isNotBlank(workUserId), UserServiceWait::getWorkerId, workUserId)
                .like(StringUtils.isNotBlank(workName), UserServiceWait::getName, workName)
                .like(StringUtils.isNotBlank(position), UserServiceWait::getPosition, position)
                .like(StringUtils.isNotBlank(mobile), UserServiceWait::getMobile, mobile)
                .orderByDesc(UserServiceWait::getCreateTime)
                .page(new Page<>(pageNum, pageSize));
    }
}
