package com.ruoyi.project.business.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ruoyi.common.enums.DelFlag;
import com.ruoyi.common.enums.FileBuzType;
import com.ruoyi.common.enums.SerialNumberPrefix;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.importExcel.excel.helper.BasicTableInfoHelper;
import com.ruoyi.common.importExcel.excel.tempInfo.AccountInfoHelper;
import com.ruoyi.common.importExcel.utils.ExcelUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LocalUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SpecialCharacterEscaper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.business.domain.vo.account.AgentAddAccount;
import com.ruoyi.project.business.domain.vo.account.AgentAddProject;
import com.ruoyi.project.business.domain.vo.account.CancelMergeReq;
import com.ruoyi.project.business.domain.TbArea;
import com.ruoyi.project.business.domain.TbCountry;
import com.ruoyi.project.business.domain.TbCountryArea;
import com.ruoyi.project.business.domain.TbFile;
import com.ruoyi.project.business.domain.TcAccount;
import com.ruoyi.project.business.domain.TcAccountContact;
import com.ruoyi.project.business.domain.TcAccountContactHistory;
import com.ruoyi.project.business.domain.TcAccountForRelated;
import com.ruoyi.project.business.domain.TcAccountHistory;
import com.ruoyi.project.business.domain.TcAccountRelation;
import com.ruoyi.project.business.domain.vo.account.CancelMergeReq;
import com.ruoyi.project.business.domain.vo.account.GetAccountByAgentDto;
import com.ruoyi.project.business.domain.vo.board.BarChartVo;
import com.ruoyi.project.business.domain.vo.lead.ConvertReq;
import com.ruoyi.project.business.domain.vo.lead.LeadRes;
import com.ruoyi.project.business.domain.vo.selectParam.AccountParam;
import com.ruoyi.project.business.enums.MessageTypeEnum;
import com.ruoyi.project.business.service.ITcAccountRelationService;
import com.ruoyi.project.business.mapper.TbAreaMapper;
import com.ruoyi.project.business.mapper.TbCountryAreaMapper;
import com.ruoyi.project.business.mapper.TbCountryMapper;
import com.ruoyi.project.business.mapper.TbFileMapper;
import com.ruoyi.project.business.mapper.TcAccountContactMapper;
import com.ruoyi.project.business.mapper.TcAccountHistoryMapper;
import com.ruoyi.project.business.mapper.TcAccountMapper;
import com.ruoyi.project.business.mapper.TcAccountRelationMapper;
import com.ruoyi.project.business.mapper.TcFollowMapper;
import com.ruoyi.project.business.mapper.TcLeadMapper;
import com.ruoyi.project.business.mapper.TcProjectMapper;
import com.ruoyi.project.business.service.ITcAccountContactHistoryService;
import com.ruoyi.project.business.service.ITcAccountService;
import com.ruoyi.project.business.service.ITcLeadService;
import com.ruoyi.project.common.domain.Message;
import com.ruoyi.project.common.service.ISseEmitterService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-10
 */
@Slf4j
@Service
public class TcAccountServiceImpl extends ServiceImpl<TcAccountMapper, TcAccount> implements ITcAccountService {

    @Resource
    private TcAccountMapper tcAccountMapper;

    @Resource
    private RedisCache redisCache;

    @Resource
    private TbFileMapper tbFileMapper;

    @Resource
    private TcAccountRelationMapper tcAccountRelationMapper;
    @Resource
    private ITcAccountRelationService tcAccountRelationService;

    @Resource
    private TcAccountHistoryMapper tcAccountHistoryMapper;

    @Resource
    private TcAccountContactMapper tcAccountContactMapper;

    @Resource
    private TcLeadMapper tcLeadMapper;

    @Resource
    private ITcLeadService tcLeadService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private TcProjectMapper tcProjectMapper;

    @Resource
    private TcFollowMapper tcFollowMapper;

    @Resource
    private ISseEmitterService sseEmitterService;

    @Resource
    private ITcAccountContactHistoryService tcAccountContactHistoryService;

    @Resource
    private TbAreaMapper tbAreaMapper;

    @Resource
    private TbCountryMapper tbCountryMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private TbCountryAreaMapper tbCountryAreaMapper;

    private static final String EMAIL_PATTERN = "^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$";

    /**
     * 查询客户管理
     * 
     * @param accountId 客户管理主键
     * @return 客户管理
     */
    @Override
    public TcAccount selectTcAccountByAccountId(Long accountId)
    {

        // 校验数据是否已被删除
        TcAccount tcAccount = tcAccountMapper.selectTcAccountByAccountId(accountId);
        if (DelFlag.YES.getCode().equals(tcAccount.getDelFlag())) {
            throw new ServiceException(MessageUtils.message("business.data.deleted"));
        }

        AccountParam param  = new AccountParam();
        param.setPermissionChar(SecurityUtils.getPermissionCharIns());
        // 代理商销售经理的场合
        if (SecurityUtils.hasRole("agent_sales")) {
            param.setLoginUserId(SecurityUtils.getUserId());
            param.setPermission(SecurityUtils.getPermissionCharIns());
        }
        List<TcAccount> list = tcAccountMapper.selectTcAccountList(param);
        if(ObjectUtils.isEmpty(list)){
            throw new ServiceException(MessageUtils.message("common.data.noPermession"));
        }

        // 查询附件信息
        TbFile tbFile = new TbFile();
        tbFile.setBusinessId(accountId);
        List<TbFile> fileList = tbFileMapper.selectTbFileList(tbFile);
        tcAccount.setFileList(fileList);
        // 查询合并客户集合
        List<TcAccountRelation> relationList = tcAccountRelationMapper.selectAllTcAccountRelation();
        if (!relationList.isEmpty()) {
            List<TcAccount> accounts = new ArrayList<>();
            relationList.forEach(relation -> {
                if (accountId.equals(relation.getAccountId())) {
                    TcAccount account = new TcAccount();
                    account.setAccountId(relation.getOtherAccountId());
                    account.setAgentName(relation.getAgentName());
                    accounts.add(account);
                }
            });
            tcAccount.setAccounts(accounts);
        }
        // 查询客户关联线索
        List<LeadRes> tcLeadList = tcLeadMapper.selectLeadListByAccountId(accountId);
        tcAccount.setLeadList(tcLeadList);
        tcAccount.setLeadIds(tcLeadList.stream().map(LeadRes::getLeadId).collect(Collectors.toList()));
        LocalUtils.setLocalAreaAndCountryName(tcAccount, TcAccount::getAreaId, TcAccount::getCountryId, TcAccount::setAreaName, TcAccount::setCountryName);
        return tcAccount;
    }

    /**
     * 查询客户管理列表
     * 
     * @param tcAccount 客户管理
     * @return 客户管理
     */
    @Override
    public List<TcAccount> selectTcAccountList(AccountParam tcAccount)
    {
        if (StringUtils.isNotEmpty(tcAccount.getAccountNo())) {
            tcAccount.setAccountNo(tcAccount.getAccountNo().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tcAccount.getAccountName())) {
            tcAccount.setAccountName(tcAccount.getAccountName().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tcAccount.getOwnerName())) {
            tcAccount.setOwnerName(tcAccount.getOwnerName().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tcAccount.getCity())) {
            tcAccount.setCity(tcAccount.getCity().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
//        tcAccount.setPermissionChar(SecurityUtils.getPermissionCharSea());
        tcAccount.setPermissionChar(SecurityUtils.getPermissionCharIns());
        // 代理商销售经理的场合
        if (SecurityUtils.hasRole("agent_sales")) {
            tcAccount.setLoginUserId(SecurityUtils.getUserId());
            tcAccount.setPermission(SecurityUtils.getPermissionCharIns());
        }
        return tcAccountMapper.selectTcAccountList(tcAccount);
    }

    @Override
    public List<AgentAddAccount> selectAgentAddAccount(AccountParam tcAccount)
    {
//        tcAccount.setPermissionChar(SecurityUtils.getPermissionCharIns());
//        // 代理商销售经理的场合
//        if (SecurityUtils.hasRole("agent_sales")) {
//            tcAccount.setLoginUserId(SecurityUtils.getUserId());
//            tcAccount.setPermission(SecurityUtils.getPermissionCharIns());
//        }
        return tcAccountMapper.selectAgentAddAccount(tcAccount);
    }

    @Override
    public List<AgentAddProject> selectAgentAddProject(AccountParam tcAccount)
    {

//        tcAccount.setPermissionChar(SecurityUtils.getPermissionCharIns());
//        // 代理商销售经理的场合
//        if (SecurityUtils.hasRole("agent_sales")) {
//            tcAccount.setLoginUserId(SecurityUtils.getUserId());
//            tcAccount.setPermission(SecurityUtils.getPermissionCharIns());
//        }
        return tcAccountMapper.selectAgentAddProject(tcAccount);
    }

    @Override
    public List<TcAccount> selectTcAccountListExport(AccountParam tcAccount)
    {
        if (StringUtils.isNotEmpty(tcAccount.getAccountNo())) {
            tcAccount.setAccountNo(tcAccount.getAccountNo().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tcAccount.getAccountName())) {
            tcAccount.setAccountName(tcAccount.getAccountName().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
        if (StringUtils.isNotEmpty(tcAccount.getOwnerName())) {
            tcAccount.setOwnerName(tcAccount.getOwnerName().replaceAll("%", "/%").replaceAll("_", "/_"));
        }
//        tcAccount.setPermissionChar(SecurityUtils.getPermissionCharSea());
        tcAccount.setPermissionChar(SecurityUtils.getPermissionCharIns());
        // 代理商销售经理的场合
        if (SecurityUtils.hasRole("agent_sales")) {
            tcAccount.setLoginUserId(SecurityUtils.getUserId());
            tcAccount.setPermission(SecurityUtils.getPermissionCharIns());
        }
        List<TcAccount> accounts = tcAccountMapper.selectTcAccountListExport(tcAccount);
        LocalUtils.setLocalAreaAndCountryNameBatch(accounts, TcAccount::getAreaId, TcAccount::getCountryId, TcAccount::setAreaName, TcAccount::setCountryName);
        return accounts;
    }

    /**
     * 查询关联客户
     *
     * @return 客户管理
     */
    @Override
    public List<TcAccountForRelated> selectAccountListByLoginId()
    {
        Long loginId = SecurityUtils.getUserId();
        return tcAccountMapper.selectAccountListByLoginId(loginId);
    }

    /**
     * 查询关联客户
     *
     * @return 客户管理
     */
    @Override
    public List<TcAccountForRelated> selectAccountListByAccountId(TcAccount tcAccount){

        return tcAccountMapper.selectAccountListByAccountId(tcAccount);
    }
    /**
     * 查询关联客户
     *
     * @return 客户管理
     */
    @Override
    public List<TcAccountForRelated> selectAccountListByQuery(TcAccount tcAccount) {
        Long loginId = SecurityUtils.getUserId();
        tcAccount.setLoginId(loginId);
        SpecialCharacterEscaper.escapeSpecialCharacters(tcAccount, TcAccount::getQuery);
        return tcAccountMapper.selectAccountListByQuery(tcAccount);
    }

    /**
     * 根据区域id获取权限字段串
     */
    @Override
    public String getPermissionChar(Long areaId) {
        // 获取权限字段串
        String permissionChar = SecurityUtils.getPermissionCharIns();
        // 获取登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser.getDeptId() == 0L && loginUser.getAreaIdList().size() > 1) {
            String permissionCharArea = tbAreaMapper.selectTbAreaByAreaId(areaId).getPermissionChar();
            for (Long userAreaId : loginUser.getAreaIdList()) {
                if (Objects.equals(areaId, userAreaId)) {
                    return areaId.toString();
                } else {
                    String[] split = permissionCharArea.substring(1, permissionCharArea.length() - 1).split(",");
                    List<Long> areaIds = Arrays.stream(split).map(Long::parseLong).collect(Collectors.toList());
                    if (areaIds.contains(areaId)) {
                        return areaId.toString();
                    }
                }
            }
        }
        return permissionChar;
    }

    /**
     * 新增客户管理
     * 
     * @param tcAccount 客户管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTcAccount(TcAccount tcAccount)
    {
        // 获取权限字段串
        // String permissionChar = getPermissionChar(tcAccount.getAreaId());
        String permissionChar = 0 == tcAccount.getOwnerAgent() ? tcAccount.getAreaId().toString() : tcAccount.getOwnerAgent().toString();
        tcAccount.setPermissionChar(permissionChar);
        // 客户名称同用户权限下去重
        int count = tcAccountMapper.selectCountByAccountName(tcAccount.getAccountName(), permissionChar, null);
        if (count > 0) {
            throw new ServiceException(MessageUtils.message("account.name.repeat"));
        }
        // 业务编号采番规则，使用RedisCache.generateSerialNumber(SerialNumberPrefix.业务)方法
        String accountNo = redisCache.generateSerialNumber(SerialNumberPrefix.ACC.getPrefix());
        tcAccount.setAccountNo(accountNo);
        // 查询客户所有人的所有代理商
        if (tcAccount.getOwnerAgent() == null) {
            tcAccount.setOwnerAgent(sysUserMapper.selectDeptIdById(tcAccount.getOwner()));
        }
        tcAccount.setCreateBy(SecurityUtils.getUserId().toString());
        tcAccount.setCreateTime(DateUtils.getNowDate());
        tcAccount.setUpdateBy(SecurityUtils.getUserId().toString());
        tcAccount.setUpdateTime(DateUtils.getNowDate());
        int result = tcAccountMapper.insertTcAccount(tcAccount);
        // 保存附件
        if (StringUtils.isNotEmpty(tcAccount.getFile())) {
            String[] fileArray = tcAccount.getFile().split(",");
            List<TbFile> tbFileList = new ArrayList<>();
            for (String filePath : fileArray) {
                TbFile tbFile = new TbFile();
                tbFile.setBusinessId(tcAccount.getAccountId());
                tbFile.setBusinessType(FileBuzType.CUSTOMER.getType());
                tbFile.setFilePath(filePath);
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                tbFile.setRealFileName(fileName.substring(0, fileName.lastIndexOf("_")));
                tbFile.setServerFileName(fileName);
                tbFile.setCreateBy(SecurityUtils.getUserId().toString());
                tbFile.setCreateTime(DateUtils.getNowDate());
                tbFileList.add(tbFile);
            }
            tbFileMapper.batchInsertTbFile(tbFileList);
        }
        // 新增联系人信息
        if (tcAccount.getContactList() != null && !tcAccount.getContactList().isEmpty()) {
            for (TcAccountContact tcAccountContact : tcAccount.getContactList()) {
                tcAccountContact.setAccountId(tcAccount.getAccountId());
                tcAccountContact.setCreateTime(DateUtils.getNowDate());
                tcAccountContactMapper.insertTcAccountContact(tcAccountContact);
            }
        }
        // 线索信息绑定客户
        if (tcAccount.getLeadIds() != null && !tcAccount.getLeadIds().isEmpty()) {
//            tcLeadMapper.updateAccountIdByLeadIds(tcAccount.getLeadIds(), tcAccount.getAccountId());
//             for (Long leadId : tcAccount.getLeadIds()) {
//                 ConvertReq convertReq = new ConvertReq();
//                 convertReq.setLeadId(leadId);
//                 convertReq.setRelativeAccount(tcAccount.getAccountId());
//                 tcLeadService.convertCustomer(convertReq);
//             }
            ConvertReq convertReq = new ConvertReq();
            convertReq.setLeadIds(tcAccount.getLeadIds());
            convertReq.setRelativeAccount(tcAccount.getAccountId());
            tcLeadService.convertCustomer(convertReq);
        }

        // ThreadUtil.execute(() -> saveHis(tcAccount, tcAccount.getContactList()));

        saveHis(tcAccount, tcAccount.getContactList());
        
        return result;
    }

    /**
     * 保存客户履历
     * 
     * @param tcAccount 客户信息
     * @param contactList   客户联系人
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveHis(TcAccount tcAccount, List<TcAccountContact> contactList) {
        try {
            // 获取客户履历最高版本号
            Long version = tcAccountHistoryMapper.selectMaxVersion(tcAccount.getAccountId());
            Long newVersion = version == null ? 1L : version + 1L;
            // 新增客户履历
            TcAccountHistory accountHis = TcAccountHistory.from(tcAccount, newVersion);
            tcAccountHistoryMapper.insert(accountHis);

            if (CollectionUtils.isNotEmpty(contactList)) {
                List<TcAccountContactHistory> collect = contactList.stream().map(item -> TcAccountContactHistory.from(item, newVersion)).collect(Collectors.toList());
                tcAccountContactHistoryService.saveBatch(collect);
            }
            return true;
        } catch (Exception e) {
            log.error("新增客户履历失败", e);
            return false;
        }
    }

    /**
     * 修改客户管理
     * 
     * @param tcAccount 客户管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTcAccount(TcAccount tcAccount)
    {
        // 获取权限字段串
        // String permissionChar = getPermissionChar(tcAccount.getAreaId());
        String permissionChar = 0 == tcAccount.getOwnerAgent() ? tcAccount.getAreaId().toString() : tcAccount.getOwnerAgent().toString();
        tcAccount.setPermissionChar(permissionChar);
        // 客户名称同用户权限下去重
        int count = tcAccountMapper.selectCountByAccountName(tcAccount.getAccountName(), permissionChar, tcAccount.getAccountId());
        if (count > 0) {
            throw new ServiceException(MessageUtils.message("account.name.repeat"));
        }
        // 获取当前数据库中客户数据
        TcAccount oldTcAccount = tcAccountMapper.selectTcAccountByAccountId(tcAccount.getAccountId());
        // 判断是否需要推送消息
        boolean flag = false;
        List<Long> oldIds = new ArrayList<>();
        List<Long> newIds = new ArrayList<>();
        if (!Objects.equals(oldTcAccount.getOwner(), tcAccount.getOwner())) {
            flag = true;
            oldIds.add(oldTcAccount.getOwner());
            newIds.add(tcAccount.getOwner());
        }
        // 获取当前数据库的附件列表
        List<TbFile> oldFileList = tbFileMapper.selectTbFileListByBuzIdAndBuzType(tcAccount.getAccountId(), FileBuzType.CUSTOMER.getType());
        String oldFile = oldFileList.stream().map(TbFile::getFilePath).collect(Collectors.joining(","));
        // 先获取当前数据库的客户联系人列表数据
        List<TcAccountContact> oldContactList = tcAccountContactMapper.selectContactlistByAccountId(tcAccount.getAccountId());
        // 获取客户履历最高版本号
        Long version = tcAccountHistoryMapper.selectMaxVersion(tcAccount.getAccountId());
        Long newVersion = version == null ? 1L : version + 1L;
        // 客户主体数据是否发生了变化
        boolean accountChange = isAccountNotEqual(oldTcAccount, tcAccount);
        // 客户联系人数据是否发生了变化
        boolean contactChange = isContactListNotEqual(oldContactList, tcAccount.getContactList());
        // 客户附件数据是否发生了变化
        boolean fileChange = !Objects.equals(tcAccount.getFile(), oldFile);
        // 客户整体数据是否发生了变化
        boolean isEdit = accountChange || contactChange || fileChange;
        // 发生变化全部增加履历
        if (isEdit) {
            // 新增客户履历

            TcAccountHistory tcAccountHistory = TcAccountHistory.from(tcAccount, newVersion);
            tcAccountHistory.setCreateBy(SecurityUtils.getUserId().toString());
            tcAccountHistoryMapper.insert(tcAccountHistory);
            
            // this.saveHis(oldTcAccount, oldContactList);

            tbFileMapper.updateTbFileByAccountId(tcAccount.getAccountId(), tcAccountHistory.getId(), FileBuzType.ACCOUNT_HISTORY.getType());
        }
        // 查询客户所有人的所有代理商
        if (tcAccount.getOwnerAgent() == null) {
            tcAccount.setOwnerAgent(sysUserMapper.selectDeptIdById(tcAccount.getOwner()));
        }
        tcAccount.setUpdateBy(SecurityUtils.getUserId().toString());
        tcAccount.setUpdateTime(DateUtils.getNowDate());
        int result = tcAccountMapper.updateTcAccount(tcAccount);
        if (contactChange) {
            // 修改客户联系人
            tcAccountContactMapper.deleteTcAccountContactByAccountId(tcAccount.getAccountId());
            List<TcAccountContact> contactList = tcAccount.getContactList();
            
            if (CollectionUtils.isNotEmpty(contactList)){
                // TODO 改成批量接口 tcAccountContactService.saveBatch(contactList); 需要测试 
                for (TcAccountContact tcAccountContact : contactList) {
                    tcAccountContactMapper.insertTcAccountContact(tcAccountContact);
                }
                List<TcAccountContactHistory> collect = contactList.stream().map(item -> TcAccountContactHistory.from(item, newVersion)).collect(Collectors.toList());
                tcAccountContactHistoryService.saveBatch(collect);
            }
        }
        // 保存附件
        if (StringUtils.isNotEmpty(tcAccount.getFile())) {
            String[] fileArray = tcAccount.getFile().split(",");
            List<TbFile> tbFileList = new ArrayList<>();
            for (String filePath : fileArray) {
                TbFile tbFile = new TbFile();
                tbFile.setBusinessId(tcAccount.getAccountId());
                tbFile.setBusinessType(FileBuzType.CUSTOMER.getType());
                tbFile.setFilePath(filePath);
                String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                tbFile.setRealFileName(fileName.substring(0, fileName.lastIndexOf("_")));
                tbFile.setServerFileName(fileName);
                tbFile.setCreateBy(SecurityUtils.getUserId().toString());
                tbFile.setCreateTime(DateUtils.getNowDate());
                tbFileList.add(tbFile);
            }
            tbFileMapper.batchInsertTbFile(tbFileList);
        }
        // 修改线索信息
        tcLeadMapper.resetAccountId(tcAccount.getAccountId());
        if (tcAccount.getLeadIds() != null && !tcAccount.getLeadIds().isEmpty()) {
            ConvertReq convertReq = new ConvertReq();
            convertReq.setLeadIds(tcAccount.getLeadIds());
            convertReq.setRelativeAccount(tcAccount.getAccountId());
            tcLeadService.convertCustomer(convertReq);
        }
        // 发送消息
        if (flag) {
            Object[] args = new String[1];
            args[0] = tcAccount.getAccountName();
            MessageSource oldSource = SpringUtils.getBean(MessageSource.class);
            String messageContentOld = oldSource.getMessage("account.owner.message.old", args, new Locale("zh", "CN"));
            String messageContentUSOld = oldSource.getMessage("account.owner.message.old", args, new Locale("en", "US"));
            String messageContentRUOld = oldSource.getMessage("account.owner.message.old", args, new Locale("ru", "RU"));
            String messageContentESOld = oldSource.getMessage("account.owner.message.old", args, new Locale("es", "ES"));
            Message messageForOld = new Message();
            messageForOld.setMessageType(MessageTypeEnum.ACCOUNT.getValue());
            messageForOld.setMessageContent(messageContentOld);
            messageForOld.setMessageContentUS(messageContentUSOld);
            messageForOld.setMessageContentRU(messageContentRUOld);
            messageForOld.setMessageContentES(messageContentESOld);

            MessageSource newSource = SpringUtils.getBean(MessageSource.class);
            String messageContentNew = newSource.getMessage("account.owner.message.new", args, new Locale("zh", "CN"));
            String messageContentUSNew = newSource.getMessage("account.owner.message.new", args, new Locale("en", "US"));
            String messageContentRUNew = newSource.getMessage("account.owner.message.new", args, new Locale("ru", "RU"));
            String messageContentESNew = newSource.getMessage("account.owner.message.new", args, new Locale("es", "ES"));
            Message messageForNew = new Message();
            messageForNew.setMessageType(MessageTypeEnum.ACCOUNT.getValue());
            messageForNew.setMessageContent(messageContentNew);
            messageForNew.setMessageContentUS(messageContentUSNew);
            messageForNew.setMessageContentRU(messageContentRUNew);
            messageForNew.setMessageContentES(messageContentESNew);
            sseEmitterService.sendSaveMessage(newIds, messageForNew);
            sseEmitterService.sendSaveMessage(oldIds, messageForOld);
        }
        return result;
    }

    private boolean isContactListNotEqual(List<TcAccountContact> oldContactList, List<TcAccountContact> contactList) {
        boolean flag = false; // 判断客户联系人数据是否变化
        if (contactList.size() == oldContactList.size()) {
            for (TcAccountContact oldContact : oldContactList) {
                TcAccountContact contact = contactList.stream().filter(c -> Objects.equals(c.getContactId(), oldContact.getContactId())).findFirst().orElse(null);
                if (contact == null) {
                    flag = true;
                    break;
                } else {
                    if (isContactNotEqual(oldContact, contact)) {
                        flag = true;
                        break;
                    }
                }
            }
        } else {
            flag = true;
        }
        return flag;
    }

    private boolean isContactNotEqual(TcAccountContact oldContact, TcAccountContact contact) {
        if (!Objects.equals(oldContact.getContactName(), contact.getContactName())) {
            return true;
        }
        if (!Objects.equals(oldContact.getPhone(), contact.getPhone())) {
            return true;
        }
        if (!Objects.equals(oldContact.getEmail(), contact.getEmail())) {
            return true;
        }
        if (!Objects.equals(oldContact.getAddress(), contact.getAddress())) {
            return true;
        }
        if (!Objects.equals(oldContact.getJobTitle(), contact.getJobTitle())) {
            return true;
        }
        if (!Objects.equals(oldContact.getBirthday(), contact.getBirthday())) {
            return true;
        }
        if (!Objects.equals(oldContact.getHoroscope(), contact.getHoroscope())) {
            return true;
        }
        if (!Objects.equals(oldContact.getMaritalStatus(), contact.getMaritalStatus())) {
            return true;
        }
        if (!Objects.equals(oldContact.getHobbies(), contact.getHobbies())) {
            return true;
        }
        return false;
    }

    private boolean isAccountNotEqual(TcAccount oldTcAccount, TcAccount tcAccount) {
        if (!Objects.equals(oldTcAccount.getAreaId(), tcAccount.getAreaId())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getCountryId(), tcAccount.getCountryId())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getCity(), tcAccount.getCity())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getType(), tcAccount.getType())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getLevel(), tcAccount.getLevel())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getAccountName(), tcAccount.getAccountName())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getCompanyType(), tcAccount.getCompanyType())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getAddress(), tcAccount.getAddress())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getCompanyWebsite(), tcAccount.getCompanyWebsite())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getBackground(), tcAccount.getBackground())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getAccountGroup(), tcAccount.getAccountGroup())) {
            return true;
        }
        // if (!Objects.equals(oldTcAccount.getStatus(), tcAccount.getStatus())) {
        //     return true;
        // }
        if (!Objects.equals(oldTcAccount.getIntentionalProduct(), tcAccount.getIntentionalProduct())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getBeginYear() == null ? null : oldTcAccount.getBeginYear().getYear(), tcAccount.getBeginYear() == null ? null : tcAccount.getBeginYear().getYear())) {
            return true;
        }
        if (!Objects.equals(oldTcAccount.getOwner(), tcAccount.getOwner())) {
            return true;
        }
        // 代理商
        if (!Objects.equals(oldTcAccount.getOwnerAgent(), tcAccount.getOwnerAgent())) {
            return true;
        }
        // 项目类型
        if (!Objects.equals(oldTcAccount.getSegment(), tcAccount.getSegment())) {
            return true;
        }
        return false;
    }

    /**
     * 批量删除客户管理
     * 
     * @param accountIds 需要删除的客户管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTcAccountByAccountIds(Long[] accountIds)
    {
        // 1.关联了项目 2.有跟进记录 不能删除
        for (Long accountId : accountIds) {
            int projectCount = tcProjectMapper.selectCountByAccountId(accountId);
            if (projectCount > 0) {
                throw new ServiceException(MessageUtils.message("account.delete.project"));
            }
            int followCount = tcFollowMapper.selectCountByAccountId(accountId);
            if (followCount > 0) {
                throw new ServiceException(MessageUtils.message("account.delete.follow"));
            }
        }
        // 批量删除附件
        tbFileMapper.deleteTbFileByBusinessIdsAndType(accountIds, FileBuzType.CUSTOMER.getType());
        // 批量删除联系人
        tcAccountContactMapper.deleteTcAccountContactByAccountIds(accountIds);
        // 批量重置线索
        tcLeadMapper.resetAccountIds(accountIds);
        return tcAccountMapper.deleteTcAccountByAccountIds(accountIds);
    }

    /**
     * 删除客户管理信息
     * 
     * @param accountId 客户管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTcAccountByAccountId(Long accountId)
    {
        // 删除附件
        tbFileMapper.deleteTbFileByBusinessIdAndType(accountId, FileBuzType.CUSTOMER.getType());
        return tcAccountMapper.deleteTcAccountByAccountId(accountId);
    }

    /**
     * 客户合并
     *
     * @param tcAccountList 待合并客户
     * @return 结果
     */
    @Override
    @Transactional
    public int merge(List<TcAccount> tcAccountList) {
        // 查询合并客户集合
        List<TcAccountRelation> relationList = tcAccountRelationMapper.selectAllTcAccountRelation();
        List<TcAccountRelation> listForAdd = new ArrayList<>();
        Date nowDate = DateUtils.getNowDate();
        String creatBy = SecurityUtils.getUserId().toString();
        tcAccountList.forEach(tcAccount -> tcAccountList.forEach(item -> {
            if (!tcAccount.getAccountId().equals(item.getAccountId())) {
                TcAccountRelation tcAccountRelation = new TcAccountRelation();
                tcAccountRelation.setAccountId(tcAccount.getAccountId());
                tcAccountRelation.setOtherAccountId(item.getAccountId());
                tcAccountRelation.setCreateBy(creatBy);
                tcAccountRelation.setCreateTime(nowDate);
                tcAccountRelation.setUpdateTime(nowDate);
                listForAdd.add(tcAccountRelation);
            }
        }));
        // 校验
        listForAdd.forEach(tcAccountRelation -> {
            if (relationList.stream().anyMatch(relation -> relation.getAccountId().equals(tcAccountRelation.getAccountId()) && relation.getOtherAccountId().equals(tcAccountRelation.getOtherAccountId()))) {
                throw new ServiceException(MessageUtils.message("account.merged"));
            }
        });
        return tcAccountRelationMapper.batchInsertTcAccountRelation(listForAdd);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelMerge(CancelMergeReq req) {
        List<TcAccountRelation> curList = tcAccountRelationService.list(Wrappers.lambdaQuery(TcAccountRelation.class).eq(TcAccountRelation::getAccountId, req.getAccountId()));
        TcAccount curAccount = tcAccountMapper.selectTcAccountByAccountId(req.getAccountId());

        List<TcAccount> collect = curList.stream().map(relation -> {
            TcAccount account = new TcAccount();
            account.setAccountId(relation.getOtherAccountId());
            account.setAgentName(relation.getAgentName());
            return account;
        }).collect(Collectors.toList());
        collect.add(curAccount);
        
        List<TcAccountRelation> query = new ArrayList<>();
        
        collect.forEach(tcAccount -> collect.forEach(item -> {
            if (!tcAccount.getAccountId().equals(item.getAccountId())) {
                TcAccountRelation tcAccountRelation = new TcAccountRelation();
                tcAccountRelation.setAccountId(tcAccount.getAccountId());
                tcAccountRelation.setOtherAccountId(item.getAccountId());
                query.add(tcAccountRelation);
            }
        }));

        List<TcAccountRelation> tcAccountRelations = tcAccountRelationMapper.selectTcAccountRelationListByList(query);
        List<Long> ids = tcAccountRelations.stream().map(TcAccountRelation::getId).collect(Collectors.toList());

        tcAccountRelationService.removeBatchByIds(ids);
        List<TcAccount> tcAccountList = req.getTcAccountList();

        if (CollectionUtils.isNotEmpty(tcAccountList)) {
            return SpringUtils.getAopProxy(this).merge(tcAccountList);
        }

        return 1;

    }

    /**
     * 客户导入数据校验
     */
    @Override
    public ExcelUtils.UploadResult<AccountInfoHelper> checkAccountInfo(BasicTableInfoHelper tableInfo, List<AccountInfoHelper> list) {
        if (list.size() > 1) {
            for (int i = 1; i < list.size(); i++) {
                if (Objects.equals(list.get(0).getAccountName(), list.get(i).getAccountName())) {
                    throw new ServiceException(MessageUtils.message("account.name.repeat"));
                }
            }
        }
        List<TcAccount> tcAccounts = tcAccountMapper.selectByPermissionChar(SecurityUtils.getPermissionCharIns());
        // 区域列表
        List<TbArea> tbAreas = tbAreaMapper.getAllAreaList();
        // 国家列表
        List<TbCountry> tbCountries = tbCountryMapper.getAllNationList();
        List<TbCountryArea> tbCountryAreas = tbCountryAreaMapper.selectTbCountryAreaList(new TbCountryArea());
        // 负责人列表
        List<SysUser> sysUsers = sysUserService.getOwnerList(false);
        return ExcelUtils.checkData(list, item -> {
            List<String> businessErrors = Lists.newArrayList();
            // 校验客户名称不能重复
            if (tcAccounts.stream().anyMatch(tcAccount -> Objects.equals(tcAccount.getAccountName(), item.getAccountName()))) {
                businessErrors.add(MessageUtils.message("account.name.repeat"));
            }
            // 校验区域
            TbArea tbArea = tbAreas.stream().filter(area -> Objects.equals(area.getAreaName(), item.getAreaId())).findFirst().orElse(null);
            if (tbArea == null) {
                businessErrors.add(MessageUtils.message("area.name.invalid"));
            } else {
                item.setAreaId(tbArea.getAreaId().toString());
                // 校验国家
                TbCountry tbCountry = tbCountries.stream().filter(country -> Objects.equals(country.getCountryName(), item.getCountryId())).findFirst().orElse(null);
                if (tbCountry == null) {
                    businessErrors.add(MessageUtils.message("country.name.invalid"));
                } else {
                    // 校验该国家是否在该区域下
                    if (tbCountryAreas.stream().noneMatch(countryArea -> countryArea.getCountryId().equals(tbCountry.getCountryId()) && countryArea.getAreaId().equals(tbArea.getAreaId().toString()))) {
                        businessErrors.add(MessageUtils.message("country.name.invalid"));
                    }
                    item.setCountryId(tbCountry.getCountryId().toString());
                }
            }
            // 校验负责人
            SysUser sysUser = sysUsers.stream().filter(user -> Objects.equals(user.getNickName(), item.getOwner())).findFirst().orElse(null);
            if (sysUser == null) {
                businessErrors.add(MessageUtils.message("owner.name.invalid"));
            } else {
                item.setOwner(sysUser.getUserId().toString());
            }
//            // 校验邮箱格式
//            if (StringUtils.isNotEmpty(item.getEmail())) {
//                if (!Pattern.compile(EMAIL_PATTERN).matcher(item.getEmail()).matches()) {
//                    businessErrors.add(MessageUtils.message("user.email.not.valid"));
//                }
//            }
            return businessErrors;
        });
    }

    /**
     * 批量插入客户导入数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> insertTcAccountExcel(BasicTableInfoHelper basicTableInfoHelper, List<AccountInfoHelper> list) {
        List<String> errorMessages = new ArrayList<>();
        List<SysDictData> typeList = sysDictDataMapper.selectDictDataByType("account_type");
        List<SysDictData> statusList = sysDictDataMapper.selectDictDataByType("account_status");
        List<SysDictData> levelList = sysDictDataMapper.selectDictDataByType("account_level");
        List<SysDictData> companyTypeList = sysDictDataMapper.selectDictDataByType("company_type");
        List<SysDictData> intentionalProductList = sysDictDataMapper.selectDictDataByType("intentional_product");
        List<SysDictData> projectTypeList = sysDictDataMapper.selectDictDataByType("project_type");
        // 获取客户实体
        // List<TcAccount> tcAccountList = new ArrayList<>();
        Date nowDate = DateUtils.getNowDate();
        for (AccountInfoHelper accountInfoHelper : list) {
            TcAccount tcAccount = new TcAccount();
            String accountNo = redisCache.generateSerialNumber(SerialNumberPrefix.ACC.getPrefix());
            tcAccount.setAccountNo(accountNo);
            tcAccount.setAccountName(accountInfoHelper.getAccountName());
            // 处理字典 客户类型
            typeList.stream().filter(item -> Objects.equals(item.getDictLabel(), accountInfoHelper.getType())).findFirst().ifPresent(type -> tcAccount.setType(type.getDictValue()));
            tcAccount.setAreaId(Long.valueOf(accountInfoHelper.getAreaId()));
            tcAccount.setCountryId(Long.valueOf(accountInfoHelper.getCountryId()));
            // 处理首次合作年份
            Date time = DateUtils.CNTimeDate(accountInfoHelper.getBeginYear(), SecurityUtils.getTimeZone());
            tcAccount.setBeginYear(time);
            tcAccount.setAddress(accountInfoHelper.getAddress());
            tcAccount.setAccountGroup(accountInfoHelper.getAccountGroup());
            // 处理字典 跟进状态
            statusList.stream().filter(item -> Objects.equals(item.getDictLabel(), accountInfoHelper.getStatus())).findFirst().ifPresent(status -> tcAccount.setStatus(status.getDictValue()));
            tcAccount.setOwner(Long.valueOf(accountInfoHelper.getOwner()));
            if (tcAccount.getOwnerAgent() == null) {
                tcAccount.setOwnerAgent(sysUserMapper.selectDeptIdById(tcAccount.getOwner()));
            }
            // 处理字典 客户等级
            levelList.stream().filter(item -> Objects.equals(item.getDictLabel(), accountInfoHelper.getLevel())).findFirst().ifPresent(level -> tcAccount.setLevel(level.getDictValue()));
            // 处理字典 公司类型
            companyTypeList.stream().filter(item -> Objects.equals(item.getDictLabel(), accountInfoHelper.getCompanyType())).findFirst().ifPresent(companyType -> tcAccount.setCompanyType(companyType.getDictValue()));
            // 处理字典 产品意向
            intentionalProductList.stream().filter(item -> Objects.equals(item.getDictLabel(), accountInfoHelper.getIntentionalProduct())).findFirst().ifPresent(intentionalProduct -> tcAccount.setIntentionalProduct(intentionalProduct.getDictValue()));
            // 处理字典 项目类型
            projectTypeList.stream().filter(item -> Objects.equals(item.getDictLabel(), accountInfoHelper.getSegment()))
                .findFirst().ifPresent(projectType -> tcAccount.setSegment(projectType.getDictValue()));
            tcAccount.setCompanyWebsite(accountInfoHelper.getCompanyWebsite());
            tcAccount.setBackground(accountInfoHelper.getBackground());
            tcAccount.setRemark(accountInfoHelper.getRemark());
            // tcAccount.setPermissionChar(getPermissionChar(Long.valueOf(accountInfoHelper.getAreaId())));
            tcAccount.setPermissionChar(0 == tcAccount.getOwnerAgent() ? accountInfoHelper.getAreaId() : tcAccount.getOwnerAgent().toString());
            tcAccount.setDelFlag(DelFlag.NO.getCode());
            tcAccount.setCreateBy(SecurityUtils.getUserId().toString());
            tcAccount.setCreateTime(nowDate);
            tcAccount.setUpdateTime(nowDate);
            tcAccount.setCity(accountInfoHelper.getCity());
            // tcAccountList.add(tcAccount);
            int result = tcAccountMapper.insertTcAccount(tcAccount);
            saveHis(tcAccount, tcAccount.getContactList());
        }

        // 批量插入客户
        // int result = tcAccountMapper.batchInsertTcAccount(tcAccountList);
        return errorMessages;
    }

    @Override
    public List<TcAccount> listRemote(String query) {
        Long owner = SecurityUtils.isVp() ? null : SecurityUtils.getUserId();
        return tcAccountMapper.listRemote(query, SecurityUtils.getPermissionCharIns(), owner);
    }

    @Override
    public Integer existCustomerByAgentIds(Long[] agentIds) {
        if (agentIds == null || agentIds.length == 0) {
            return null;
        }
        return tcAccountMapper.existUserByAgentIds(agentIds);
    }

    public BarChartVo getCustomerCountStat(LocalDate startDate, LocalDate endDate, String statMode) {
        LocalDateTime start;
        LocalDateTime end;

        Function<LocalDateTime, LocalDateTime> fun;
        String pattern;
        LocalTime endTime = LocalTime.of(23, 59, 59);

        switch (statMode) {
            case "day":
                start = startDate.atStartOfDay();
                end = LocalDateTime.of(endDate, endTime);
                fun = date -> date.plusDays(1);
                pattern = "yyyy-MM-dd";
                break;
            case "month":
                start = startDate.withDayOfMonth(1).atStartOfDay();
                end = LocalDateTime.of(endDate.withDayOfMonth(endDate.lengthOfMonth()), endTime);
                fun = date -> date.plusMonths(1);
                pattern = "yyyy-MM";
                break;
            case "year":
                start = startDate.withDayOfYear(1).atStartOfDay();
                end = LocalDateTime.of(endDate.withDayOfYear(endDate.lengthOfYear()), endTime);
                fun = date -> date.plusYears(1);
                pattern = "yyyy";
                break;
            default:
                throw new RuntimeException(MessageUtils.message("board.statistical.model.error"));
        }
        // endDate = fun.apply(endDate);


        // 查询数据 // TODO 这里暂时使用 stream 处理了，因为 crm 系统数据量不会太大。如果后续耗时过长使用本方法 javadoc 中的 sql修改
        List<TcAccount> tcAccounts = tcAccountMapper.selectSimpleByCreateTime(start, end, SecurityUtils.getPermissionCharIns());
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Map<String, Long> collect = tcAccounts.stream()
                .filter(lead -> lead.getCreateTime() != null)
                .collect(Collectors.groupingBy(
                        lead -> sdf.format(lead.getCreateTime()),
                        Collectors.counting()
                ));
        // 使用有序map
        collect = new TreeMap<>(collect);

        // 补全数据; 按照年月日处理
        while (start.isBefore(end)) {
            String key = sdf.format(DateUtil.date(start));
            collect.putIfAbsent(key, 0L);
            start = fun.apply(start);
        }

        return new BarChartVo(collect.keySet(), collect.values());

    }
    
    //@Override
    //public BarChartVo getCustomerCountStat() {
    //    TcAccount account = new TcAccount();
    //
    //    // start
    //    Date start = DateUtils.CNTimeDate(DateUtils.addMonths(new Date(), -6), SecurityUtils.getTimeZone());
    //    // end
    //    Date end = new Date();
    //    
    //    account.setDateRange(Arrays.asList(start, end));
    //    account.setPermissionChar(SecurityUtils.getPermissionCharIns());
    //
    //    // 候选人们
    //    List<TcAccount> candidates = tcAccountMapper.selectSimpleByCreateTime(account);
    //    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
    //    Map<String, Long> collect = candidates.stream().filter(candidate -> candidate.getCreateTime() != null)
    //            .collect(Collectors.groupingBy(
    //                    candidate -> sdf.format(candidate.getCreateTime()),
    //                    Collectors.counting()
    //            ));
    //    
    //    collect = new TreeMap<>(collect);
    //    
    //    // 补全数据
    //    while (start.before(end)) {
    //        String key = sdf.format(start);
    //        collect.putIfAbsent(key, 0L);
    //        start = DateUtils.addMonths(start, 1);
    //    }
    //
    //    return new BarChartVo(collect.keySet(), collect.values());
    //}

    @Override
    public List<Pair<Long, String>> selectCountriesByCurUser() {
        List<Long> countryIds = tcAccountMapper.selectCountriesByCurUser(SecurityUtils.getPermissionCharIns());
        
        return LocalUtils.selectCountriesByCurUser(countryIds);
    }

    @Override
    public List<GetAccountByAgentDto> getAccountByAgent(Long ownerAgent){
        return tcAccountMapper.getAccountByAgent(ownerAgent);
    }

    @Override
    public List<Pair<Long, String>> selectAreasByCurUser() {
        List<Long> areaIds = tcAccountMapper.selectAreasByCurUser(SecurityUtils.getPermissionCharIns());
        return LocalUtils.selectAreasByCurUser(areaIds);
    }

    @Override
    public boolean changeOwner(TcAccount tcAccount) {

        tcAccount.setUpdateBy(SecurityUtils.getUserId().toString());
        tcAccount.setUpdateTime(DateUtils.getNowDate());
        SysUser user = sysUserService.selectUserById(tcAccount.getOwner());
        if (user == null) {
            throw new ServiceException("user not found");
        }
        tcAccount.setPermissionChar(0L == user.getDeptId() ? user.getAreaId() : user.getDeptId().toString());
        int i = tcAccountMapper.updateTcAccount(tcAccount);

        TcAccount tcAccountHis = selectTcAccountByAccountId(tcAccount.getAccountId());
        if(ObjectUtils.isEmpty(tcAccountHis.getFileList())){
            tcAccountHis.setFileList(null);
        }
        saveHis(tcAccountHis, tcAccountHis.getContactList());

        // // 同时变更区域，如果变更的目标用户有多个区域权限，取有关联的第一个
        // TcAccount accountDb = tcAccountMapper.selectTcAccountByAccountId(tcAccount.getAccountId());
        // List<Long> areaIdList = user.getAreaIdList();
        // if (CollectionUtils.isNotEmpty(areaIdList)) {
        //     Long areaId = accountDb.getAreaId();
        //     List<TbArea> areas = tbAreaMapper.selectListByIdsAndAncestorId(areaIdList, areaId);
        //     // Map<Long, List<String>> area = areas.stream().collect(Collectors.toMap(TbArea::getAreaId, item -> Arrays.stream(item.getPermissionChar().split(",")).filter(StringUtils::isNotBlank).collect(Collectors.toList())));
        //     if (CollectionUtils.isEmpty(areas)) {
        //         tcAccount.setAreaId(areaIdList.get(0));
        //     } else {
        //         tcAccount.setAreaId(areas.get(0).getAreaId());
        //     }
        // }

        return i> 0;
    }

    @Override
    public List<TcAccount> listByAccountNameList(List<String> accountNameList) {
        return tcAccountMapper.listByAccountNameList(accountNameList, SecurityUtils.getPermissionCharIns());
    }
}
