package org.jeecg.modules.adweb.enterprise.controller;

import static org.jeecg.modules.adweb.site.service.impl.AdwebSiteServiceImpl.generateRandomEmail;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictPropertyModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FastJsonUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.RestTemplateConfig;
import org.jeecg.modules.adweb.common.constant.AdwebConstant;
import org.jeecg.modules.adweb.common.constant.NumConstant;
import org.jeecg.modules.adweb.common.dto.CommonDto;
import org.jeecg.modules.adweb.common.mapper.CommonMapper;
import org.jeecg.modules.adweb.common.service.FeishuService;
import org.jeecg.modules.adweb.common.util.MD5Util;
import org.jeecg.modules.adweb.enquiry.entity.AdwebEnquiry;
import org.jeecg.modules.adweb.enquiry.service.IAdwebEnquiryService;
import org.jeecg.modules.adweb.enquiry.service.ISubUserEmailService;
import org.jeecg.modules.adweb.enterprise.dto.CreateUserParam;
import org.jeecg.modules.adweb.enterprise.dto.EditPermissionParam;
import org.jeecg.modules.adweb.enterprise.service.SysUserPermissionService;
import org.jeecg.modules.adweb.enterprise.vo.User;
import org.jeecg.modules.adweb.site.entity.AdwebSite;
import org.jeecg.modules.adweb.site.entity.AdwebSiteUserPermission;
import org.jeecg.modules.adweb.site.entity.AdwebUserWpsite;
import org.jeecg.modules.adweb.site.service.IAdwebSiteService;
import org.jeecg.modules.adweb.site.service.IAdwebUserWpsiteService;
import org.jeecg.modules.adweb.site.service.ISiteUserPermissionService;
import org.jeecg.modules.adweb.system.entity.MasterSubAccountRelation;
import org.jeecg.modules.adweb.system.service.IMasterSubAccountRelationService;
import org.jeecg.modules.adweb.system.service.SysAdwebApi;
import org.jeecg.modules.system.entity.SysPermission;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: 企业用户管理 @Author: jeecg-boot @Date: 2022-06-10 @Version: V1.0
 */
@Tag(name = "企业用户管理")
@RestController
@RequestMapping("/enterprise/user")
@Slf4j
public class EnterpriseUserManageController {
  @Autowired private ISysUserService sysUserService;

  @Autowired private IMasterSubAccountRelationService masterSubAccountRelationService;

  @Autowired private ISysRoleService sysRoleService;

  @Autowired private ISysUserRoleService sysUserRoleService;

  @Autowired private ISiteUserPermissionService siteUserPermissionService;

  @Autowired private IAdwebSiteService adwebSiteService;

  @Resource private SysUserPermissionService sysUserPermissionService;

  @Resource private CommonMapper adwebCommonMapper;

  @Resource private IAdwebEnquiryService adwebEnquiryService;

  @Resource private SysAdwebApi sysAdwebApi;

  @Autowired private IAdwebUserWpsiteService adwebUserWpsiteService;

  @Autowired private ISubUserEmailService subUserEmailService;

  @Resource private FeishuService openFeishuMsgService;

  @AutoLog(value = "企业用户管理-分页列表查询")
  @Operation(summary = "企业用户管理-分页列表查询")
  @GetMapping(value = "/list")
  public Result<IPage<User>> queryPageList(
      SysUser user,
      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
      HttpServletRequest req) {
    Map<String, String[]> map = new HashMap(req.getParameterMap());
    map.put("order", new String[] {"asc"});

    LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
    List<String> idList =
        masterSubAccountRelationService.getSubAccountIdByMaster(loginUser.getId());
    idList.add(loginUser.getId());

    if (CollectionUtils.isEmpty(idList)) {
      return Result.OK();
    }

    QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, map);
    queryWrapper.ne("username", "_reserve_user_external");
    queryWrapper.in("id", idList);
    queryWrapper.eq("status", 1);
    String queryCondition = req.getParameter("queryCondition");
    if (StringUtils.isNotBlank(queryCondition)) {
      queryWrapper.and(
          wrapper ->
              wrapper
                  .like("username", queryCondition)
                  .or()
                  .like("realname", queryCondition)
                  .or()
                  .like("phone", queryCondition));
    }
    Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
    IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);
    // 类型转换
    IPage<User> pageList2 = converseType(pageList);
    // 序号
    this.addSeqNumber(pageList2.getRecords(), pageNo, pageSize);
    // 统计管理的询盘和产品数量
    Map<String, Integer> map1 = adwebEnquiryService.getEnquiryCount(idList);
    for (User user1 : pageList2.getRecords()) {
      if (map1.get(user1.getId()) != null) {
        user1.setEnquiryNum(map1.get(user1.getId()));
      }
    }
    // 主账户产品和询盘数量统计规则不同
    if (pageNo == 1) {
      User user1 = pageList2.getRecords().get(0);
      user1.setPrimaryAccount(true);
      user1.setEnquiryNum(adwebEnquiryService.getEnquiryCount(user1.getId()));
    }
    return Result.OK(pageList2);
  }

  /**
   * 添加
   *
   * @param param 用户的相关信息
   */
  @AutoLog(value = "企业用户管理-添加")
  @Operation(summary = "企业用户管理-添加")
  @PostMapping(value = "/add")
  public Result<SysUser> add(@RequestBody CreateUserParam param) {
    Result<SysUser> result = new Result<SysUser>();

    List<DictPropertyModel> siteRes = sysAdwebApi.queryDictInfoByDictCode("turn_inquiry_site_code");
    // 判断特殊站点
    if (CollectionUtils.isNotEmpty(siteRes)
        && StringUtils.isNotBlank(param.getSiteCode())
        && siteRes.get(0).getValue().equals(param.getSiteCode())) {
      if (StringUtils.isEmpty(param.getEmail())) {
        return result.error500("邮箱不可为空！");
      }
      // 获取主账号
      if (StringUtils.isNotEmpty(param.getMasterId())) {
        SysUser sysUser = sysUserService.getById(param.getMasterId());
        // 通过主账号id获取子账号id集合
        List<String> idList =
            masterSubAccountRelationService.getSubAccountIdByMaster(sysUser.getId());
        idList.add(sysUser.getId());
        if (CollectionUtils.isNotEmpty(idList)) {
          List<String> emailList = sysUserService.getEmailBySubIdList(idList);
          // 判断 sysUser 的电子邮件是否存在于 emailList 中
          boolean emailExists = emailList.contains(param.getEmail());
          if (emailExists) {
            return result.error500("邮箱不可重复！");
          }
        }
      }
    }
    param.setUsername(param.getUsername().trim());
    param.setRealname(param.getRealname().trim());

    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
    String masterId = sysUser.getId();
    String masterName = sysUser.getUsername();
    String masterEmail = sysUser.getEmail();
    List<Integer> siteIds = adwebSiteService.getAllSiteIdByUid(masterId);

    if (StringUtils.isNotEmpty(param.getEmail())) {
      if (param.getEmail().equals(masterEmail)) {
        return result.error500("子账户邮箱不可以与主账户邮箱一致。");
      }
      QueryWrapper<AdwebSite> queryWrapper = new QueryWrapper<>();
      List<String> codeList = siteUserPermissionService.getSiteCodeList(param.getMasterId());
      queryWrapper.in("code", codeList);
      queryWrapper.ne("status", AdwebConstant.SITE_DEL).isNull("parent_group_code");
      List<AdwebSite> siteList = adwebSiteService.list(queryWrapper);
      if (CollectionUtils.isNotEmpty(siteList)) {
        for (AdwebSite adwebSite : siteList) {
          String emailStr = adwebSite.getEnquiryEmailList();
          if (StringUtils.isNotEmpty(emailStr)) {
            List<String> emailList = FastJsonUtil.parseList(emailStr, String.class);
            for (String email : emailList) {
              if (email.equals(param.getEmail())) {
                return result.error500("子账户邮箱不可以与站点询盘配置邮箱一致。");
              }
            }
          }
        }
      }
    }

    try {
      // 创建子账户
      SysUser user = new SysUser();
      user.setUsername(param.getUsername());
      user.setRealname(param.getRealname());
      user.setPhone(param.getPhone());
      String randomEmail = generateRandomEmail();
      if (param.getSex() != null) {
        user.setSex(param.getSex());
      }
      if (StringUtils.isNotEmpty(param.getEmail())) {
        user.setEmail(param.getEmail());
      } else {
        user.setEmail(randomEmail);
      }

      user.setAvatar(param.getAvatar());
      user.setCreateTime(new Date());
      user.setUpdateTime(new Date());
      String salt = oConvertUtils.randomGen(8);
      user.setSalt(salt);
      String passwordEncode = PasswordUtil.encrypt(param.getUsername(), param.getPassword(), salt);
      user.setPassword(passwordEncode);
      user.setStatus(1);
      user.setDelFlag(CommonConstant.DEL_FLAG_0);
      user.setHasMasterAccount(CommonConstant.HAS_MASTER_ACCOUNT);
      String roleId = sysRoleService.getRoleIdByRoleCode("adweb_sub_vip");
      String relTenantIds = param.getRelTenantIds();
      sysUserService.saveUser(user, roleId, "", relTenantIds);

      // 创建父子关系
      MasterSubAccountRelation relation = new MasterSubAccountRelation();
      relation.setMasterId(masterId);
      relation.setSubId(user.getId());
      relation.setMasterName(masterName);
      relation.setSubName(user.getUsername());
      relation.setStatus(1);
      masterSubAccountRelationService.insertAccountRelation(relation);

      // 创建子账户和站点的关系
      List<AdwebSiteUserPermission> subPermissionList = new ArrayList<>();
      List<AdwebSiteUserPermission> masterPermissionList =
          siteUserPermissionService.getPermissionCode(sysUser.getId());
      for (AdwebSiteUserPermission masterPermission : masterPermissionList) {
        AdwebSiteUserPermission subPermission = new AdwebSiteUserPermission();
        subPermission.setUid(user.getId());
        subPermission.setPermissionCode(masterPermission.getPermissionCode());
        subPermission.setStatus(masterPermission.getStatus());
        subPermission.setCreateTime(new Date());
        subPermissionList.add(subPermission);
      }
      siteUserPermissionService.saveBatch(subPermissionList);

      // 给子账户创建权限
      List<SysPermission> list = adwebCommonMapper.getAdwebVipPermission();
      List<String> ids = list.stream().map(SysPermission::getId).collect(Collectors.toList());
      String permissionIds = String.join(",", ids);
      EditPermissionParam editPermissionParam = new EditPermissionParam();
      editPermissionParam.setUserId(user.getId());
      editPermissionParam.setPermissionIds(permissionIds);
      this.saveRolePermission(editPermissionParam);

      List<CommonDto> errorResults = new ArrayList<>();
      for (Integer siteId : siteIds) {
        AdwebSite adwebSite = adwebSiteService.getById(siteId);
        int userAccount = 2;
        if (StringUtils.isNotEmpty(adwebSite.getWordpressSetting())) {
          JsonObject asJsonObject =
              JsonParser.parseString(adwebSite.getWordpressSetting()).getAsJsonObject();
          if (adwebSite.getWordpressSetting().contains("userAccount")) {
            userAccount = asJsonObject.get("userAccount").getAsInt();
          }
        }

        if (userAccount == 1 && adwebSite.getCreateType().equals("wp")) {
          log.info("检查环境配置");
          String checkUserRoleUrl =
              adwebSite.getDomain() + "/wp-json/check_user_role_plugin_active/v2";
          log.info(checkUserRoleUrl);

          MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
          HttpHeaders headers = new HttpHeaders();
          headers.add("Content-Type", "application/json");
          headers.add(
              "user-agent",
              "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
          HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(paramMap, headers);

          RestTemplate restTemplate = null;
          try {
            restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
          } catch (NoSuchAlgorithmException e) {
            log.info("忽略SSL证书异常:{}", e.getMessage());
          } catch (KeyManagementException | KeyStoreException e) {
            log.info("忽略SSL证书异常:{}", e.getMessage());
          }
          ResponseEntity<String> checkPluginResponseEntity = null;
          try {
            // 获取响应结果
            if (restTemplate != null) {
              checkPluginResponseEntity =
                  restTemplate.exchange(checkUserRoleUrl, HttpMethod.GET, httpEntity, String.class);
            }

            String checkPluginResponse = checkPluginResponseEntity.getBody();
            // 获取响应结果
            JsonObject checkJsonObject = null;
            if (checkPluginResponse != null) {
              checkJsonObject = JsonParser.parseString(checkPluginResponse).getAsJsonObject();
            }
            String checkCode = checkJsonObject.get("code").getAsString();
            String checkMsg = checkJsonObject.get("msg").getAsString();
            if (!checkCode.equals("200")) {
              CommonDto commonDto = new CommonDto();
              commonDto.setType("检测插件状态");
              commonDto.setSiteName(adwebSite.getName());
              commonDto.setSiteCode(adwebSite.getCode());
              commonDto.setMsg(checkMsg);
              commonDto.setCode(Integer.parseInt(checkCode));
              errorResults.add(commonDto);
              log.info(checkCode + ":" + checkMsg);
              continue;
            } else {
              log.info("wordpress新增子账户");
              String url = adwebSite.getDomain() + "/wp-json/add_user/v2/";
              log.info(url);
              String username = param.getUsername();
              String md5Username = MD5Util.byte2Md5(username.getBytes(StandardCharsets.UTF_8));
              Map<String, String> map = new HashMap<>();
              map.put("username", md5Username);
              map.put("password", "IFQam6zx^A3DfyHqDlhWuxT1");
              map.put("email", user.getEmail());
              map.put("nickname", param.getRealname());
              map.put("type", "adweb_user_sub");

              AdwebUserWpsite adwebUserWpsite = new AdwebUserWpsite();
              adwebUserWpsite.setSiteId(siteId);
              adwebUserWpsite.setUid(user.getId());
              adwebUserWpsite.setUsername(username);
              adwebUserWpsite.setWpUsername(md5Username);
              adwebUserWpsite.setStatus(NumConstant.ONE);
              adwebUserWpsite.setUpdateTime(new Date());
              adwebUserWpsite.setWpUserpwd("IFQam6zx^A3DfyHqDlhWuxT1");
              adwebUserWpsite.setWpUserrole("adweb_user_sub");

              // 将Map转换为URL编码的请求体
              Gson gson = new Gson();
              String json = gson.toJson(map);
              log.info(json);
              HttpEntity<String> httpEntityAdd = new HttpEntity<>(json, headers);
              ResponseEntity<String> response = null;
              try {
                response = restTemplate.exchange(url, HttpMethod.POST, httpEntityAdd, String.class);
                String responseBody = response.getBody();
                if (StringUtils.isNoneEmpty(responseBody)) {
                  JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject();
                  String code = jsonObject.get("code").getAsString();
                  String msg = jsonObject.get("msg").getAsString();
                  CommonDto commonDto = new CommonDto();
                  commonDto.setType("新增wordpress用户信息");
                  commonDto.setSiteName(adwebSite.getName());
                  commonDto.setSiteCode(adwebSite.getCode());
                  commonDto.setMsg(msg);
                  commonDto.setCode(Integer.parseInt(code));
                  errorResults.add(commonDto);
                  if (!code.equals("200")) {
                    log.info(code + ":" + msg);
                    continue;
                  } else {
                    adwebUserWpsiteService.save(adwebUserWpsite);
                    log.info("wordpress新增子账户成功");
                  }
                } else {
                  CommonDto commonDto = new CommonDto();
                  commonDto.setType("wordpress新增子账户失败");
                  commonDto.setSiteName(adwebSite.getName());
                  commonDto.setSiteCode(adwebSite.getCode());
                  commonDto.setMsg("wordpress新增子账户失败：");
                  errorResults.add(commonDto);
                  log.info("wordpress新增子账户失败");
                }
              } catch (Exception e) {
                CommonDto commonDto = new CommonDto();
                commonDto.setType("请求新增wordpress用户接口失败");
                commonDto.setSiteName(adwebSite.getName());
                commonDto.setSiteCode(adwebSite.getCode());
                commonDto.setMsg("请求新增wordpress用户接口失败：" + e.getMessage().replaceAll("\"", ""));
                errorResults.add(commonDto);
                log.info("请求新增wordpress用户接口失败：{}", e.getMessage());
              }
            }
          } catch (Exception e) {
            CommonDto commonDto = new CommonDto();
            commonDto.setType("请求wordpress检测环境接口失败");
            commonDto.setSiteName(adwebSite.getName());
            commonDto.setSiteCode(adwebSite.getCode());
            commonDto.setMsg("请求wordpress检测环境接口失败" + e.getMessage().replaceAll("\"", ""));
            errorResults.add(commonDto);
            log.info("请求wordpress检测环境接口失败{}", e.getMessage());
          }
        }
      }

      if (CollectionUtils.isNotEmpty(errorResults)) {
        String title = "WordPress网站主账户新增子账户：" + param.getRealname();
        String message = "";
        for (CommonDto item : errorResults) {
          message += "**站点名称：**" + item.getSiteName() + "\n";
          if (item.getSiteCode() != null) {
            message += "**站点code：**" + item.getSiteCode() + "\n";
          }
          message += "**类型：**" + item.getType() + "\n";
          message += "**信息：**" + item.getMsg() + "\n";
          if (item.getCode() != null) {
            message += "**code：**" + item.getCode() + "\n";
          }
          message += "\n";
        }
        try {
          openFeishuMsgService.sendAdWebV3FeiShuMsg(title, message);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
          throw new RuntimeException(e);
        }
      }
      subUserEmailService.removeAll();
      result.success("添加成功！");
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      result.error500("操作失败");
    }
    return result;
  }

  /**
   * 子账户分页列表查询
   *
   * @param user
   * @param pageNo
   * @param pageSize
   * @param req
   * @return
   */
  @AutoLog(value = "企业用户管理-子账户分页列表查询")
  @Operation(summary = "企业用户管理-子账户分页列表查询")
  @GetMapping(value = "/sub/list")
  public Result<IPage<User>> querySubPageList(
      SysUser user,
      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
      @RequestParam String siteCode,
      HttpServletRequest req) {
    Map<String, String[]> map = new HashMap(req.getParameterMap());
    map.put("order", new String[] {"asc"});

    LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
    List<String> idList =
        masterSubAccountRelationService.getSubAccountIdByMaster(loginUser.getId());
    // 获取当前站点主账号
    QueryWrapper<AdwebSite> adwebSiteQueryWrapper = new QueryWrapper<>();
    adwebSiteQueryWrapper.eq("code", siteCode);
    AdwebSite adwebSite = adwebSiteService.getOne(adwebSiteQueryWrapper);
    if (adwebSite != null) {
      idList.add(adwebSite.getUid());
    }
    //        idList.add(loginUser.getId());
    if (CollectionUtils.isEmpty(idList)) {
      return Result.OK();
    }
    QueryWrapper<SysUser> queryWrapper = QueryGenerator.initQueryWrapper(user, map);
    queryWrapper.ne("username", "_reserve_user_external");
    queryWrapper.in("id", idList);
    queryWrapper.eq("status", 1);
    String queryCondition = req.getParameter("queryCondition");
    if (StringUtils.isNotEmpty(queryCondition)) {
      queryWrapper.and(
          wrapper ->
              wrapper
                  .like("username", queryCondition)
                  .or()
                  .like("realname", queryCondition)
                  .or()
                  .like("phone", queryCondition));
    }
    Page<SysUser> page = new Page<SysUser>(pageNo, pageSize);
    IPage<SysUser> pageList = sysUserService.page(page, queryWrapper);
    // 类型转换
    IPage<User> pageList2 = converseType(pageList);
    // 序号
    this.addSeqNumber(pageList2.getRecords(), pageNo, pageSize);
    // 统计管理的询盘和产品数量
    /*Map<String, Integer> map1 = adwebEnquiryService.getEnquiryCount(idList);
    Map<String, Integer> map2 = adwebMaterialProductService.getProductCount(idList);
    for (User user1 : pageList2.getRecords()) {
        if (map1.get(user1.getId()) != null) {
            user1.setEnquiryNum(map1.get(user1.getId()));
        }
        if (map2.get(user1.getId()) != null) {
            user1.setProductNum(map2.get(user1.getId()));
        }
    }*/
    // 主账户产品和询盘数量统计规则不同
    if (pageNo == 1 && CollectionUtils.isNotEmpty(pageList2.getRecords())) {
      User user1 = pageList2.getRecords().get(0);
      if (user1.getId().equals(adwebSite.getUid())) {
        user1.setPrimaryAccount(true);
        user1.setIsInquiry(2);
      }
    }
    return Result.OK(pageList2);
  }

  /** 保存角色授权 */
  @RequestMapping(value = "/saveRolePermission", method = RequestMethod.POST)
  public Result saveRolePermission(@RequestBody EditPermissionParam param) {
    String userId = param.getUserId();
    String permissionIds = param.getPermissionIds();
    try {
      sysUserPermissionService.editUserPermission(userId, permissionIds);
      return Result.OK("保存成功！");
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      return Result.error("授权失败！");
    }
  }

  /** 冻结&解冻用户 */
  @RequestMapping(value = "/frozen", method = RequestMethod.PUT)
  public Result<SysUser> frozenBatch(@RequestBody JSONObject jsonObject) {
    Result<SysUser> result = new Result<SysUser>();
    try {
      String ids = jsonObject.getString("ids");
      String status = jsonObject.getString("status");
      String[] arr = ids.split(",");
      for (String id : arr) {
        if (oConvertUtils.isNotEmpty(id)) {
          this.sysUserService.update(
              new SysUser().setStatus(Integer.parseInt(status)),
              new UpdateWrapper<SysUser>().lambda().eq(SysUser::getId, id));
          // 获取该子账户的主账户
          QueryWrapper<MasterSubAccountRelation> queryWrapper1 = new QueryWrapper<>();
          queryWrapper1.eq("sub_id", id);
          List<MasterSubAccountRelation> masterSubAccountRelationList =
              masterSubAccountRelationService.list(queryWrapper1);
          String masterUid = null;
          if (CollectionUtils.isNotEmpty(masterSubAccountRelationList)) {
            masterUid = masterSubAccountRelationList.get(0).getMasterId();
            // 把原本跟进人改成主账户
            this.adwebEnquiryService.update(
                new AdwebEnquiry().setPrincipalUid(masterUid),
                new UpdateWrapper<AdwebEnquiry>().lambda().eq(AdwebEnquiry::getPrincipalUid, id));
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      result.error500("操作失败" + e.getMessage());
    }
    subUserEmailService.removeAll();
    result.success("操作成功!");
    return result;
  }

  private IPage<User> converseType(IPage<SysUser> pageList) {
    IPage<User> pageList2 = new Page<>();
    pageList2.setPages(pageList.getPages());
    pageList2.setCurrent(pageList.getCurrent());
    pageList2.setSize(pageList.getSize());
    pageList2.setTotal(pageList.getTotal());
    if (CollectionUtils.isEmpty(pageList.getRecords())) {
      pageList2.setRecords(new ArrayList<>());
      return pageList2;
    }
    List<User> users = new ArrayList<>();
    for (SysUser sysUser : pageList.getRecords()) {
      User user = new User();
      user.setId(sysUser.getId());
      user.setUsername(sysUser.getUsername());
      user.setRealname(sysUser.getRealname());
      user.setAvatar(sysUser.getAvatar());
      user.setPhone(sysUser.getPhone());
      user.setEmail(sysUser.getEmail());
      user.setUpdateTime(sysUser.getUpdateTime());
      user.setCreateTime(sysUser.getCreateTime());
      //      user.setIsInquiry(sysUser.getIsInquiry());
      user.setSex(sysUser.getSex());
      users.add(user);
    }
    pageList2.setRecords(users);
    return pageList2;
  }

  /**
   * 增加序号
   *
   * @param productList 结果集合
   * @param pageNum 页号
   * @param pageSize 页长
   */
  public void addSeqNumber(List<User> productList, int pageNum, int pageSize) {
    if (CollectionUtils.isEmpty(productList)) {
      return;
    }
    int index = (pageNum - 1) * pageSize + 1;
    for (User user : productList) {
      user.setSeqNumber(index++);
    }
  }
}
