EnterpriseAccountServiceImpl.java 105 KB
Newer Older
eddie.woo's avatar
eddie.woo committed
1 2 3 4


package pwc.taxtech.atms.service.impl;

5
import com.google.common.collect.Lists;
eddie.woo's avatar
eddie.woo committed
6
import com.google.common.collect.Maps;
eddie.woo's avatar
eddie.woo committed
7
import org.apache.commons.collections.CollectionUtils;
eddie.woo's avatar
eddie.woo committed
8
import org.apache.commons.collections.MapUtils;
eddie.woo's avatar
eddie.woo committed
9
import org.apache.commons.lang3.StringUtils;
eddie.woo's avatar
eddie.woo committed
10 11 12 13
import org.nutz.lang.Files;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
14 15 16 17 18
import pwc.taxtech.atms.common.CommonConstants;
import pwc.taxtech.atms.common.CommonUtils;
import pwc.taxtech.atms.common.OperateLogType;
import pwc.taxtech.atms.common.OperationAction;
import pwc.taxtech.atms.common.OperationModule;
eddie.woo's avatar
eddie.woo committed
19
import pwc.taxtech.atms.common.message.EnterpriseAccountMessage;
eddie.woo's avatar
eddie.woo committed
20
import pwc.taxtech.atms.common.message.EnterpriseAccountSetOrgMsg;
eddie.woo's avatar
eddie.woo committed
21 22 23
import pwc.taxtech.atms.common.message.LogMessage;
import pwc.taxtech.atms.constant.EnterpriseAccountConstant;
import pwc.taxtech.atms.constant.IndustryConstant;
eddie.woo's avatar
eddie.woo committed
24
import pwc.taxtech.atms.constant.enums.AccountRuleEnum;
25 26 27 28 29 30 31
import pwc.taxtech.atms.dao.AccountMappingDao;
import pwc.taxtech.atms.dao.AccountMappingManualDao;
import pwc.taxtech.atms.dao.AccountMappingManualMapper;
import pwc.taxtech.atms.dao.EnterpriseAccountDao;
import pwc.taxtech.atms.dao.EnterpriseAccountSetOrgDao;
import pwc.taxtech.atms.dao.OrganizationMapper;
import pwc.taxtech.atms.dao.StandardAccountDao;
32
import pwc.taxtech.atms.dpo.EnterpriseAccountDto;
eddie.woo's avatar
eddie.woo committed
33
import pwc.taxtech.atms.dto.OperationLogDto;
eddie.woo's avatar
eddie.woo committed
34 35 36
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.UpdateLogParams;
import pwc.taxtech.atms.dto.ValidateInfoDto;
eddie.woo's avatar
eddie.woo committed
37
import pwc.taxtech.atms.dto.accountmapping.AccountMappingManualDto;
38 39 40 41
import pwc.taxtech.atms.dto.epaccount.AccountMapDto;
import pwc.taxtech.atms.dto.epaccount.AccountMappingDto;
import pwc.taxtech.atms.dto.epaccount.EnterpriseAccountAndValidateInfo;
import pwc.taxtech.atms.dto.epaccount.EnterpriseAccountSetDto;
eddie.woo's avatar
eddie.woo committed
42
import pwc.taxtech.atms.dto.stdaccount.StandardAccountDto;
43
import pwc.taxtech.atms.entity.*;
eddie.woo's avatar
eddie.woo committed
44

eddie.woo's avatar
eddie.woo committed
45 46 47 48
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

eddie.woo's avatar
eddie.woo committed
49
@Service
50
public class EnterpriseAccountServiceImpl extends AbstractService {
eddie.woo's avatar
eddie.woo committed
51

eddie.woo's avatar
eddie.woo committed
52
    @Autowired
53
    private AccountServiceImpl accountService;
eddie.woo's avatar
eddie.woo committed
54
    @Autowired
55
    private EnterpriseAccountSetServiceImpl enterpriseAccountSetService;
eddie.woo's avatar
eddie.woo committed
56 57 58 59 60 61 62 63 64 65 66 67
    @Autowired
    private FileService fileService;
    @Autowired
    private EnterpriseAccountDao enterpriseAccountDao;
    @Autowired
    private StandardAccountDao standardAccountDao;
    @Autowired
    private AccountMappingManualDao mappingManualDao;
    @Autowired
    private EnterpriseAccountSetOrgDao epAccountSetOrgDao;
    @Autowired
    private AccountMappingDao accountMappingDao;
eddie.woo's avatar
eddie.woo committed
68 69
    @Autowired
    private AccountMappingManualMapper mappingManualMapper;
70 71 72
    @Autowired
    private OrganizationMapper organizationMapper;

eddie.woo's avatar
eddie.woo committed
73
    private Map<String, List<String>> mapParentAccountResult;
74 75


eddie.woo's avatar
eddie.woo committed
76 77 78
    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#getEnterpriseAccount(java.lang.String, java.lang.String)
     */
79
    public EnterpriseAccount getEnterpriseAccount(String enterpriseAccountCode, String enterpriseAccountSetId) {
eddie.woo's avatar
eddie.woo committed
80
        EnterpriseAccountExample example = new EnterpriseAccountExample();
81
        example.createCriteria().andCodeEqualTo(enterpriseAccountCode).andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId);
82

eddie.woo's avatar
eddie.woo committed
83
        List<EnterpriseAccount> epAccounts = enterpriseAccountMapper.selectByExample(example);
84
        return CollectionUtils.isEmpty(epAccounts) ? null : epAccounts.get(0);
eddie.woo's avatar
eddie.woo committed
85 86 87 88
    }

    /*
     * (non-Javadoc)
89
     *
eddie.woo's avatar
eddie.woo committed
90
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#
91
     * getListByEnterpriseAccountSetId(java.lang.String)
eddie.woo's avatar
eddie.woo committed
92
     */
93
    public EnterpriseAccountAndValidateInfo getListByEnterpriseAccountSetId(String enterpriseAccountSetId) {
eddie.woo's avatar
eddie.woo committed
94 95 96

        EnterpriseAccountExample enterpriseAccountExample = new EnterpriseAccountExample();
        enterpriseAccountExample.createCriteria()
97 98
                .andRuleTypeEqualTo(2)
                .andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId);
gary's avatar
gary committed
99
        enterpriseAccountExample.setOrderByClause("parent_code ASC, is_active Desc, code ASC");
eddie.woo's avatar
eddie.woo committed
100
        List<EnterpriseAccount> epAccounts = enterpriseAccountMapper.selectByExample(enterpriseAccountExample);
101

eddie.woo's avatar
eddie.woo committed
102
        //no enterprise account
103
        if (epAccounts == null || epAccounts.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
104 105
            return new EnterpriseAccountAndValidateInfo();
        }
106

eddie.woo's avatar
eddie.woo committed
107 108 109
        //get all standard accounts
        StandardAccountExample standardAccountExample = new StandardAccountExample();
        List<StandardAccount> stdAccounts = standardAccountMapper.selectByExample(standardAccountExample);
110

eddie.woo's avatar
eddie.woo committed
111 112
        //set stdName
        List<EnterpriseAccountDto> epAccountDtoList = new ArrayList<>();
113
        for (EnterpriseAccount epAccount : epAccounts) {
eddie.woo's avatar
eddie.woo committed
114
            EnterpriseAccountDto epAccountDto = new EnterpriseAccountDto();
115

eddie.woo's avatar
eddie.woo committed
116 117 118 119 120
            CommonUtils.copyProperties(epAccount, epAccountDto);
            epAccountDto.setParentName("");
            epAccountDto.setParentFullName("");
            epAccountDto.setStdName("");
            stdAccounts.stream().filter(stdAccount -> stdAccount.getCode().equals(epAccount.getStdCode())).findFirst()
121 122 123
                    .ifPresent(stdAccount -> {
                        epAccountDto.setStdName(stdAccount.getName());
                    });
eddie.woo's avatar
eddie.woo committed
124 125
            epAccountDtoList.add(epAccountDto);
        }
126

eddie.woo's avatar
eddie.woo committed
127 128
        //wrap epAccounts and generate retEpAccountDtoList
        List<EnterpriseAccountDto> retEpAccountDtoList = new ArrayList<>();
129 130
        List<EnterpriseAccountDto> topEpAccountDtoList
                = epAccountDtoList.stream().filter(epAccountDto -> epAccountDto.getParentCode() == null)
eddie.woo's avatar
eddie.woo committed
131
                .collect(Collectors.toList());
132
        for (EnterpriseAccountDto epAccountDto : topEpAccountDtoList) {
eddie.woo's avatar
eddie.woo committed
133 134 135 136
            epAccountDto.setTreeLevel(0);
            retEpAccountDtoList.add(epAccountDto);
            retEpAccountDtoList.addAll(getWrapList(epAccountDto, epAccountDtoList));
        }
137

eddie.woo's avatar
eddie.woo committed
138
        //lost epAccounts list
139 140
        for (EnterpriseAccountDto epAccountDto : epAccountDtoList) {
            if (!retEpAccountDtoList.contains(epAccountDto)) {
eddie.woo's avatar
eddie.woo committed
141 142 143
                retEpAccountDtoList.add(epAccountDto);
            }
        }
144

eddie.woo's avatar
eddie.woo committed
145 146
        //validate enterprise account list
        List<ValidateInfoDto> validateInfoList = validateEnterpriseAccountList(retEpAccountDtoList);
147

eddie.woo's avatar
eddie.woo committed
148 149 150
        EnterpriseAccountAndValidateInfo enterpriseAccountAndValidateInfo = new EnterpriseAccountAndValidateInfo();
        enterpriseAccountAndValidateInfo.setEnterpriseAccountList(retEpAccountDtoList);
        enterpriseAccountAndValidateInfo.setValidateInfoList(validateInfoList);
151

eddie.woo's avatar
eddie.woo committed
152 153
        return enterpriseAccountAndValidateInfo;
    }
154

eddie.woo's avatar
eddie.woo committed
155 156 157 158
    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#getEnterpriseAccount(java.lang.String)
     */
    public EnterpriseAccountDto getEnterpriseAccount(String enterpriseAccountId) {
159

eddie.woo's avatar
eddie.woo committed
160
        EnterpriseAccount enterpriseAccount = enterpriseAccountMapper.selectByPrimaryKey(enterpriseAccountId);
161

eddie.woo's avatar
eddie.woo committed
162 163 164
        //get all enterprise accounts
        EnterpriseAccountExample enterpriseAccountExample = new EnterpriseAccountExample();
        enterpriseAccountExample.createCriteria()
165 166 167
                .andIsActiveEqualTo(CommonConstants.ACTIVE_STATUS)
                .andRuleTypeEqualTo(2)
                .andEnterpriseAccountSetIdEqualTo(enterpriseAccount.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
168
        List<EnterpriseAccount> epAccounts = enterpriseAccountMapper.selectByExample(enterpriseAccountExample);
169

eddie.woo's avatar
eddie.woo committed
170 171 172
        //get all standard accounts
        StandardAccountExample standardAccountExample = new StandardAccountExample();
        List<StandardAccount> stdAccounts = standardAccountMapper.selectByExample(standardAccountExample);
173

eddie.woo's avatar
eddie.woo committed
174 175
        EnterpriseAccountDto enterpriseAccountDto = new EnterpriseAccountDto();
        CommonUtils.copyProperties(enterpriseAccount, enterpriseAccountDto);
176 177 178 179
        epAccounts.stream().filter(epAccount -> enterpriseAccount.getParentCode() != null && enterpriseAccount.getParentCode().equals(epAccount.getCode())).findFirst()
                .ifPresent(epAccount -> {
                    enterpriseAccountDto.setParentName(epAccount.getName());
                    enterpriseAccountDto.setParentFullName(epAccount.getFullName());
eddie.woo's avatar
eddie.woo committed
180 181
                });
        stdAccounts.stream().filter(stdAccount -> stdAccount.getCode().equals(enterpriseAccount.getStdCode())).findFirst()
182 183
                .ifPresent(stdAccount -> {
                    enterpriseAccountDto.setStdName(stdAccount.getName());
eddie.woo's avatar
eddie.woo committed
184 185
                });
        enterpriseAccountDto.setSubStdAccounts(new ArrayList<>());
186
        enterpriseAccountDto.setIndustryId("");
187

eddie.woo's avatar
eddie.woo committed
188 189
        return enterpriseAccountDto;
    }
190

eddie.woo's avatar
eddie.woo committed
191 192 193 194 195 196
    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#addEnterpriseAccount(pwc.taxtech.atms.service.dto.EnterpriseAccountDto)
     */
    @Transactional
    public OperationResultDto<List<EnterpriseAccountDto>> addEnterpriseAccount(EnterpriseAccountDto enterpriseAccountDto) {

197
        if (enterpriseAccountDto == null) {
eddie.woo's avatar
eddie.woo committed
198 199 200 201
            return new OperationResultDto<>(false);
        }
        EnterpriseAccount entityToAdd = new EnterpriseAccount();
        CommonUtils.copyProperties(enterpriseAccountDto, entityToAdd);
202

eddie.woo's avatar
eddie.woo committed
203 204
        //check duplication ep account
        List<EnterpriseAccountDto> sameEpAccounts = getSameEnterpriseAccountList(enterpriseAccountDto);
205
        if (sameEpAccounts != null && !sameEpAccounts.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
206 207 208
            return new OperationResultDto<>(false, EnterpriseAccountMessage.EnterpriceAccountRepeat, sameEpAccounts);
        }
        //set parent account no leaf
209
        setParentIsNotLeaf(enterpriseAccountDto.getParentCode(), enterpriseAccountDto.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
210
        //add enterprise accoun
211
        entityToAdd.setId(CommonUtils.getUUID());
eddie.woo's avatar
eddie.woo committed
212 213 214
        entityToAdd.setIsLeaf(true);
        entityToAdd.setCreateTime(new Date());
        entityToAdd.setUpdateTime(new Date());
215 216
        entityToAdd.setCreatorId(authUserHelper.getCurrentUserId());
        entityToAdd.setUpdatorId(authUserHelper.getCurrentUserId());
eddie.woo's avatar
eddie.woo committed
217
        enterpriseAccountMapper.insert(entityToAdd);
218

eddie.woo's avatar
eddie.woo committed
219 220
        //获取与之关联的机构
        EnterpriseAccountSetOrgExample example = new EnterpriseAccountSetOrgExample();
221
        example.createCriteria().andEnterpriseAccountSetIdEqualTo(enterpriseAccountDto.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
222
        List<EnterpriseAccountSetOrg> accountSetOrgList = enterpriseAccountSetOrgMapper.selectByExampleWithAssociation(example);
223

eddie.woo's avatar
eddie.woo committed
224 225 226
        //构造数据结构,调用更新父级科目对应方法
        List<String> epAccountCodeList = new ArrayList<>();
        epAccountCodeList.add(entityToAdd.getCode());
227

eddie.woo's avatar
eddie.woo committed
228
        this.mapParentAccountResult = new HashMap<>();
229
        for (EnterpriseAccountSetOrg accountSetOrg : accountSetOrgList) {
230 231
            String industryId = organizationMapper.selectByPrimaryKey(accountSetOrg.getOrganizationId()).getIndustryId();
            mapAccountUpdateParent(epAccountCodeList, accountSetOrg.getEnterpriseAccountSetId(), getConvertedIndustryId(industryId), accountSetOrg.getOrganizationId(), true);
eddie.woo's avatar
eddie.woo committed
232
        }
233

eddie.woo's avatar
eddie.woo committed
234
        //get enterprise set name
235
        EnterpriseAccountSet enterpriseAccountSet = enterpriseAccountSetMapper.selectByPrimaryKey(enterpriseAccountDto.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
236 237
        //add operational log
        UpdateLogParams updateLogParams = new UpdateLogParams();
238
        updateLogParams.setOperationUser(authUserHelper.getCurrentAuditor().get());
eddie.woo's avatar
eddie.woo committed
239 240 241 242 243 244 245 246 247
        updateLogParams.setUpdateState("");
        updateLogParams.setOriginalState("");
        updateLogParams.setOperationContent(enterpriseAccountDto.getCode() + " " + enterpriseAccountDto.getName());
        updateLogParams.setOperationObject(enterpriseAccountSet.getName());
        updateLogParams.setOperationModule(OperationModule.BasicDataEnterpriceAccount.value());
        updateLogParams.setOperateLogType(OperateLogType.OperationLogEnterPrise.value());
        updateLogParams.setComment("");
        updateLogParams.setOperationAction(OperationAction.New.value());
        operationLogService.addOrDeleteDataAddLog(updateLogParams);
248

eddie.woo's avatar
eddie.woo committed
249 250 251 252 253 254 255 256 257
        return new OperationResultDto<>(true);
    }

    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#updateEnterpriseAccount(pwc.taxtech.atms.service.dto.EnterpriseAccountDto)
     */
    @Transactional
    public OperationResultDto<List<EnterpriseAccountDto>> updateEnterpriseAccount(EnterpriseAccountDto enterpriseAccountDto) {

258
        if (enterpriseAccountDto == null) {
eddie.woo's avatar
eddie.woo committed
259 260
            return new OperationResultDto<>(false);
        }
261

262
        EnterpriseAccount entityToUpdate = enterpriseAccountMapper.selectByPrimaryKey(enterpriseAccountDto.getId());
263
        if (entityToUpdate == null) {
eddie.woo's avatar
eddie.woo committed
264 265
            return new OperationResultDto<>(false);
        }
266

eddie.woo's avatar
eddie.woo committed
267 268
        //check duplication ep account
        List<EnterpriseAccountDto> sameEpAccounts = getSameEnterpriseAccountList(enterpriseAccountDto);
269
        if (sameEpAccounts != null && !sameEpAccounts.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
270 271
            return new OperationResultDto<>(false, EnterpriseAccountMessage.EnterpriceAccountRepeat, sameEpAccounts);
        }
272

eddie.woo's avatar
eddie.woo committed
273 274 275
        //copy entityToUpdate
        EnterpriseAccount entityCopy = new EnterpriseAccount();
        CommonUtils.copyProperties(entityToUpdate, entityCopy);
276 277

        if (entityCopy.getParentCode() != null && !entityCopy.getParentCode().equals(enterpriseAccountDto.getParentCode())) {
eddie.woo's avatar
eddie.woo committed
278
            // reset the isleaf
279 280
            setParentIsNotLeaf(enterpriseAccountDto.getParentCode(), enterpriseAccountDto.getEnterpriseAccountSetId());
            setParentLeaf(entityCopy.getParentCode(), enterpriseAccountDto.getEnterpriseAccountSetId(), enterpriseAccountDto.getId());
eddie.woo's avatar
eddie.woo committed
281
        }
282 283


eddie.woo's avatar
eddie.woo committed
284 285 286 287
        //查询所有原本对应子科目
        //如修改的为父科目, 需要级联修改其所有子科目的父科目代码以及名字
        EnterpriseAccountExample enterpriseAccountexample = new EnterpriseAccountExample();
        enterpriseAccountexample.createCriteria()
288 289
                .andParentCodeEqualTo(entityCopy.getCode())
                .andEnterpriseAccountSetIdEqualTo(enterpriseAccountDto.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
290
        List<EnterpriseAccount> childrenAccountList = enterpriseAccountMapper.selectByExample(enterpriseAccountexample);
291 292 293
        if (childrenAccountList != null && !childrenAccountList.isEmpty()) {
            if (!entityCopy.getCode().equals(enterpriseAccountDto.getCode()) || !entityCopy.getName().equals(enterpriseAccountDto.getName())) {
                for (EnterpriseAccount childrenAccount : childrenAccountList) {
eddie.woo's avatar
eddie.woo committed
294 295 296 297 298 299
                    childrenAccount.setParentCode(enterpriseAccountDto.getCode());
                    childrenAccount.setFullName(enterpriseAccountDto.getFullName() + EnterpriseAccountConstant.FullNameSeparator + childrenAccount.getName());
                    enterpriseAccountMapper.updateByPrimaryKey(childrenAccount);
                }
            }
        }
300

eddie.woo's avatar
eddie.woo committed
301 302 303 304 305 306 307 308
        entityToUpdate.setCode(enterpriseAccountDto.getCode());
        entityToUpdate.setName(enterpriseAccountDto.getName());
        entityToUpdate.setFullName(enterpriseAccountDto.getFullName());
        entityToUpdate.setParentCode(enterpriseAccountDto.getParentCode());
        entityToUpdate.setDirection(enterpriseAccountDto.getDirection());
        entityToUpdate.setAcctProp(enterpriseAccountDto.getAcctProp());
        entityToUpdate.setStdCode(enterpriseAccountDto.getStdCode());
        enterpriseAccountMapper.updateByPrimaryKey(entityToUpdate);
309

eddie.woo's avatar
eddie.woo committed
310 311
        //获取与之关联的机构
        EnterpriseAccountSetOrgExample example = new EnterpriseAccountSetOrgExample();
312
        example.createCriteria().andEnterpriseAccountSetIdEqualTo(enterpriseAccountDto.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
313
        List<EnterpriseAccountSetOrg> accountSetOrgList = enterpriseAccountSetOrgMapper.selectByExampleWithAssociation(example);
314

eddie.woo's avatar
eddie.woo committed
315 316 317
        //构造数据结构,调用更新父级科目对应方法
        List<String> epAccountCodeList = new ArrayList<>();
        epAccountCodeList.add(entityToUpdate.getCode());
318

eddie.woo's avatar
eddie.woo committed
319
        this.mapParentAccountResult = new HashMap<>();
320 321
        for (EnterpriseAccountSetOrg accountSetOrg : accountSetOrgList) {
            if (entityToUpdate.getParentCode() != null && entityToUpdate.getParentCode().equals(entityCopy.getParentCode())) {
eddie.woo's avatar
eddie.woo committed
322 323
                
                /* @See below C#代码 EnterpriseAccountService.cs Line 238-240
324 325
                 * string updateSql = "UPDATE AccountMapping SET StandardAccountCode='00' WHERE EnterpriseAccountCode={0} AND EnterpriseAccountSetId={1} AND OrganizationId={2} AND IndustryId={3}";
                   _dbContext.Database.ExecuteSqlCommand(updateSql, entity.id, item.EnterpriseAccountSetId, item.OrganizationId, GetConvertedIndustryId(item.IndustryId));
eddie.woo's avatar
eddie.woo committed
326 327
                 * EnterpriseAccountCode 参数应该设错了
                 */
328

eddie.woo's avatar
eddie.woo committed
329 330 331 332 333
                //需要清除旧的对应关系
                AccountMapping accountMapping = new AccountMapping();
                accountMapping.setStandardAccountCode("00");
                AccountMappingExample accountMappingExample = new AccountMappingExample();
                accountMappingExample.createCriteria()
334 335 336 337
                        .andEnterpriseAccountCodeEqualTo(entityCopy.getParentCode())
                        .andEnterpriseAccountSetIdEqualTo(accountSetOrg.getEnterpriseAccountSetId())
                        .andOrganizationIdEqualTo(accountSetOrg.getOrganizationId())
                        .andIndustryIdEqualTo(getConvertedIndustryId(accountSetOrg.getOrganization().getIndustryId()));
eddie.woo's avatar
eddie.woo committed
338 339
                accountMappingMapper.updateByExampleSelective(accountMapping, accountMappingExample);
            }
340
            mapAccountUpdateParent(epAccountCodeList, accountSetOrg.getEnterpriseAccountSetId(),
341
                    getConvertedIndustryId(accountSetOrg.getOrganization().getIndustryId()), accountSetOrg.getOrganizationId(), true);
eddie.woo's avatar
eddie.woo committed
342 343
        }
        //get enterprise set name
344
        EnterpriseAccountSet enterpriseAccountSet = enterpriseAccountSetMapper.selectByPrimaryKey(enterpriseAccountDto.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
345 346
        //operation log
        UpdateLogParams updateLogParams = new UpdateLogParams();
347
        updateLogParams.setOperationUser(authUserHelper.getCurrentAuditor().get());
eddie.woo's avatar
eddie.woo committed
348 349 350 351 352 353 354 355 356
        updateLogParams.setUpdateState(getEnterpriseAccountInfo(entityToUpdate));
        updateLogParams.setOriginalState(getEnterpriseAccountInfo(entityCopy));
        updateLogParams.setOperationContent(enterpriseAccountDto.getCode() + " " + enterpriseAccountDto.getName());
        updateLogParams.setOperationObject(enterpriseAccountSet.getName());
        updateLogParams.setOperationModule(OperationModule.BasicDataEnterpriceAccount.value());
        updateLogParams.setOperateLogType(OperateLogType.OperationLogEnterPrise.value());
        updateLogParams.setComment("");
        updateLogParams.setOperationAction(OperationAction.UpdateEnterpriseAccount.value());
        operationLogService.addOrDeleteDataAddLog(updateLogParams);
357

358
        enableEnterpriseAccountSet(enterpriseAccountDto.getEnterpriseAccountSetId());
359

eddie.woo's avatar
eddie.woo committed
360 361
        return new OperationResultDto<>(true);
    }
362 363


eddie.woo's avatar
eddie.woo committed
364 365 366
    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#mapAccountUpdateParent(java.util.List, java.lang.String, java.lang.String, java.lang.String, java.lang.Boolean)
     */
367
    public void mapAccountUpdateParent(List<String> enterpriseAccountCodeList, String enterpriseAccountSetId,
368
                                       String industryId, String orgId, Boolean isToUpdateEvenExists) {
eddie.woo's avatar
eddie.woo committed
369 370

        for (String epAccountCode : enterpriseAccountCodeList) {
371

eddie.woo's avatar
eddie.woo committed
372 373
            /* 数据准备 start */
            String mappedStdCode = "";
374

eddie.woo's avatar
eddie.woo committed
375 376 377
            //第一步:通过企业科目Code获取企业科目对象
            EnterpriseAccountExample enterpriseAccountExample = new EnterpriseAccountExample();
            enterpriseAccountExample.createCriteria()
378 379
                    .andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId)
                    .andCodeEqualTo(epAccountCode);
eddie.woo's avatar
eddie.woo committed
380
            List<EnterpriseAccount> epAccounts = enterpriseAccountMapper.selectByExample(enterpriseAccountExample);
381
            if (CollectionUtils.isEmpty(epAccounts)) {
eddie.woo's avatar
eddie.woo committed
382 383 384 385
                continue;
            }
            EnterpriseAccount epAccount = epAccounts.get(0);
            //如果当前对应的本身就是第一级,不需要再考虑
386
            if (epAccount.getParentCode() == null || epAccount.getParentCode().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
387 388
                continue;
            }
389

eddie.woo's avatar
eddie.woo committed
390 391 392
            //第二步: 通过上一步获取到的企业科目对象的ParentCode获取企业企业科目对象
            enterpriseAccountExample = new EnterpriseAccountExample();
            enterpriseAccountExample.createCriteria()
393 394
                    .andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId)
                    .andCodeEqualTo(epAccount.getParentCode());
eddie.woo's avatar
eddie.woo committed
395
            List<EnterpriseAccount> parentEpAccounts = enterpriseAccountMapper.selectByExample(enterpriseAccountExample);
396
            if (CollectionUtils.isEmpty(parentEpAccounts)) {
eddie.woo's avatar
eddie.woo committed
397 398 399
                return; //C# return
            }
            EnterpriseAccount parentEpAccount = parentEpAccounts.get(0);
400

eddie.woo's avatar
eddie.woo committed
401
            //第三步: 通过Parent企业科目对象获取该ParentCode下面的所有子企业科目
402
            List<EnterpriseAccount> childrenEpAccountList = getMappingResultByParentCode(parentEpAccount.getCode(), enterpriseAccountSetId, industryId, orgId);
403

eddie.woo's avatar
eddie.woo committed
404
            //第四步: 判断第三步获取到企业科目中,标准科目为空的个数
405
            if (CollectionUtils.isEmpty(childrenEpAccountList)) {
eddie.woo's avatar
eddie.woo committed
406 407
                continue;
            }
408 409
            long emptyStdCodeCount = childrenEpAccountList.stream().filter(sa -> sa.getStdCode() == null || sa.getStdCode().isEmpty()).count();

eddie.woo's avatar
eddie.woo committed
410 411
            //第五部: 将第三步获取到的所有企业科目取出其中的StdCode并去重
            List<String> uniqueStdCodeList = childrenEpAccountList.stream()
412
                    .filter(sa -> sa.getStdCode() != null && !sa.getStdCode().isEmpty())
eddie.woo's avatar
eddie.woo committed
413 414
                    .map(sa -> sa.getStdCode()).collect(Collectors.toList());
            /* 数据准备 end */
415

eddie.woo's avatar
eddie.woo committed
416
            /* 业务处理 start */
417

eddie.woo's avatar
eddie.woo committed
418
            //等于0说明子科目全部都有对应上
419 420
            if (emptyStdCodeCount == 0) {

eddie.woo's avatar
eddie.woo committed
421
                long countOfDistinctStdCode = uniqueStdCodeList.size();
422

eddie.woo's avatar
eddie.woo committed
423
                //等于1说明对应上的标准科目都是同一个
424
                if (countOfDistinctStdCode == 1) {
eddie.woo's avatar
eddie.woo committed
425 426 427 428 429
                    //2. 手动对应,子科目完全对应的时候并且都对应到同一个标准科目,那么父级也要对应到该标准科目
                    mappedStdCode = uniqueStdCodeList.get(0);
                }
                //说明虽然完全对应上了,但是对应上的标准科目代码不唯一
                else {
430

eddie.woo's avatar
eddie.woo committed
431 432 433
                    //3. 手动对应,子科目完全对应的时候但是没有对应到同一个标准科目
                    StandardAccountExample standardAccountExample = new StandardAccountExample();
                    standardAccountExample.createCriteria()
434
                            .andCodeIn(uniqueStdCodeList).andIndustryIdEqualTo(industryId);
eddie.woo's avatar
eddie.woo committed
435
                    List<StandardAccount> standardAccountList = standardAccountMapper.selectByExample(standardAccountExample);
436
                    if (CollectionUtils.isEmpty(standardAccountList)) {
eddie.woo's avatar
eddie.woo committed
437 438 439 440 441
                        continue;
                    }
                    List<String> distinctStdParentCodeList = standardAccountList.stream()
                            .map(sa -> sa.getParentCode()).distinct().collect(Collectors.toList());
                    long uniqueStdParentCodeCount = distinctStdParentCodeList.size();
442

eddie.woo's avatar
eddie.woo committed
443
                    //等于1说明对应上的都属于同一个父级标准科目
444 445
                    if (uniqueStdParentCodeCount == 1
                            && distinctStdParentCodeList.get(0) != null && !distinctStdParentCodeList.get(0).isEmpty()
eddie.woo's avatar
eddie.woo committed
446 447 448
                            && !uniqueStdCodeList.contains("0000")) {
                        //子科目完全对应的时候但是没有对应到同一个标准科目但是属于同一个父科目下,那么该企业科目的父级也要对应到该标准科目的父级
                        mappedStdCode = standardAccountList.get(0).getParentCode();
449
                    } else {
eddie.woo's avatar
eddie.woo committed
450 451 452 453
                        //子科目完全对应的时候但是没有对应到同一个标准科目又不属于同一个父科目下,那么该企业科目的父级显示为横线 -
                        mappedStdCode = CommonConstants.EmptyStdCode;
                    }
                }
454
            } else {
eddie.woo's avatar
eddie.woo committed
455 456 457
                //4.  手动对应,子科目没有全对应的时候,那么父级科目显示为未对应
                mappedStdCode = null;
            }
458

eddie.woo's avatar
eddie.woo committed
459 460
            /* 更新UI准备  start */
            StandardAccount stdAccount = new StandardAccount();
461
            if (mappedStdCode == CommonConstants.EmptyStdCode) {
eddie.woo's avatar
eddie.woo committed
462 463
                stdAccount.setCode(CommonConstants.EmptyStdCode);
                stdAccount.setName("");
464
            } else if (mappedStdCode == null) {
eddie.woo's avatar
eddie.woo committed
465 466
                stdAccount.setCode(null);
                stdAccount.setName("");
467
            } else {
eddie.woo's avatar
eddie.woo committed
468 469
                StandardAccountExample standardAccountExample = new StandardAccountExample();
                standardAccountExample.createCriteria()
470 471
                        .andCodeEqualTo(mappedStdCode)
                        .andIndustryIdEqualTo(industryId);
eddie.woo's avatar
eddie.woo committed
472
                List<StandardAccount> stdAccountList = standardAccountMapper.selectByExample(standardAccountExample);
eddie.woo's avatar
eddie.woo committed
473
                if (CollectionUtils.isEmpty(stdAccountList)) {
eddie.woo's avatar
eddie.woo committed
474 475 476 477 478
                    continue;
                }
                stdAccount = stdAccountList.get(0);
            }
            addMapParentAccountResult(parentEpAccount.getCode(), Arrays.asList(stdAccount.getCode(), stdAccount.getName()));
479

eddie.woo's avatar
eddie.woo committed
480
            //更新该企业科目的标准科目为mappedStdCode
481
            accountService.mapStdAccountByCode(enterpriseAccountSetId, stdAccount.getCode(), epAccountCode, industryId, orgId, isToUpdateEvenExists, 0);
482

eddie.woo's avatar
eddie.woo committed
483 484
            /* 更新UI准备  end */
            /* 业务处理 end */
485

eddie.woo's avatar
eddie.woo committed
486
            /* 如果还存在上一级的情况,所以递归处理 start */
487
            mapAccountUpdateParent(Arrays.asList(parentEpAccount.getCode()), enterpriseAccountSetId, industryId, orgId, isToUpdateEvenExists);
eddie.woo's avatar
eddie.woo committed
488 489 490 491 492 493 494 495 496 497
            /* 如果还存在上一级的情况,所以递归处理 end */
        }
    }

    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#createEnterpriseAccountSetAndimportEnterpriseAccount(java.lang.String, java.lang.String, java.util.List)
     */
    @SuppressWarnings("rawtypes")
    @Transactional
    public OperationResultDto addEnterpriseAccountSetAndImportData(String enterpriseAccountSetName,
498 499
                                                                   String enterpriseAccountSetCode, List<EnterpriseAccountDto> importData) {

eddie.woo's avatar
eddie.woo committed
500 501 502 503 504
        EnterpriseAccountSetDto enterpriseAccountSetDto = new EnterpriseAccountSetDto();
        enterpriseAccountSetDto.setName(enterpriseAccountSetName);
        enterpriseAccountSetDto.setCode(enterpriseAccountSetCode);
        //validate name is duplicated
        OperationResultDto<?> nameValidate = enterpriseAccountSetService.enterpriseAccountSetNameValidate(enterpriseAccountSetDto);
505
        if (!nameValidate.getResult()) {
eddie.woo's avatar
eddie.woo committed
506 507 508 509
            return nameValidate;
        }
        //validate code is duplicated
        OperationResultDto<?> codeValidate = enterpriseAccountSetService.enterpriseAccountSetCodeValidate(enterpriseAccountSetDto);
510
        if (!codeValidate.getResult()) {
eddie.woo's avatar
eddie.woo committed
511 512
            return codeValidate;
        }
513

eddie.woo's avatar
eddie.woo committed
514 515 516
        //save enterprise account set
        EnterpriseAccountSet enterpriseAccountSet = new EnterpriseAccountSet();
        CommonUtils.copyProperties(enterpriseAccountSetDto, enterpriseAccountSet);
517
        enterpriseAccountSet.setId(CommonUtils.getUUID());
eddie.woo's avatar
eddie.woo committed
518 519 520
        enterpriseAccountSet.setIsActive(CommonConstants.ACTIVE_STATUS);
        enterpriseAccountSet.setCreateTime(new Date());
        enterpriseAccountSet.setUpdateTime(new Date());
521
        enterpriseAccountSet.setCreatorId(authUserHelper.getCurrentUserId());
eddie.woo's avatar
eddie.woo committed
522
        enterpriseAccountSetMapper.insert(enterpriseAccountSet);
523

eddie.woo's avatar
eddie.woo committed
524 525
        //create operationlog for creating enterprise account set
        UpdateLogParams updateLogParams = new UpdateLogParams();
526
        updateLogParams.setOperationUser(authUserHelper.getCurrentAuditor().get());
eddie.woo's avatar
eddie.woo committed
527 528 529
//        updateLogParams.setUpdateState("");
//        updateLogParams.setOriginalState("");
//        updateLogParams.setOperationContent("");
eddie.woo's avatar
eddie.woo committed
530
        updateLogParams.setOperationModule(OperationModule.BasicDataEnterpriceAccount.value());
eddie.woo's avatar
eddie.woo committed
531
//        updateLogParams.setComment("");
eddie.woo's avatar
eddie.woo committed
532 533 534 535
        updateLogParams.setOperateLogType(OperateLogType.OperationLogEnterPrise.value());
        updateLogParams.setOperationAction(OperationAction.AddEnterpriseAccountSet.value());
        updateLogParams.setOperationObject(enterpriseAccountSet.getName());
        operationLogService.addOrDeleteDataAddLog(updateLogParams);
536

eddie.woo's avatar
eddie.woo committed
537
        //nothing to import
538
        if (importData == null && CollectionUtils.isEmpty(importData)) {
eddie.woo's avatar
eddie.woo committed
539 540
            return OperationResultDto.success();
        }
541

542
        importDataProcess(importData, enterpriseAccountSet.getId(), true);
543

eddie.woo's avatar
eddie.woo committed
544 545
        return OperationResultDto.success();
    }
546

eddie.woo's avatar
eddie.woo committed
547 548 549 550 551 552 553

    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#repeatImportEnterpriseAccountSet(pwc.taxtech.atms.dto.epaccount.EnterpriseAccountSetDto, java.util.List)
     */
    @SuppressWarnings("rawtypes")
    @Transactional
    public OperationResultDto repeatImportEnterpriseAccountSet(EnterpriseAccountSetDto enterpriseAccountSetDto,
554
                                                               List<EnterpriseAccountDto> importData) {
eddie.woo's avatar
eddie.woo committed
555

556
        return importDataProcess(importData, enterpriseAccountSetDto.getId(), enterpriseAccountSetDto.getIsImportAppend());
eddie.woo's avatar
eddie.woo committed
557 558
    }

559

eddie.woo's avatar
eddie.woo committed
560 561 562 563 564
    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#clearRepeatEnterpriseAccountList(pwc.taxtech.atms.dto.epaccount.EnterpriseAccountSetDto)
     */
    @SuppressWarnings("rawtypes")
    public OperationResultDto clearRepeatEnterpriseAccountList(EnterpriseAccountSetDto enterpriseAccountSetDto) {
565

eddie.woo's avatar
eddie.woo committed
566 567
        EnterpriseAccountExample enterpriseAccountExample = new EnterpriseAccountExample();
        enterpriseAccountExample.createCriteria()
568
                .andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetDto.getId());
eddie.woo's avatar
eddie.woo committed
569
        List<EnterpriseAccount> epAccountList = enterpriseAccountMapper.selectByExample(enterpriseAccountExample);
570 571

        if (enterpriseAccountSetDto.getRepeatCodeList() == null && enterpriseAccountSetDto.getRepeatCodeList().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
572 573
            return OperationResultDto.success();
        }
574

eddie.woo's avatar
eddie.woo committed
575
        //删除重复项 留1个
576
        for (String repeatCode : enterpriseAccountSetDto.getRepeatCodeList()) {
eddie.woo's avatar
eddie.woo committed
577 578
            List<EnterpriseAccount> repeatedEpAccountList = epAccountList.stream()
                    .filter(sa -> sa.getCode().equals(repeatCode)).collect(Collectors.toList());
579
            for (int i = 0; i < repeatedEpAccountList.size() - 1; i++) {
580
                enterpriseAccountMapper.deleteByPrimaryKey(repeatedEpAccountList.get(i).getId());
eddie.woo's avatar
eddie.woo committed
581 582
            }
        }
583

584
        enableEnterpriseAccountSet(enterpriseAccountSetDto.getId());
585

eddie.woo's avatar
eddie.woo committed
586 587 588 589 590
        return OperationResultDto.success();
    }

    /**
     * Generate by-level wrapped enterprise Account list
591
     *
eddie.woo's avatar
eddie.woo committed
592 593 594 595 596
     * @param currentEpAccountDto
     * @param epAccountDtoList
     * @return List<EnterpriseAccountDto>
     */
    private List<EnterpriseAccountDto> getWrapList(EnterpriseAccountDto currentEpAccountDto, List<EnterpriseAccountDto> epAccountDtoList) {
597

eddie.woo's avatar
eddie.woo committed
598 599 600 601
        List<EnterpriseAccountDto> result = new ArrayList<>();
        List<EnterpriseAccountDto> subList = epAccountDtoList.stream()
                .filter(epAccountDto -> currentEpAccountDto.getCode().equals(epAccountDto.getParentCode()))
                .collect(Collectors.toList());
602 603 604 605

        if (subList != null && !subList.isEmpty()) {
            for (EnterpriseAccountDto sub : subList) {
                sub.setTreeLevel(currentEpAccountDto.getTreeLevel() + 1);
eddie.woo's avatar
eddie.woo committed
606 607 608 609
                sub.setParentName(currentEpAccountDto.getName());
                sub.setParentFullName(currentEpAccountDto.getFullName());
                result.add(sub);
                List<EnterpriseAccountDto> tempList = getWrapList(sub, epAccountDtoList);
610
                if (tempList != null && !tempList.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
611 612 613 614 615 616
                    result.addAll(tempList);
                }
            }
        }
        return result;
    }
617 618


eddie.woo's avatar
eddie.woo committed
619 620 621
    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#getAccountMappingOrg(java.lang.String)
     */
622
    public List<AccountMappingDto> getAccountMappingOrg(String organizationId) {
eddie.woo's avatar
eddie.woo committed
623 624 625

        AccountMappingExample accountMappingExample = new AccountMappingExample();
        accountMappingExample.createCriteria()
626
                .andOrganizationIdEqualTo(organizationId);
eddie.woo's avatar
eddie.woo committed
627
        List<AccountMapping> accountMappingList = accountMappingMapper.selectByExample(accountMappingExample);
628

eddie.woo's avatar
eddie.woo committed
629 630 631
        List<AccountMappingDto> accountMappingDtoList = new ArrayList<>();
        accountMappingList.stream().forEach(accountMapping -> {
            AccountMappingDto accountMappingDto = new AccountMappingDto();
632 633
            accountMappingDto.setIndustryId(accountMapping.getIndustryId());
            accountMappingDto.setOrganizationId(accountMapping.getOrganizationId());
eddie.woo's avatar
eddie.woo committed
634 635 636 637 638
            accountMappingDtoList.add(accountMappingDto);
        });
        return accountMappingDtoList;
    }

639
    public List<EnterpriseAccountSetDto> getEnterpriseAccountSetListByOrgId(String orgId) {
eddie.woo's avatar
eddie.woo committed
640 641 642 643 644 645 646
        if (StringUtils.isBlank(orgId)) {
            return Collections.emptyList();
        }
        return enterpriseAccountSetMapper.getAccountDtoByOrgId(orgId).stream()
                .map(this::toAccountSetDto).collect(Collectors.toList());
    }

647 648
    public List<EnterpriseAccountDto> getList(String epAccountSetId, String orgId, String filterType) {
        if (StringUtils.isAnyBlank(epAccountSetId, orgId)) {
649 650 651
            return Collections.emptyList();
        }
        Organization organization = organizationMapper.selectByPrimaryKey(orgId);
652 653 654
        Industry industry = industryMapper.selectByPrimaryKey(organization.getIndustryId());
        String industryId = null == industry ? IndustryConstant.GeneralIndustryId : industry.getId();
        List<EnterpriseAccountDto> dtoList = enterpriseAccountMapper.getDto(epAccountSetId, orgId, industryId);
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
//        dtoList = dtoList.stream().map(x -> {
//            if (StringUtils.isBlank(x.getParentCode())) {
//                x.setParentCode(StringUtils.EMPTY);
//            }
//            return x;
//        }).sorted(Comparator.comparing(EnterpriseAccountDto::getParentCode)
//                .thenComparing(EnterpriseAccountDto::getIsActive).reversed()
//                .thenComparing(EnterpriseAccountDto::getCode)).collect(Collectors.toList());
        List<EnterpriseAccountDto> result;
        switch (filterType) {
            //未对应
            case "0":
                result = dtoList.stream().filter(x -> StringUtils.isBlank(x.getStdCode())).collect(Collectors.toList());
                break;
            //已对应
            case "1":
                result = dtoList.stream().filter(x -> StringUtils.isNotBlank(x.getStdCode())).collect(Collectors.toList());
                break;
            //借贷方向不一致
            case "2":
                result = dtoList.stream().filter(x -> StringUtils.isNotBlank(x.getStdCode())
                        && !StringUtils.equalsAny(x.getStdCode(), EnterpriseAccountConstant.StdCode.EMPTY_STD_CODE, EnterpriseAccountConstant.StdCode.NULL_STD_CODE)
                        && x.getDirection() != x.getStdDirection()).collect(Collectors.toList());
                break;
            //科目类型不一致
            case "3":
                result = dtoList.stream().filter(x -> StringUtils.isNotBlank(x.getStdCode())
                        && !StringUtils.equalsAny(x.getStdCode(), EnterpriseAccountConstant.StdCode.EMPTY_STD_CODE, EnterpriseAccountConstant.StdCode.NULL_STD_CODE)
                        && x.getAcctProp() != x.getStdAcctProp()).collect(Collectors.toList());
                break;
            default:
                result = dtoList;
        }
        List<EnterpriseAccountDto> rootList = result.stream().filter(x -> StringUtils.isBlank(x.getParentCode())).map(x -> {
            x.setTreeLevel(0);
            return x;
        }).collect(Collectors.toList());
        List<EnterpriseAccountDto> total = Lists.newArrayList();
        formatEpAccountDtoTree(rootList, result, total);
eddie.woo's avatar
eddie.woo committed
694 695
        return total.stream().collect(Collectors.groupingBy(EnterpriseAccountDto::getCode)).values().stream().map(o -> o.get(0))
                .sorted(Comparator.comparing(EnterpriseAccountDto::getCode)).collect(Collectors.toList());
696 697
    }

eddie.woo's avatar
eddie.woo committed
698 699 700 701 702 703 704 705
    @Transactional
    public OperationResultDto autoMap(String orgId, String accountSetId) {
        //region 基础数据获取
        Optional<EnterpriseAccountSetOrg> optional = epAccountSetOrgDao.getByOrgIdAndAccountSetId(orgId, accountSetId)
                .stream().findFirst();
        Organization org = organizationMapper.selectByPrimaryKey(orgId);
        if (optional.isPresent() && null != org) {
            EnterpriseAccountSetOrg setOrg = optional.get();
706
            String industryId = org.getIndustryId();
eddie.woo's avatar
eddie.woo committed
707 708 709 710 711 712 713 714 715 716 717

            //标准科目准则
            int ruleId = AccountRuleEnum.Rule2007.getValue();

            //获取账套信息便于存储日志
            EnterpriseAccountSet accountSet = new EnterpriseAccountSet();
            //endregion

            //region 获取基础信息

            //获取指定企业账套下的企业科目集合并转化为DTO
718
            List<EnterpriseAccount> epAccountList = enterpriseAccountDao.getByEpAccountSetId(setOrg.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
719 720 721 722 723 724 725 726 727 728 729
            List<EnterpriseAccountDto> accountDtoList = epAccountList.stream().map(x -> {
                return CommonUtils.copyProperties(x, new EnterpriseAccountDto());
            }).collect(Collectors.toList());

            //获取与该机构行业相同的标准科目集合并转化为DTO
            List<StandardAccount> stdAccountList = standardAccountDao.getByIndustryId(industryId).get();
            List<StandardAccountDto> stdAccountDtoList = epAccountList.stream().map(x -> {
                return CommonUtils.copyProperties(x, new StandardAccountDto());
            }).collect(Collectors.toList());

            //获取叶子节点标准科目集合
eddie.woo's avatar
eddie.woo committed
730
            List<StandardAccountDto> stdAccountLeafList = stdAccountDtoList.stream().filter(StandardAccountDto::getIsLeaf).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
            List<AccountMappingManual> allAccountMappingManualList = mappingManualDao.getAll().get();

            accountSet = enterpriseAccountSetMapper.selectByPrimaryKey(accountSetId);
            //endregion

            //region Step 0: 从手动对应库优先获取对应关系
            applyPriorityKeywords(accountDtoList, allAccountMappingManualList, accountSetId, orgId, industryId);
            //endregion

            //region Step 1: 匹配企业科目全称FullName与标准科目FullName完全一致
            //Step 1: Map accounts which name is identical to standard code fullname
            for (StandardAccountDto stdAccount : stdAccountLeafList) {
                Optional<EnterpriseAccountDto> account = accountDtoList.stream().filter(x -> StringUtils.equals(x.getFullName(),
                        stdAccount.getFullName())).findFirst();
                if (account.isPresent() && StringUtils.isNotBlank(account.get().getCode())) {
                    if (account.get().getIsLeaf()) {
747
                        accountMappingDao.mapStdAccountByCode(setOrg.getEnterpriseAccountSetId(), stdAccount.getCode(),
eddie.woo's avatar
eddie.woo committed
748 749 750 751 752 753
                                account.get().getCode(), industryId, orgId, false, 0);
                    } else {
                        List<EnterpriseAccountDto> relatedAccounts = accountDtoList.stream().filter(x -> StringUtils.startsWith(x.getCode()
                                , account.get().getCode())).collect(Collectors.toList());
                        // in case user has already mapped some of the leaf accounts and we do not want to overwrite them, otherwise just loop all and map all.
                        // now use recursion to map one by one...
754
                        mapAllChildrenRecursively(orgId, industryId, setOrg.getEnterpriseAccountSetId(),
eddie.woo's avatar
eddie.woo committed
755 756 757 758 759 760 761
                                account.get().getCode(), stdAccount.getCode(), relatedAccounts, false);
                    }
                }
            }
            //endregion

            //region Step 2: 匹配关键字库AccountMappingKeyword
762 763
            List<EnterpriseAccountDto> accountList = enterpriseAccountDao.getAccountMappingResult(setOrg.getEnterpriseAccountSetId(), ruleId, industryId);
            accountDtoList = getAllActiveAccounts(orgId, industryId, setOrg.getEnterpriseAccountSetId(), false); //rdbDisplayPart.Checked 只显示有期初余额或有凭证的科目
eddie.woo's avatar
eddie.woo committed
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
            for (EnterpriseAccountDto account : accountList) {
                EnterpriseAccountDto crtAccount = account;
                if (accountDtoList.stream().anyMatch(x -> StringUtils.equals(x.getCode(), account.getCode()))) {
                    List<EnterpriseAccountDto> mappingAccounts = accountDtoList.stream()
                            .filter(x -> StringUtils.equals(x.getCode(), account.getCode())).collect(Collectors.toList());
                    //查找C_AccountMappingKeyword中是否有关键字与当前科目的FullName完全匹配
                    for (EnterpriseAccountDto a : mappingAccounts) {
                        Optional<EnterpriseAccountDto> identicalMappedAccount = accountList.stream().filter(x -> StringUtils.equals(x.getCode(), a.getCode()) &&
                                StringUtils.equals(x.getMappingFullName(), a.getFullName())).findFirst();
                        if (identicalMappedAccount.isPresent()) {
                            crtAccount = identicalMappedAccount.get();
                            break;
                        }
                    }

                    if (crtAccount.getIsLeaf()) {
780
                        accountMappingDao.mapStdAccountByCode(setOrg.getEnterpriseAccountSetId(), crtAccount.getStdCode(),
eddie.woo's avatar
eddie.woo committed
781 782 783 784 785 786 787
                                crtAccount.getCode(), industryId, orgId, false, 0);
                    } else {
                        EnterpriseAccountDto finalCrtAccount = crtAccount;
                        List<EnterpriseAccountDto> relatedAccounts = accountDtoList.stream().filter(x -> StringUtils.startsWith(x.getCode(),
                                finalCrtAccount.getCode())).collect(Collectors.toList());
                        // in case user has already mapped some of the leaf accounts and we do not want to overwrite them, otherwise just loop all and map all.
                        // now use recursion to map one by one...
788
                        mapAllChildrenRecursively(orgId, industryId, setOrg.getEnterpriseAccountSetId(), crtAccount.getCode(),
eddie.woo's avatar
eddie.woo committed
789 790 791 792 793 794 795 796
                                crtAccount.getStdCode(), relatedAccounts, false);
                    }
                }
            }
            //endregion

            //region Step 3: Map 2nd or lower level of accounts which can be mapped to "其他"
            //Step 3: Map 2nd or lower level of accounts which can be mapped to "其他"
797
            accountDtoList = getAllActiveAccounts(orgId, industryId, setOrg.getEnterpriseAccountSetId(), false); //rdbDisplayPart.Checked 只显示有期初余额或有凭证的科目
eddie.woo's avatar
eddie.woo committed
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819

            List<EnterpriseAccountDto> accountsUnmappedList = accountDtoList.stream().filter(x -> StringUtils.isBlank(x.getStdCode())
                    && x.getAcctLevel() > 1).collect(Collectors.toList());
            for (EnterpriseAccountDto accountsUnmapped : accountsUnmappedList) {
                String accountsUnmappedParent = accountsUnmapped.getParentCode();
                List<EnterpriseAccountDto> accountsUnmappedBrothers = accountDtoList.stream().filter(x -> StringUtils.equals(x.getParentCode(),
                        accountsUnmappedParent) && StringUtils.isNotBlank(x.getStdCode()) && !StringUtils.equals(x.getStdCode(),
                        CommonConstants.EmptyStdCode) && !StringUtils.equals(x.getStdCode(), CommonConstants.DashSignSeparator))
                        .sorted(Comparator.comparingInt(a -> a.getStdCode().length())).collect(Collectors.toList());
                EnterpriseAccountDto accountsUnmappedBrother;
                if (CollectionUtils.isNotEmpty(accountsUnmappedBrothers)) {
                    accountsUnmappedBrother = accountsUnmappedBrothers.get(0);
                    List<StandardAccountDto> stdAccountss = stdAccountDtoList.stream().filter(x -> StringUtils.equals(x.getCode(),
                            accountsUnmappedBrother.getStdCode())).collect(Collectors.toList());
                    StandardAccountDto stdAccount;
                    if (CollectionUtils.isNotEmpty(stdAccountss)) {
                        stdAccount = stdAccountss.get(0);
                        List<StandardAccountDto> stdAccountOthers = stdAccountLeafList.stream().filter(x -> StringUtils.equals(x.getParentCode(),
                                stdAccount.getParentCode()) && StringUtils.equals(x.getName(), EnterpriseAccountConstant.StrOthers)).collect(Collectors.toList());//其他
                        if (CollectionUtils.isNotEmpty(stdAccountOthers)) {
                            StandardAccountDto stdAccountOther = stdAccountOthers.get(0);
                            if (accountsUnmapped.getIsLeaf()) {
820
                                accountMappingDao.mapStdAccountByCode(setOrg.getEnterpriseAccountSetId(), stdAccountOther.getCode(),
eddie.woo's avatar
eddie.woo committed
821 822 823 824
                                        accountsUnmapped.getCode(), industryId, orgId, false, 0);
                            } else {
                                List<EnterpriseAccountDto> relatedAccounts = accountDtoList.stream().filter(x -> StringUtils.startsWith(x.getCode(),
                                        accountsUnmapped.getCode())).collect(Collectors.toList());
825
                                mapAllChildrenRecursively(orgId, industryId, setOrg.getEnterpriseAccountSetId(),
eddie.woo's avatar
eddie.woo committed
826 827 828 829 830 831 832 833 834 835
                                        accountsUnmapped.getCode(), stdAccountOther.getCode(), relatedAccounts, true);
                            }
                        }
                    }
                }
            }
            //endregion

            //region Step 4: Update the mapping of all parents
            //Step 4: Update the mapping of all parents
836
            accountDtoList = getAllActiveAccounts(orgId, industryId, setOrg.getEnterpriseAccountSetId(), false); //rdbDisplayPart.Checked 只显示有期初余额或有凭证的科目
eddie.woo's avatar
eddie.woo committed
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857

            List<EnterpriseAccountDto> accountParents = accountDtoList.stream().filter(x -> StringUtils.isBlank(x.getStdCode()) &&
                    !x.getIsLeaf()).sorted(Comparator.comparingInt(EnterpriseAccountDto::getAcctLevel).reversed()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(accountParents)) {
                List<EnterpriseAccountDto> accountParentList = accountParents;
                for (EnterpriseAccountDto accountParent : accountParentList) {
                    List<EnterpriseAccountDto> accountParentChildList = accountDtoList.stream().filter(x -> StringUtils
                            .equals(x.getParentCode(), accountParent.getCode())).collect(Collectors.toList());
                    List<EnterpriseAccountDto> accountParentChildMappedList = accountParentChildList.stream().filter(x -> StringUtils
                            .isNotBlank(x.getStdCode())).collect(Collectors.toList());
                    boolean isAllMappedSame = true;
                    //All children accounts are mapped
                    if (accountParentChildList.size() == accountParentChildMappedList.size() && CollectionUtils.isNotEmpty(accountParentChildList)) {
                        String mappedStdCode = accountParentChildList.get(0).getStdCode();
                        for (EnterpriseAccountDto accountParentChild : accountParentChildList) {
                            if (!StringUtils.equalsIgnoreCase(mappedStdCode, accountParentChild.getStdCode())) {
                                isAllMappedSame = false;
                                break;
                            }
                        }
                        if (isAllMappedSame) {
858
                            accountMappingDao.mapStdAccountByCode(setOrg.getEnterpriseAccountSetId(), mappedStdCode, accountParent.getCode(),
eddie.woo's avatar
eddie.woo committed
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
                                    industryId, orgId, false, 0);
                            EnterpriseAccountDto account = accountDtoList.stream().filter(x -> StringUtils.equals(x.getCode(), accountParent.getCode())).findFirst().get();
                            account.setStdCode(mappedStdCode);
                        } else {
                            //if all child accounts map to the same parent stdcode, save the parent stdcode.
                            //otherwise, same "0000" and display "-"
                            List<StandardAccountDto> mappedStdAccounts = stdAccountDtoList.stream().filter(x -> StringUtils.equals(x.getCode(),
                                    mappedStdCode)).collect(Collectors.toList());
                            StandardAccountDto mappedStdAccount = new StandardAccountDto();
                            boolean isAllMappedSameParent = true;
                            if (CollectionUtils.isNotEmpty(mappedStdAccounts)) {
                                mappedStdAccount = mappedStdAccounts.get(0);
                                for (EnterpriseAccountDto accountParentChild : accountParentChildList) {
                                    StandardAccountDto accountParentChildStdAccount = new StandardAccountDto();
                                    List<StandardAccountDto> accountParentChildStdAccounts = stdAccountDtoList.stream().filter(x ->
                                            StringUtils.equals(x.getCode(), accountParentChild.getStdCode())).collect(Collectors.toList());
                                    if (CollectionUtils.isNotEmpty(accountParentChildStdAccounts)) {
                                        accountParentChildStdAccount = accountParentChildStdAccounts.get(0);
                                        if (!StringUtils.equalsIgnoreCase(mappedStdAccount.getParentCode(), accountParentChildStdAccount.getParentCode())) {
                                            isAllMappedSameParent = false;
                                            break;
                                        }
                                    } else {
                                        isAllMappedSameParent = false;
                                    }
                                }
                            } else {
                                isAllMappedSameParent = false;
                            }
                            EnterpriseAccountDto account = accountDtoList.stream().filter(x -> StringUtils.equals(x.getCode(),
                                    accountParent.getCode())).findFirst().get();
                            if (isAllMappedSameParent) {
891
                                accountMappingDao.mapStdAccountByCode(setOrg.getEnterpriseAccountSetId(), mappedStdAccount.getParentCode(),
eddie.woo's avatar
eddie.woo committed
892 893
                                        accountParent.getCode(), industryId, orgId, true, 0);
                            } else {
eddie.woo's avatar
eddie.woo committed
894
                                mapParentAccountResult = Maps.newHashMap();
eddie.woo's avatar
eddie.woo committed
895 896 897 898 899 900 901
                                List<String> codeList = Lists.newArrayList();
                                if (CollectionUtils.isNotEmpty(accountParentChildList)) {
                                    //只需要把子科目加入其中一个就可以了
                                    //否则将会循环多次
                                    codeList.add(accountParentChildList.get(0).getCode());
                                    mapAccountUpdateParent(codeList, accountSetId, industryId, orgId, true);
                                }
902
                                accountMappingDao.mapStdAccountByCode(setOrg.getEnterpriseAccountSetId(), CommonConstants.EmptyStdCode,
eddie.woo's avatar
eddie.woo committed
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
                                        accountParent.getCode(), industryId, orgId, false, 0);
                            }
                        }
                    }
                }
            }
            //endregion

            OperationLogDto operationLogDto = new OperationLogDto();
            operationLogDto.setOperationContent(StringUtils.EMPTY);
            operationLogDto.setAction(OperationAction.New.value());
            operationLogDto.setOperationObject(org.getName() + "-" + accountSet.getName());
            operationLogDto.setOriginalState(StringUtils.EMPTY);
            operationLogDto.setUpdateState(StringUtils.EMPTY);
            operationLogDto.setModule(OperationModule.SubjectCorresponding.value());
            operationLogDto.setComment(StringUtils.EMPTY);
            operationLogDto.setLogType(OperateLogType.OperationLogSubject.value());
            operationLogService.addOperationLog(operationLogDto);

            return OperationResultDto.success();
        } else {
            return OperationResultDto.error(EnterpriseAccountSetOrgMsg.NoOrgSetOrOrgExist);
        }
    }

eddie.woo's avatar
eddie.woo committed
928 929 930
    @Transactional
    public OperationResultDto mapAccount(AccountMapDto accountMapDto) {
        //region 获取相关的机构对象,标准科目对象, 账套对象
931 932
        Organization organization = organizationMapper.selectByPrimaryKey(accountMapDto.getOrgId());
        String industryId;
eddie.woo's avatar
eddie.woo committed
933 934 935
        if (organization == null) {
            return OperationResultDto.error(EnterpriseAccountConstant.OrgNotExist);
        }
936 937 938
        industryId = organization.getIndustryId();
        //通过该机构的行业Id和标准科目的Code获取相关的标准科目对象
        List<StandardAccount> tmpList = standardAccountDao.getByCodeAndIndustryId(accountMapDto.getStandardAccountCode(), industryId);
eddie.woo's avatar
eddie.woo committed
939 940 941 942
        if (CollectionUtils.isEmpty(tmpList)) {
            return OperationResultDto.error(EnterpriseAccountConstant.StdCodeIsNotExist);
        }
        StandardAccount stdAccount = tmpList.get(0);
943 944 945 946 947
        //通过机构的Id获取与之机构关联的账套对象
        //以下通过机构Id获取账套是错误的,因为一个机构存在多个账套,不知道用户选择的是哪个账套
        //var accountSet = this._dbContext.Set<EnterpriseAccountSetOrg>().Where(x => x.OrganizationId == organization.id).FirstOrDefault();
        String accountSetId = accountMapDto.getAccountSetId();
        if (StringUtils.isBlank(accountSetId)) {
eddie.woo's avatar
eddie.woo committed
948 949 950
            return OperationResultDto.error(EnterpriseAccountConstant.AccountSetNotExist);
        }

951
        List<EnterpriseAccount> eaList = enterpriseAccountDao.getByEpAccountSetId(accountSetId);
eddie.woo's avatar
eddie.woo committed
952 953

        //获取账套信息
954
        EnterpriseAccountSet accountSet = enterpriseAccountSetMapper.selectByPrimaryKey(accountSetId);
eddie.woo's avatar
eddie.woo committed
955 956 957 958 959 960 961 962 963 964
        //endregion

        //region 手动对应当前及所有子科目

        for (String eAccountCode : accountMapDto.getEnterpriseAccountCodes()) {
            Optional<EnterpriseAccount> opEpAccount = eaList.stream().filter(x -> StringUtils.equals(x.getCode(), eAccountCode)).findFirst();
            EnterpriseAccount eAccount;
            if (opEpAccount.isPresent()) {
                eAccount = opEpAccount.get();
                //region 获取对应前旧对应关系所所对应的标准科目,为了记录日志
965
                List<AccountMapping> mappingList = accountMappingDao.getAccountMapping(eAccountCode, accountSetId, organization.getId());
eddie.woo's avatar
eddie.woo committed
966 967 968 969 970 971 972 973 974
                AccountMapping mapping;
                String originalCode = null;

                if (CollectionUtils.isNotEmpty(mappingList)) {
                    mapping = mappingList.get(0);
                    originalCode = mapping.getStandardAccountCode();
                }
                //endregion

975 976
                accountMappingDao.mapStdAccountByCode(accountSetId, stdAccount.getCode(), eAccount.getCode(), industryId,
                        organization.getId(), true, 0);
eddie.woo's avatar
eddie.woo committed
977 978 979

                //region 根据新的需求,需要将手动对应的记录记载下来,在下次自动对应的时候需要优先考虑
                AccountMappingManual manual = new AccountMappingManual();
980
                manual.setId(CommonUtils.getUUID());
eddie.woo's avatar
eddie.woo committed
981 982
                manual.setFullName(eAccount.getFullName());
                manual.setStandardCode(stdAccount.getCode());
983 984
                manual.setOrganizationId(organization.getId());
                manual.setEnterpriseAccountSetId(accountSetId);
985
                manual.setUpdateBy(authUserHelper.getCurrentAuditor().get());
eddie.woo's avatar
eddie.woo committed
986 987 988 989 990
                manual.setUpdateTime(new Date());
                addManualMappingRecord(manual);
                //endregion

                //1. 如果将标准科目对应到企业科目的父级,那么该企业科目的子级都对应到该标准科目
eddie.woo's avatar
eddie.woo committed
991
//                updateManualMapChildAccount(eaList, eAccount, stdAccount, accountSetId, industryId, organization.getId());
eddie.woo's avatar
eddie.woo committed
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

                //region 添加日志
                OperationLogDto operationLogDto = new OperationLogDto();
                operationLogDto.setOperationContent(eAccount.getCode() + CommonConstants.DashSignSeparator + eAccount.getName());
                operationLogDto.setAction(OperationAction.ManualMapping.value());
                operationLogDto.setOperationObject(organization.getName() + "-" + accountSet.getName());
                operationLogDto.setOriginalState(StringUtils.isBlank(originalCode) ? StringUtils.EMPTY : originalCode +
                        CommonConstants.DashSignSeparator + stdAccount.getName());
                operationLogDto.setUpdateState(stdAccount.getCode() + CommonConstants.DashSignSeparator + stdAccount.getName());
                operationLogDto.setModule(OperationModule.SubjectCorresponding.value());
                operationLogDto.setComment(StringUtils.EMPTY);
                operationLogDto.setLogType(OperateLogType.OperationLogSubject.value());
                operationLogService.addOperationLog(operationLogDto);
                //endregion
            }
        }
        //endregion

        //region 手动对应当前的所有父级科目
        //清空ParentAccountMapResult
eddie.woo's avatar
eddie.woo committed
1012 1013 1014
//        this.mapParentAccountResult = Maps.newHashMap();
//        mapAccountUpdateParent(Lists.newArrayList(accountMapDto.getEnterpriseAccountCodes()), accountSetId, industryId,
//                organization.getId(), true);
eddie.woo's avatar
eddie.woo committed
1015 1016 1017

        //endregion
        AccountMapDto mapDto = new AccountMapDto();
eddie.woo's avatar
eddie.woo committed
1018
        mapDto.setParentAccountMappingResult(this.mapParentAccountResult); //todo 此处有线程安全问题
eddie.woo's avatar
eddie.woo committed
1019 1020 1021
        return OperationResultDto.success(mapDto);
    }

1022 1023
    public OperationResultDto clearMap(String[] epAccountIds, String orgId) {
        if (epAccountIds != null && StringUtils.isNotBlank(orgId)) {
eddie.woo's avatar
eddie.woo committed
1024 1025 1026 1027 1028
            boolean isToClearAllMapping = false;
            Organization organization = organizationMapper.selectByPrimaryKey(orgId);
            if (organization == null) {
                return OperationResultDto.error(EnterpriseAccountConstant.OrgNotExist);
            }
1029
            String industryId = organization.getIndustryId();
eddie.woo's avatar
eddie.woo committed
1030
            List<EnterpriseAccount> eaAllList = enterpriseAccountDao.getAll();
1031 1032
            List<String> enterpriseAccountIds = Lists.newArrayList(epAccountIds);
            List<EnterpriseAccount> enterpriseAccountList = eaAllList.stream().filter(x -> enterpriseAccountIds.contains(x.getId())).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1033 1034 1035

            if (CollectionUtils.isNotEmpty(enterpriseAccountList)) {
                //获取该账套下有多少企业科目
1036 1037
                String enterprisetAccountSetId = enterpriseAccountList.get(0).getEnterpriseAccountSetId();
                long countOfEnterpriseAccount = eaAllList.stream().filter(x -> StringUtils.equals(x.getEnterpriseAccountSetId(),
eddie.woo's avatar
eddie.woo committed
1038 1039 1040 1041 1042
                        enterprisetAccountSetId)).count();

                if (countOfEnterpriseAccount == enterpriseAccountList.size()) {
                    isToClearAllMapping = true;
                }
1043
                accountMappingDao.clearMapping(enterpriseAccountList, industryId, orgId, isToClearAllMapping);
eddie.woo's avatar
eddie.woo committed
1044 1045 1046 1047
                //如果该账套下的企业科目和传进来需要取消的个数一样,说明是全部取消,没有必须要再去更新父级状态
                if (!isToClearAllMapping) {
                    //清空ParentAccountMapResult
                    this.mapParentAccountResult = Maps.newHashMap();
1048
                    clearParentMapping(eaAllList, enterpriseAccountList, enterprisetAccountSetId, industryId, orgId);
eddie.woo's avatar
eddie.woo committed
1049 1050
                }
                //region 添加日志
1051
                String enterpriseAccountId = enterpriseAccountIds.get(0);
eddie.woo's avatar
eddie.woo committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
                //获取账套信息
                EnterpriseAccountSet accountSet = enterpriseAccountSetMapper.selectByPrimaryKey(enterprisetAccountSetId);
                //记载取消的企业科目
                String clearEACodeList = StringUtils.join(enterpriseAccountList.stream().map(x -> x.getCode())
                        .collect(Collectors.toList()), ",");

                OperationLogDto operationLogDto = new OperationLogDto();
                operationLogDto.setOperationContent(EnterpriseAccountConstant.SubjectCorresponding);
                operationLogDto.setAction(OperationAction.CancelMapping.value());
                operationLogDto.setOperationObject(accountSet != null ? organization.getName() + "-" + accountSet.getName()
                        : organization.getName());
                operationLogDto.setOriginalState(StringUtils.EMPTY);
                operationLogDto.setUpdateState(StringUtils.EMPTY);
                operationLogDto.setModule(OperationModule.SubjectCorresponding.value());
                operationLogDto.setComment(isToClearAllMapping ? StringUtils.EMPTY : clearEACodeList);
                operationLogDto.setLogType(OperateLogType.OperationLogSubject.value());
                operationLogService.addOperationLog(operationLogDto);
                //endregion

                AccountMapDto mapDto = new AccountMapDto();
                mapDto.setParentAccountMappingResult(this.mapParentAccountResult);
                return OperationResultDto.success(mapDto);
            }
        }
        return OperationResultDto.error(EnterpriseAccountConstant.NoAccountNeedClear);
    }

    private void clearParentMapping(List<EnterpriseAccount> eaAllList, List<EnterpriseAccount> eaClearList,
1080
                                    String enterpriseAccountSetId, String industryId, String orgId) {
eddie.woo's avatar
eddie.woo committed
1081 1082
        for (EnterpriseAccount ea : eaClearList) {
            Optional<EnterpriseAccount> eaParentOp = eaAllList.stream().filter(x -> StringUtils.equals(x.getCode(),
1083
                    ea.getParentCode()) && StringUtils.equals(x.getEnterpriseAccountSetId(), enterpriseAccountSetId)).findFirst();
eddie.woo's avatar
eddie.woo committed
1084 1085 1086
            if (eaParentOp.isPresent()) {
                EnterpriseAccount eaParent = eaParentOp.get();
                //删除科目对应表里面的对应关系
1087
                accountMappingDao.delMapping(eaParent.getCode(), enterpriseAccountSetId, orgId, industryId);
eddie.woo's avatar
eddie.woo committed
1088 1089 1090
                //添加到list中为了更新UI界面
                addMapParentAccountResult(eaParent.getCode(), Lists.newArrayList(null, StringUtils.EMPTY));
                //删除父级以及更高层的对应关系
1091
                clearParentMappingRecursion(eaAllList, eaParent, enterpriseAccountSetId, industryId, orgId);
eddie.woo's avatar
eddie.woo committed
1092 1093 1094 1095 1096
            }
        }
    }

    private void clearParentMappingRecursion(List<EnterpriseAccount> eaAllList, EnterpriseAccount eaParent,
1097
                                             String enterpriseAccountSetId, String industryId, String orgId) {
eddie.woo's avatar
eddie.woo committed
1098 1099
        if (StringUtils.isNotBlank(eaParent.getParentCode())) {
            Optional<EnterpriseAccount> parentAccountOp = eaAllList.stream().filter(x -> StringUtils.equals(x.getCode(),
1100
                    eaParent.getParentCode()) && StringUtils.equals(x.getEnterpriseAccountSetId(), enterpriseAccountSetId)).findFirst();
eddie.woo's avatar
eddie.woo committed
1101 1102 1103
            if (parentAccountOp.isPresent()) {
                EnterpriseAccount parentAccount = parentAccountOp.get();
                //删除科目对应表里面的对应关系
1104
                accountMappingDao.delMapping(parentAccount.getCode(), enterpriseAccountSetId, orgId, industryId);
eddie.woo's avatar
eddie.woo committed
1105 1106
                //添加到list中为了更新UI界面
                addMapParentAccountResult(parentAccount.getCode(), Lists.newArrayList(null, StringUtils.EMPTY));
1107
                clearParentMappingRecursion(eaAllList, parentAccount, enterpriseAccountSetId, industryId, orgId);
eddie.woo's avatar
eddie.woo committed
1108 1109 1110 1111 1112
            }
        }
    }

    private void updateManualMapChildAccount(List<EnterpriseAccount> eaList, EnterpriseAccount eAccountCode, StandardAccount stdAccount,
1113
                                             String accountSetId, String industryId, String orgId) {
eddie.woo's avatar
eddie.woo committed
1114 1115 1116 1117
        List<EnterpriseAccount> eAccount = eaList.stream().filter(x -> StringUtils.equals(x.getParentCode(), eAccountCode.getCode()))
                .collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(eAccount)) {
            for (EnterpriseAccount ea : eAccount) {
1118
                accountMappingDao.mapStdAccountByCode(accountSetId, stdAccount.getCode(), ea.getCode(), industryId, orgId,
eddie.woo's avatar
eddie.woo committed
1119 1120 1121
                        true, 0);
                //region 根据新的需求,需要将手动对应的记录记载下来,在下次自动对应的时候需要优先考虑
                AccountMappingManual manual = new AccountMappingManual();
1122
                manual.setId(CommonUtils.getUUID());
eddie.woo's avatar
eddie.woo committed
1123 1124
                manual.setFullName(ea.getFullName());
                manual.setStandardCode(stdAccount.getCode());
1125 1126 1127
                manual.setOrganizationId(orgId);
                manual.setEnterpriseAccountSetId(accountSetId);
                manual.setIndustryId(industryId);
1128
                manual.setUpdateBy(authUserHelper.getCurrentAuditor().get());
eddie.woo's avatar
eddie.woo committed
1129 1130 1131
                manual.setUpdateTime(new Date());
                addManualMappingRecord(manual);
                //endregion
1132
                updateManualMapChildAccount(eaList, ea, stdAccount, accountSetId, industryId, orgId);
eddie.woo's avatar
eddie.woo committed
1133 1134 1135 1136
            }
        }
    }

1137
    public void addManualMappingRecord(AccountMappingManual manualMapping) {
1138 1139
        mappingManualDao.delMapping(manualMapping.getFullName(), manualMapping.getEnterpriseAccountSetId(),
                manualMapping.getOrganizationId(), manualMapping.getIndustryId());
eddie.woo's avatar
eddie.woo committed
1140 1141 1142
        mappingManualMapper.insertSelective(manualMapping);
    }

1143 1144
    public List<EnterpriseAccountDto> getAllActiveAccounts(String orgId, String industryId, String accountSetId, Boolean isActive) {
        List<Map<String, Object>> list = enterpriseAccountDao.selectAccounts(industryId, accountSetId, orgId, EnterpriseAccountConstant.InvalidId,
eddie.woo's avatar
eddie.woo committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
                EnterpriseAccountConstant.InvalidId, EnterpriseAccountConstant.InvalidId, isActive);

        return list.stream().map(x -> {
            EnterpriseAccountDto dto = new EnterpriseAccountDto();
            dto.setCode(MapUtils.getString(x, "Code"));
            dto.setName(MapUtils.getString(x, "Name"));
            dto.setFullName(MapUtils.getString(x, "FullName"));
            dto.setParentCode(MapUtils.getString(x, "ParentCode"));
            dto.setAcctLevel(MapUtils.getInteger(x, "AcctLevel"));
            dto.setStdCode(MapUtils.getString(x, "StdCode"));
            dto.setIsLeaf(MapUtils.getShort(x, "IsLeaf") == EnterpriseAccountConstant.I_Yes);
            return dto;
        }).collect(Collectors.toList());
    }

1160
    private Boolean mapAllChildrenRecursively(String orgId, String industryId, String accountSetId, String accountCode,
eddie.woo's avatar
eddie.woo committed
1161 1162 1163 1164 1165 1166 1167 1168 1169
                                              String stdAccountCode, List<EnterpriseAccountDto> accounts, Boolean exceptionFlag) {
        List<String> enterpriseCodeList = Lists.newArrayList();
        boolean allChildrenMapped = true;
        List<EnterpriseAccountDto> children = accounts.stream().filter(x -> StringUtils.equals(x.getParentCode(), accountCode))
                .collect(Collectors.toList());

        for (EnterpriseAccountDto child : children) {
            if (child.getIsLeaf()) {
                if (StringUtils.isBlank(child.getStdCode())) {
1170
                    accountMappingDao.mapStdAccountByCode(accountSetId, stdAccountCode, child.getCode(), industryId, orgId, false, 0);
eddie.woo's avatar
eddie.woo committed
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
                } else {
                    if (!StringUtils.equals(child.getStdCode(), stdAccountCode)) {
                        allChildrenMapped = false;

                        if (exceptionFlag) {
                            //只需要添加一次即可
                            enterpriseCodeList.add(child.getCode());
                        }
                    }
                }
            } else {
1182
                allChildrenMapped = mapAllChildrenRecursively(orgId, industryId, accountSetId, child.getCode(),
eddie.woo's avatar
eddie.woo committed
1183 1184 1185 1186 1187 1188
                        stdAccountCode, accounts, false);
            }
        }

        //子科目全部对应时,父科目显示对应:1.子科目对应一致-子科目对应的标准科目;2.子科目对应不一致-0000
        if (allChildrenMapped) {
1189
            accountMappingDao.mapStdAccountByCode(accountSetId, stdAccountCode, accountCode, industryId, orgId, false, 0);
eddie.woo's avatar
eddie.woo committed
1190
        } else {
1191
            accountMappingDao.mapStdAccountByCode(accountSetId, CommonConstants.EmptyStdCode, accountCode, industryId, orgId, false, 0);
eddie.woo's avatar
eddie.woo committed
1192 1193 1194
        }

        if (exceptionFlag) {
eddie.woo's avatar
eddie.woo committed
1195
            this.mapParentAccountResult = Maps.newHashMap();
1196
            mapAccountUpdateParent(enterpriseCodeList, accountSetId, industryId, orgId, false);
eddie.woo's avatar
eddie.woo committed
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
        }

        //Update the mapping of parent account
        //var row = grdTarget.Rows.OfType<DataGridViewRow>()
        //    .Where(r => r.Cells["AccountCode"].Value.ToString().Trim() == accountCode).FirstOrDefault();
        //if (row != null)
        //{
        //    UpdateParentAccounts(row.Index, accountCode, false);
        //}

        return allChildrenMapped;
    }

    private void applyPriorityKeywords(List<EnterpriseAccountDto> allEpAccountDtoList, List<AccountMappingManual> allManualList,
1211
                                       String accountSetId, String orgId, String industryId) {
eddie.woo's avatar
eddie.woo committed
1212 1213
        List<AccountMappingManualDto> resultList;
        //1 账套机构行业都一样 (本身优先级别最高)
1214 1215
        List<AccountMappingManual> tmpManualList = allManualList.stream().filter(x -> StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && StringUtils.equals(x.getOrganizationId(), orgId) && StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1216 1217 1218
        resultList = wrapPriority(tmpManualList, 1);

        //2 账套行业一样,机构不一样
1219 1220
        tmpManualList = allManualList.stream().filter(x -> StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && !StringUtils.equals(x.getOrganizationId(), orgId) && StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1221 1222 1223
        resultList = getManualMappingResult(resultList, wrapPriority(tmpManualList, 2));

        //3 账套不一样,机构和行业都一样
1224 1225
        tmpManualList = allManualList.stream().filter(x -> !StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && StringUtils.equals(x.getOrganizationId(), orgId) && StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1226 1227 1228
        resultList = getManualMappingResult(resultList, wrapPriority(tmpManualList, 3));

        //4 账套机构一样,行业不一样
1229 1230
        tmpManualList = allManualList.stream().filter(x -> StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && StringUtils.equals(x.getOrganizationId(), orgId) && !StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1231 1232 1233
        resultList = getManualMappingResult(resultList, wrapPriority(tmpManualList, 4));

        //5 机构一样,账套行业不一样
1234 1235
        tmpManualList = allManualList.stream().filter(x -> !StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && StringUtils.equals(x.getOrganizationId(), orgId) && !StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1236 1237 1238
        resultList = getManualMappingResult(resultList, wrapPriority(tmpManualList, 5));

        //6 账套机构不一样,行业一样
1239 1240
        tmpManualList = allManualList.stream().filter(x -> !StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && !StringUtils.equals(x.getOrganizationId(), orgId) && StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1241 1242 1243
        resultList = getManualMappingResult(resultList, wrapPriority(tmpManualList, 6));

        //7 账套一样,机构行业都不一样
1244 1245
        tmpManualList = allManualList.stream().filter(x -> StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && !StringUtils.equals(x.getOrganizationId(), orgId) && !StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1246 1247 1248
        resultList = getManualMappingResult(resultList, wrapPriority(tmpManualList, 7));

        //8 账套机构行业都不一样
1249 1250
        tmpManualList = allManualList.stream().filter(x -> !StringUtils.equals(x.getEnterpriseAccountSetId(), accountSetId)
                && !StringUtils.equals(x.getOrganizationId(), orgId) && !StringUtils.equals(x.getIndustryId(), industryId)).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
1251 1252 1253
        resultList = getManualMappingResult(resultList, wrapPriority(tmpManualList, 8));

        List<AccountMapping> mappingList = Lists.newArrayList();
1254 1255 1256
        resultList.stream().forEach(x -> {
            allEpAccountDtoList.stream().filter(EnterpriseAccountDto::getIsLeaf).forEach(y -> {
                if (StringUtils.equals(x.getFullName(), y.getFullName())) {
eddie.woo's avatar
eddie.woo committed
1257
                    AccountMapping tmp = new AccountMapping();
1258
                    tmp.setId(CommonUtils.getUUID());
eddie.woo's avatar
eddie.woo committed
1259 1260
                    tmp.setEnterpriseAccountCode(y.getCode());
                    tmp.setStandardAccountCode(x.getStandardCode());
1261 1262
                    tmp.setOrganizationId(orgId);
                    tmp.setIndustryId(industryId);
eddie.woo's avatar
eddie.woo committed
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
                    mappingList.add(tmp);
                }
            });
        });

        //先删除
        List<AccountMapping> filterMappingResult = mappingList.stream().filter(x -> StringUtils.isNotBlank(x.getEnterpriseAccountCode()))
                .collect(Collectors.toList());
        List<String> filterEACodeList = filterMappingResult.stream().map(AccountMapping::getEnterpriseAccountCode).collect(Collectors.toList());

        accountMappingDao.delByEpAccountCodeList(filterEACodeList);

        filterMappingResult.stream().forEach(x -> accountMappingMapper.insertSelective(x));

    }

    private List<AccountMappingManualDto> getManualMappingResult(List<AccountMappingManualDto> priorityList,
                                                                 List<AccountMappingManualDto> lowerPriorityList) {
        List<AccountMappingManualDto> originalMapList = new ArrayList<>(priorityList);

        List<String> list1 = priorityList.stream().map(AccountMappingManualDto::getFullName).collect(Collectors.toList());
        List<String> list2 = lowerPriorityList.stream().map(AccountMappingManualDto::getFullName).collect(Collectors.toList());
        List<String> intersectedList = list1.stream().filter(list2::contains).collect(Collectors.toList());
        List<AccountMappingManualDto> addedList = lowerPriorityList.stream().filter(x -> list2.stream()
                .filter(y -> !intersectedList.contains(y)).collect(Collectors.toList()).contains(x.getFullName()))
                .collect(Collectors.toList());

        originalMapList.addAll(addedList);

        return originalMapList;
    }

    private List<AccountMappingManualDto> wrapPriority(List<AccountMappingManual> manualList, int priority) {
        return manualList.stream().collect(Collectors.groupingBy(AccountMappingManual::getFullName))
                .entrySet().stream().map(x -> {
                    AccountMappingManualDto dto = new AccountMappingManualDto();
                    AccountMappingManual manual = x.getValue().stream().sorted((m1, m2) -> m2.getUpdateTime()
                            .compareTo(m1.getUpdateTime())).findFirst().get();
                    CommonUtils.copyProperties(manual, dto);
                    dto.setPriority(priority);
                    return dto;
                }).collect(Collectors.toList());
    }

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
    private void formatEpAccountDtoTree(List<EnterpriseAccountDto> rootList, List<EnterpriseAccountDto> allList,
                                        List<EnterpriseAccountDto> result) {
        if (CollectionUtils.isEmpty(rootList)) {
            return;
        }
        int level = rootList.get(0).getTreeLevel() + 1;
        rootList.forEach(item -> {
            result.add(item);
            List<EnterpriseAccountDto> subList = allList.stream().filter(x -> StringUtils.equals(x.getParentCode(), item.getCode()))
                    .map(x -> {
                        x.setTreeLevel(level);
                        x.setParentName(item.getName());
                        x.setParentFullName(item.getFullName());
                        return x;
                    }).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(subList)) {
                result.addAll(subList);
                formatEpAccountDtoTree(subList, allList, result);
            }
        });
    }

eddie.woo's avatar
eddie.woo committed
1329 1330 1331 1332 1333
    private EnterpriseAccountSetDto toAccountSetDto(EnterpriseAccountSet accountSet) {
        EnterpriseAccountSetDto dto = new EnterpriseAccountSetDto();
        return CommonUtils.copyProperties(accountSet, dto);
    }

eddie.woo's avatar
eddie.woo committed
1334 1335
    /**
     * Validates the enterprise account list.
1336
     *
eddie.woo's avatar
eddie.woo committed
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
     * @param epAccountList
     * @return The validate list
     */
    private List<ValidateInfoDto> validateEnterpriseAccountList(List<EnterpriseAccountDto> epAccountList) {
        List<ValidateInfoDto> validateInfoDtolist = new ArrayList<>();
        validateInfoDtolist.add(this.getRepeatValidate(epAccountList));
        validateInfoDtolist.add(this.getEmptyNameValidate(epAccountList));
        validateInfoDtolist.add(this.getDirectionValidate(epAccountList));
        validateInfoDtolist.add(this.getAcctPropNullValidate(epAccountList));
        validateInfoDtolist.add(this.getAcctPropValidate(epAccountList));
        validateInfoDtolist.add(this.getNoParentValidate(epAccountList));
1348

eddie.woo's avatar
eddie.woo committed
1349
        return validateInfoDtolist.stream()
1350
                .filter(validateInfo -> validateInfo.getInValidateCodeList() != null && !validateInfo.getInValidateCodeList().isEmpty())
eddie.woo's avatar
eddie.woo committed
1351
                .collect(Collectors.toList());
1352

eddie.woo's avatar
eddie.woo committed
1353
    }
1354

eddie.woo's avatar
eddie.woo committed
1355 1356
    /**
     * Validates if there is any duplication account code in the list
1357
     *
eddie.woo's avatar
eddie.woo committed
1358
     * @param epAccountList
eddie.woo's avatar
eddie.woo committed
1359 1360 1361
     * @return ValidateInfoDto
     */
    private ValidateInfoDto getRepeatValidate(List<EnterpriseAccountDto> epAccountList) {
1362

eddie.woo's avatar
eddie.woo committed
1363 1364
        ValidateInfoDto validateInfoDto = new ValidateInfoDto();
        validateInfoDto.setType(EnterpriseAccountMessage.EnterpriceAccountRepeat);
1365

eddie.woo's avatar
eddie.woo committed
1366 1367
        List<String> distinctCodeList = epAccountList.stream()
                .map(epAccount -> epAccount.getCode()).distinct().collect(Collectors.toList());
1368 1369

        for (String code : distinctCodeList) {
eddie.woo's avatar
eddie.woo committed
1370 1371
            List<EnterpriseAccountDto> accountsWithSameCode = epAccountList.stream()
                    .filter(epAccount -> code.equals(epAccount.getCode())).collect(Collectors.toList());
1372
            if (accountsWithSameCode != null && accountsWithSameCode.size() > 1) {
eddie.woo's avatar
eddie.woo committed
1373 1374 1375 1376 1377
                validateInfoDto.addInValidateCode(code);
            }
        }
        return validateInfoDto;
    }
1378

eddie.woo's avatar
eddie.woo committed
1379
    /**
1380 1381
     * Validates if there is any account with wrong direction value
     *
eddie.woo's avatar
eddie.woo committed
1382 1383 1384 1385
     * @param epAccountList
     * @return ValidateInfoDto
     */
    private ValidateInfoDto getDirectionValidate(List<EnterpriseAccountDto> epAccountList) {
1386

eddie.woo's avatar
eddie.woo committed
1387 1388
        ValidateInfoDto validateInfoDto = new ValidateInfoDto();
        validateInfoDto.setType(EnterpriseAccountMessage.DirectionFormatError);
1389

eddie.woo's avatar
eddie.woo committed
1390
        List<String> inValidateCodeList = epAccountList.stream()
1391 1392
                .filter(epAccount ->
                        !CommonConstants.CreditDirectionValue.equals(epAccount.getDirection()) && !CommonConstants.DebitDirectionValue.equals(epAccount.getDirection()))
eddie.woo's avatar
eddie.woo committed
1393 1394 1395
                .map(epAccount -> epAccount.getCode())
                .distinct().collect(Collectors.toList());
        validateInfoDto.setInValidateCodeList(inValidateCodeList);
1396

eddie.woo's avatar
eddie.woo committed
1397 1398
        return validateInfoDto;
    }
1399

eddie.woo's avatar
eddie.woo committed
1400 1401
    /**
     * Validates if there is any account with wrong accprop value
1402
     *
eddie.woo's avatar
eddie.woo committed
1403 1404 1405 1406
     * @param epAccountList
     * @return ValidateInfoDto
     */
    private ValidateInfoDto getAcctPropValidate(List<EnterpriseAccountDto> epAccountList) {
1407

eddie.woo's avatar
eddie.woo committed
1408 1409
        ValidateInfoDto validateInfoDto = new ValidateInfoDto();
        validateInfoDto.setType(EnterpriseAccountMessage.AcctPropFormatError);
1410

eddie.woo's avatar
eddie.woo committed
1411
        List<String> inValidateCodeList = epAccountList.stream()
1412 1413
                .filter(epAccount ->
                        epAccount.getAcctProp() != null && (epAccount.getAcctProp() > EnterpriseAccountConstant.MaxAcctPropValue || (epAccount.getAcctProp() < EnterpriseAccountConstant.MinAcctPropValue && epAccount.getAcctProp() != EnterpriseAccountConstant.SpecialAcctPropValue)))
eddie.woo's avatar
eddie.woo committed
1414 1415 1416
                .map(epAccount -> epAccount.getCode())
                .distinct().collect(Collectors.toList());
        validateInfoDto.setInValidateCodeList(inValidateCodeList);
1417

eddie.woo's avatar
eddie.woo committed
1418 1419
        return validateInfoDto;
    }
1420

eddie.woo's avatar
eddie.woo committed
1421 1422
    /**
     * Validates if there is any account with null accprop value
1423
     *
eddie.woo's avatar
eddie.woo committed
1424 1425 1426 1427
     * @param epAccountList
     * @return ValidateInfoDto
     */
    private ValidateInfoDto getAcctPropNullValidate(List<EnterpriseAccountDto> epAccountList) {
1428

eddie.woo's avatar
eddie.woo committed
1429 1430
        ValidateInfoDto validateInfoDto = new ValidateInfoDto();
        validateInfoDto.setType(EnterpriseAccountMessage.AcctPropNullError);
1431

eddie.woo's avatar
eddie.woo committed
1432
        List<String> inValidateCodeList = epAccountList.stream()
1433 1434
                .filter(epAccount ->
                        epAccount.getAcctProp() == null)
eddie.woo's avatar
eddie.woo committed
1435 1436 1437
                .map(epAccount -> epAccount.getCode())
                .distinct().collect(Collectors.toList());
        validateInfoDto.setInValidateCodeList(inValidateCodeList);
1438

eddie.woo's avatar
eddie.woo committed
1439 1440
        return validateInfoDto;
    }
1441

eddie.woo's avatar
eddie.woo committed
1442 1443
    /**
     * Validates if there is any account with empty name
1444
     *
eddie.woo's avatar
eddie.woo committed
1445 1446 1447 1448
     * @param epAccountList
     * @return ValidateInfoDto
     */
    private ValidateInfoDto getEmptyNameValidate(List<EnterpriseAccountDto> epAccountList) {
1449

eddie.woo's avatar
eddie.woo committed
1450 1451
        ValidateInfoDto validateInfoDto = new ValidateInfoDto();
        validateInfoDto.setType(EnterpriseAccountMessage.EnterpriseAccountNameEmpty);
1452

eddie.woo's avatar
eddie.woo committed
1453 1454 1455 1456 1457
        List<String> inValidateCodeList = epAccountList.stream()
                .filter(epAccount -> epAccount.getName() == null || epAccount.getName().equals(""))
                .map(epAccount -> epAccount.getCode())
                .distinct().collect(Collectors.toList());
        validateInfoDto.setInValidateCodeList(inValidateCodeList);
1458

eddie.woo's avatar
eddie.woo committed
1459 1460
        return validateInfoDto;
    }
1461

eddie.woo's avatar
eddie.woo committed
1462 1463
    /**
     * Validates if there is any account with empty name
1464
     *
eddie.woo's avatar
eddie.woo committed
1465 1466 1467 1468
     * @param epAccountList
     * @return ValidateInfoDto
     */
    private ValidateInfoDto getNoParentValidate(List<EnterpriseAccountDto> epAccountList) {
1469

eddie.woo's avatar
eddie.woo committed
1470 1471
        ValidateInfoDto validateInfoDto = new ValidateInfoDto();
        validateInfoDto.setType(EnterpriseAccountMessage.NoParentCode);
1472 1473

        List<EnterpriseAccountDto> accountsWithParent = epAccountList.stream().filter(epAccount -> epAccount.getParentCode() != null && !epAccount.getParentCode().equals(""))
eddie.woo's avatar
eddie.woo committed
1474
                .collect(Collectors.toList());
1475 1476

        for (EnterpriseAccountDto accountWithParent : accountsWithParent) {
eddie.woo's avatar
eddie.woo committed
1477
            boolean parentExist = epAccountList.stream()
1478 1479
                    .anyMatch(epAccount -> epAccount.getCode().equals(accountWithParent.getParentCode()));
            if (!parentExist) {
eddie.woo's avatar
eddie.woo committed
1480 1481 1482 1483
                validateInfoDto.addInValidateCode(accountWithParent.getCode());
            }
        }
        return validateInfoDto;
1484

eddie.woo's avatar
eddie.woo committed
1485
    }
1486 1487


eddie.woo's avatar
eddie.woo committed
1488 1489
    /**
     * Gets the same enterprise account list.
1490
     *
eddie.woo's avatar
eddie.woo committed
1491 1492 1493
     * @param enterpriseAccountDto
     * @return
     */
1494 1495
    private List<EnterpriseAccountDto> getSameEnterpriseAccountList(EnterpriseAccountDto enterpriseAccountDto) {

eddie.woo's avatar
eddie.woo committed
1496 1497 1498
        if (enterpriseAccountDto == null) {
            return null;
        }
1499

eddie.woo's avatar
eddie.woo committed
1500 1501
        EnterpriseAccountExample enterpriseAccountExample = new EnterpriseAccountExample();
        EnterpriseAccountExample.Criteria criteria = enterpriseAccountExample.createCriteria();
1502
        if (enterpriseAccountDto.getId() != null && !enterpriseAccountDto.getId().isEmpty()) {
1503
            criteria.andIdNotEqualTo(enterpriseAccountDto.getId());
eddie.woo's avatar
eddie.woo committed
1504
        }
1505
        criteria.andEnterpriseAccountSetIdEqualTo(enterpriseAccountDto.getEnterpriseAccountSetId())
1506 1507
                .andCodeEqualTo(enterpriseAccountDto.getCode())
                .andIsActiveEqualTo(CommonConstants.ACTIVE_STATUS);
eddie.woo's avatar
eddie.woo committed
1508 1509
        List<EnterpriseAccount> epAccountsWithSameCode = enterpriseAccountMapper.selectByExample(enterpriseAccountExample);
        //没有重复项
1510
        if (epAccountsWithSameCode == null || epAccountsWithSameCode.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1511 1512
            return null;
        }
1513

eddie.woo's avatar
eddie.woo committed
1514 1515
        //有重复项
        List<EnterpriseAccountDto> sameEnterpriseAccountDtoList = new ArrayList<>();
1516
        for (EnterpriseAccount enterpriseAccount : epAccountsWithSameCode) {
eddie.woo's avatar
eddie.woo committed
1517 1518
            enterpriseAccountExample = new EnterpriseAccountExample();
            criteria = enterpriseAccountExample.createCriteria();
1519
            if (enterpriseAccount.getParentCode() != null && !enterpriseAccount.getParentCode().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1520 1521
                criteria.andCodeEqualTo(enterpriseAccount.getParentCode());
            }
1522 1523
            criteria.andRuleTypeEqualTo(2)
                    .andIsActiveEqualTo(CommonConstants.ACTIVE_STATUS);
eddie.woo's avatar
eddie.woo committed
1524
            List<EnterpriseAccount> epAccountsParent = enterpriseAccountMapper.selectByExample(enterpriseAccountExample);
1525
            if (epAccountsParent != null && !epAccountsParent.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1526 1527 1528 1529 1530 1531 1532 1533
                epAccountsParent.stream().forEach(epAccountParent -> {
                    EnterpriseAccountDto epAccountDto = new EnterpriseAccountDto();
                    CommonUtils.copyProperties(enterpriseAccount, epAccountDto);
                    epAccountDto.setParentName(epAccountParent.getName());
                    epAccountDto.setParentFullName(epAccountParent.getFullName());
                    epAccountDto.setSubStdAccounts(new ArrayList<>());
                    sameEnterpriseAccountDtoList.add(epAccountDto);
                });
1534
            } else {
eddie.woo's avatar
eddie.woo committed
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
                EnterpriseAccountDto epAccountDto = new EnterpriseAccountDto();
                CommonUtils.copyProperties(enterpriseAccount, epAccountDto);
                epAccountDto.setParentName("");
                epAccountDto.setParentFullName("");
                epAccountDto.setSubStdAccounts(new ArrayList<>());
                sameEnterpriseAccountDtoList.add(epAccountDto);
            }
        }
        return sameEnterpriseAccountDtoList;
    }
1545

eddie.woo's avatar
eddie.woo committed
1546 1547
    /**
     * Sets the parent is not leaf.
1548 1549
     *
     * @param parentCode             - The parent code
1550
     * @param enterpriseAccountSetId - The enterprise account set identifier
eddie.woo's avatar
eddie.woo committed
1551
     */
1552
    private void setParentIsNotLeaf(String parentCode, String enterpriseAccountSetId) {
1553

eddie.woo's avatar
eddie.woo committed
1554
        // no parent, do nothing
1555
        if (parentCode == null || parentCode.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1556 1557
            return;
        }
1558

eddie.woo's avatar
eddie.woo committed
1559
        EnterpriseAccountExample example = new EnterpriseAccountExample();
1560
        example.createCriteria().andCodeEqualTo(parentCode).andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId);
eddie.woo's avatar
eddie.woo committed
1561
        List<EnterpriseAccount> parentNodes = enterpriseAccountMapper.selectByExample(example);
1562
        if (parentNodes == null || parentNodes.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1563 1564 1565
            return;
        }
        EnterpriseAccount parentNode = parentNodes.get(0);
1566
        if (parentNode != null && parentNode.getIsLeaf().equals(CommonConstants.IsLeaf)) {
eddie.woo's avatar
eddie.woo committed
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
            //save enterpriseAccount
            EnterpriseAccount parentNodeOriginal = new EnterpriseAccount();
            CommonUtils.copyProperties(parentNode, parentNodeOriginal);
            parentNode.setIsLeaf(CommonConstants.IsNotLeaf);
            enterpriseAccountMapper.updateByPrimaryKey(parentNode);
            //save operational log
            UpdateLogParams updateLogParams = new UpdateLogParams();
            updateLogParams.setOriginalState(parentNodeOriginal);
            updateLogParams.setUpdateState(parentNode);
            updateLogParams.setOperationModule(OperationModule.BasicDataEnterpriceAccount.value());
1577
            updateLogParams.setOperationUser(authUserHelper.getCurrentAuditor().get());
eddie.woo's avatar
eddie.woo committed
1578 1579 1580 1581 1582 1583 1584 1585
            updateLogParams.setComment(LogMessage.EnterpriceAccountImportUpdate);
            updateLogParams.setOperationObject(parentNodeOriginal.getName());
            updateLogParams.setOperationContent("operation content");
            updateLogParams.setOperateLogType(OperateLogType.OperationLogEnterPrise.value());
            updateLogParams.setOperationAction(OperationAction.Update.value());
            operationLogService.updateDataAddLog(updateLogParams);
        }
    }
1586

eddie.woo's avatar
eddie.woo committed
1587 1588
    /**
     * Sets the parent leaf.
1589 1590
     *
     * @param parentCode             - The parentcode
1591
     * @param enterpriseAccountSetId
1592
     * @param currentEpAccountId     - Current enterprise account id
eddie.woo's avatar
eddie.woo committed
1593
     */
1594
    private void setParentLeaf(String parentCode, String enterpriseAccountSetId, String currentEpAccountId) {
eddie.woo's avatar
eddie.woo committed
1595
        // no parent, do nothing
1596
        if (parentCode == null || parentCode.isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1597 1598
            return;
        }
1599

1600
        EnterpriseAccount parentNodeEntity = getEnterpriseAccount(parentCode, enterpriseAccountSetId);
1601
        if (parentNodeEntity == null) {
eddie.woo's avatar
eddie.woo committed
1602 1603
            return;
        }
1604

eddie.woo's avatar
eddie.woo committed
1605 1606 1607
        //copy parentNodeEntity
        EnterpriseAccount parentNodeOriginal = new EnterpriseAccount();
        CommonUtils.copyProperties(parentNodeEntity, parentNodeOriginal);
1608

eddie.woo's avatar
eddie.woo committed
1609 1610 1611
        //get other children nodes of this parent
        EnterpriseAccountExample example = new EnterpriseAccountExample();
        example.createCriteria()
1612 1613 1614
                .andParentCodeEqualTo(parentNodeEntity.getCode())
                .andIdNotEqualTo(currentEpAccountId)
                .andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId);
eddie.woo's avatar
eddie.woo committed
1615
        List<EnterpriseAccount> childrenAccountsOfparentNode = enterpriseAccountMapper.selectByExample(example);
1616
        if (CollectionUtils.isEmpty(childrenAccountsOfparentNode)) {
eddie.woo's avatar
eddie.woo committed
1617 1618 1619
            // no sub node list, set is the leaf node
            parentNodeEntity.setIsLeaf(CommonConstants.IsLeaf);
            enterpriseAccountMapper.updateByPrimaryKey(parentNodeEntity);
1620

eddie.woo's avatar
eddie.woo committed
1621 1622 1623 1624 1625
            //operation log
            UpdateLogParams updateLogParams = new UpdateLogParams();
            updateLogParams.setOriginalState(parentNodeOriginal);
            updateLogParams.setUpdateState(parentNodeEntity);
            updateLogParams.setOperationModule(OperationModule.BasicDataEnterpriceAccount.value());
1626
            updateLogParams.setOperationUser(authUserHelper.getCurrentAuditor().get());
eddie.woo's avatar
eddie.woo committed
1627 1628 1629 1630 1631 1632 1633 1634
            updateLogParams.setComment(LogMessage.EnterpriceAccountImportUpdate);
            updateLogParams.setOperationObject(parentNodeOriginal.getName());
            updateLogParams.setOperationContent("operation content");
            updateLogParams.setOperateLogType(OperateLogType.OperationLogEnterPrise.value());
            updateLogParams.setOperationAction(OperationAction.Update.value());
            operationLogService.updateDataAddLog(updateLogParams);
        }
    }
1635

eddie.woo's avatar
eddie.woo committed
1636 1637
    /**
     * 通过Parent企业科目对象获取该ParentCode下面的所有子企业科目
1638 1639
     *
     * @param parentCode   - Parent企业科目代码
1640
     * @param accountSetId - 企业账套Id
1641 1642
     * @param industryId   - 行业Id
     * @param orgId        - 机构Id
eddie.woo's avatar
eddie.woo committed
1643 1644
     * @return
     */
1645 1646
    private List<EnterpriseAccount> getMappingResultByParentCode(String parentCode, String accountSetId, String industryId, String orgId) {
        return customAccountMapper.getMappingResult(accountSetId, industryId, orgId, parentCode);
eddie.woo's avatar
eddie.woo committed
1647
    }
1648 1649 1650

    private void addMapParentAccountResult(String key, List<String> value) {
        if (!mapParentAccountResult.containsKey(key)) {
eddie.woo's avatar
eddie.woo committed
1651 1652 1653
            this.mapParentAccountResult.put(key, value);
        }
    }
1654 1655 1656

    private String getConvertedIndustryId(String industryId) {
        if (industryId != null && industryId.equals(IndustryConstant.RealEstateId)) {
1657
            return industryId;
eddie.woo's avatar
eddie.woo committed
1658
        }
1659
        return IndustryConstant.GeneralIndustryId;
eddie.woo's avatar
eddie.woo committed
1660
    }
1661 1662

    private String getEnterpriseAccountInfo(EnterpriseAccount enterpriseAccount) {
eddie.woo's avatar
eddie.woo committed
1663
        String str = "";
1664
        if (enterpriseAccount.getAcctProp() != null && enterpriseAccount.getAcctProp() < EnterpriseAccountConstant.acctPropLogList.size()) {
eddie.woo's avatar
eddie.woo committed
1665 1666
            if (enterpriseAccount.getAcctProp() <= -1) {
                str = EnterpriseAccountConstant.acctPropLogList.get(0);
1667
            } else {
eddie.woo's avatar
eddie.woo committed
1668 1669 1670
                str = EnterpriseAccountConstant.acctPropLogList.get(enterpriseAccount.getAcctProp());
            }
        }
1671 1672 1673
        return enterpriseAccount.getCode() + " "
                + enterpriseAccount.getName() + " " + str + " "
                + EnterpriseAccountConstant.directionLogMap.get(enterpriseAccount.getDirection());
eddie.woo's avatar
eddie.woo committed
1674
    }
1675

1676
    private void enableEnterpriseAccountSet(String enterpriseAccountSetId) {
1677

1678
        EnterpriseAccountSet enterpriseAccountSet = enterpriseAccountSetMapper.selectByPrimaryKey(enterpriseAccountSetId);
1679
        if (enterpriseAccountSet.getIsActive()) {
eddie.woo's avatar
eddie.woo committed
1680 1681
            return;
        }
1682

eddie.woo's avatar
eddie.woo committed
1683
        EnterpriseAccountExample example = new EnterpriseAccountExample();
1684
        example.createCriteria().andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId);
eddie.woo's avatar
eddie.woo committed
1685
        List<EnterpriseAccount> enterpriseAccountList = enterpriseAccountMapper.selectByExample(example);
1686

eddie.woo's avatar
eddie.woo committed
1687
        if (CollectionUtils.isEmpty(enterpriseAccountList)) {
eddie.woo's avatar
eddie.woo committed
1688 1689
            return;
        }
1690

eddie.woo's avatar
eddie.woo committed
1691 1692 1693 1694 1695 1696 1697
        List<EnterpriseAccountDto> enterpriseAccountDtoList = new ArrayList<>();
        enterpriseAccountList.stream().forEach(sa -> {
            EnterpriseAccountDto enterpriseAccountDto = new EnterpriseAccountDto();
            CommonUtils.copyProperties(sa, enterpriseAccountDto);
            enterpriseAccountDtoList.add(enterpriseAccountDto);
        });
        List<ValidateInfoDto> validateInfoDtoList = validateEnterpriseAccountList(enterpriseAccountDtoList);
eddie.woo's avatar
eddie.woo committed
1698
        boolean anyValidationErrorExist = validateInfoDtoList.stream().filter(sa -> !CollectionUtils.isEmpty(sa.getInValidateCodeList())).findAny().isPresent();
1699 1700
        if (!anyValidationErrorExist) {
            if (!enterpriseAccountSet.getIsActive()) {
eddie.woo's avatar
eddie.woo committed
1701 1702 1703 1704
                enterpriseAccountSet.setIsActive(CommonConstants.ACTIVE_STATUS);
                enterpriseAccountSetMapper.updateByPrimaryKey(enterpriseAccountSet);
            }
        }
1705

eddie.woo's avatar
eddie.woo committed
1706
    }
1707 1708


eddie.woo's avatar
eddie.woo committed
1709 1710 1711 1712
    /* (non-Javadoc)
     * @see pwc.taxtech.atms.service.EnterpriseAccountService#validateImportEnterpriseAccount(java.io.InputStream, java.lang.String)
     */
    public OperationResultDto<List<EnterpriseAccountDto>> validateImportEnterpriseAccount(String filePath) {
1713

eddie.woo's avatar
eddie.woo committed
1714 1715 1716 1717
        //validate header
        InputStream savedInputStream = Files.findFileAsStream(filePath);
        Map<String, Integer> headerMap = fileService.readExcelHeaderAndClose(savedInputStream);
        List<String> standardHeader = Arrays.asList(
1718 1719 1720 1721
                EnterpriseAccountConstant.Code,
                EnterpriseAccountConstant.Name,
                EnterpriseAccountConstant.ParentCode,
                EnterpriseAccountConstant.Direction,
eddie.woo's avatar
eddie.woo committed
1722 1723
                EnterpriseAccountConstant.AcctProp);
        boolean hasParentCode = true;
1724
        for (String header : standardHeader) {
eddie.woo's avatar
eddie.woo committed
1725
            Integer index = headerMap.get(header);
1726 1727
            if (index == null) {
                if (header.equals(EnterpriseAccountConstant.ParentCode)) {
eddie.woo's avatar
eddie.woo committed
1728 1729 1730 1731 1732 1733
                    hasParentCode = false;
                    continue;
                }
                return new OperationResultDto<>(false, EnterpriseAccountMessage.EnterpriceAccountImportDataFormatError);
            }
        }
1734

eddie.woo's avatar
eddie.woo committed
1735 1736 1737
        //read excel data
        savedInputStream = Files.findFileAsStream(filePath);
        Collection<Map> mapCollection = fileService.readExcelAndClose(savedInputStream);
1738

eddie.woo's avatar
eddie.woo committed
1739
        //nothing to import
1740
        if (mapCollection == null || CollectionUtils.isEmpty(mapCollection)) {
eddie.woo's avatar
eddie.woo committed
1741 1742
            return new OperationResultDto<>(true);
        }
1743

eddie.woo's avatar
eddie.woo committed
1744 1745
        //validate data
        List<EnterpriseAccountDto> importData = new ArrayList<>();
1746
        for (Map map : mapCollection) {
eddie.woo's avatar
eddie.woo committed
1747
            EnterpriseAccountDto enterpriseAccountDto = new EnterpriseAccountDto();
1748

eddie.woo's avatar
eddie.woo committed
1749
            //direction
1750
            String direction = map.get(EnterpriseAccountConstant.Direction) == null ? null : map.get(EnterpriseAccountConstant.Direction).toString();
eddie.woo's avatar
eddie.woo committed
1751 1752 1753 1754 1755
            if (direction == null || direction.trim().isEmpty()) {
                direction = CommonConstants.DebitDirection;
            }
            try {
                enterpriseAccountDto.setDirection(Integer.valueOf(direction));
1756
            } catch (NumberFormatException e) {
eddie.woo's avatar
eddie.woo committed
1757 1758
                return new OperationResultDto<>(false, EnterpriseAccountMessage.DirectionFormatError);
            }
1759

eddie.woo's avatar
eddie.woo committed
1760
            //accprop 
1761 1762
            String acctProp = map.get(EnterpriseAccountConstant.AcctProp) == null ? null : map.get(EnterpriseAccountConstant.AcctProp).toString();
            if (acctProp == null || acctProp.trim().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1763 1764 1765 1766
                acctProp = "-1";
            }
            try {
                enterpriseAccountDto.setAcctProp(Integer.valueOf(acctProp));
1767
            } catch (NumberFormatException e) {
eddie.woo's avatar
eddie.woo committed
1768 1769
                return new OperationResultDto<>(false, EnterpriseAccountMessage.AcctPropFormatError);
            }
1770

eddie.woo's avatar
eddie.woo committed
1771
            //code
1772 1773
            String code = map.get(EnterpriseAccountConstant.Code) == null ? null : map.get(EnterpriseAccountConstant.Code).toString();
            if (code == null || code.trim().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1774 1775
                return new OperationResultDto<>(false, EnterpriseAccountMessage.CodeEmpty);
            }
1776
            if (code.length() > EnterpriseAccountConstant.CodeMaxLength) {
eddie.woo's avatar
eddie.woo committed
1777 1778 1779
                return new OperationResultDto<>(false, EnterpriseAccountMessage.CodeMaxLength);
            }
            enterpriseAccountDto.setCode(code);
1780

eddie.woo's avatar
eddie.woo committed
1781
            //name
1782 1783
            String name = map.get(EnterpriseAccountConstant.Name) == null ? null : map.get(EnterpriseAccountConstant.Name).toString();
            if (name == null || name.trim().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1784 1785
                name = "";
            }
1786
            if (name.length() > EnterpriseAccountConstant.NameMaxLength) {
eddie.woo's avatar
eddie.woo committed
1787 1788 1789
                return new OperationResultDto<>(false, EnterpriseAccountMessage.NameMaxLength);
            }
            enterpriseAccountDto.setName(name);
1790

eddie.woo's avatar
eddie.woo committed
1791 1792
            //parentCode
            String parentCode = "";
1793 1794
            if (hasParentCode) {
                parentCode = map.get(EnterpriseAccountConstant.ParentCode) == null ? null : map.get(EnterpriseAccountConstant.ParentCode).toString();
eddie.woo's avatar
eddie.woo committed
1795
            }
1796
            if (enterpriseAccountDto.getCode().equals(parentCode)) {
eddie.woo's avatar
eddie.woo committed
1797 1798 1799
                parentCode = "";
            }
            enterpriseAccountDto.setParentCode(parentCode);
1800

eddie.woo's avatar
eddie.woo committed
1801 1802
            importData.add(enterpriseAccountDto);
        }
1803
        OperationResultDto<List<EnterpriseAccountDto>> result = new OperationResultDto<>(true);
eddie.woo's avatar
eddie.woo committed
1804 1805 1806
        result.setData(importData);
        return result;
    }
1807

1808
    private OperationResultDto<?> importDataProcess(List<EnterpriseAccountDto> importData, String enterpriseAccountSetId, boolean isImportAppend) {
1809

eddie.woo's avatar
eddie.woo committed
1810
        //nothing to import
1811
        if (CollectionUtils.isEmpty(importData) && isImportAppend) {
eddie.woo's avatar
eddie.woo committed
1812 1813 1814
            return OperationResultDto.success();
        }
        // transfrom data
1815
        List<EnterpriseAccount> importEntityList = transform(importData, enterpriseAccountSetId);
1816

eddie.woo's avatar
eddie.woo committed
1817
        //disable EnterpriseAccountSet
1818
        EnterpriseAccountSet enterpriseAccountSet = enterpriseAccountSetMapper.selectByPrimaryKey(enterpriseAccountSetId);
1819
        if (enterpriseAccountSet.getIsActive()) {
eddie.woo's avatar
eddie.woo committed
1820 1821 1822 1823 1824 1825
            enterpriseAccountSet.setIsActive(CommonConstants.DEACTIVE_STATUS);
            enterpriseAccountSetMapper.updateByPrimaryKey(enterpriseAccountSet);
        }

        //import
        //如覆盖导入先批量删除
1826
        if (!isImportAppend) {
eddie.woo's avatar
eddie.woo committed
1827
            EnterpriseAccountExample example = new EnterpriseAccountExample();
1828
            example.createCriteria().andEnterpriseAccountSetIdEqualTo(enterpriseAccountSetId);
eddie.woo's avatar
eddie.woo committed
1829 1830 1831
            enterpriseAccountMapper.deleteByExample(example);
        }
        //导入
1832
        for (EnterpriseAccount importEntity : importEntityList) {
eddie.woo's avatar
eddie.woo committed
1833 1834
            enterpriseAccountMapper.insertSelective(importEntity);
        }
1835

eddie.woo's avatar
eddie.woo committed
1836
        //enable EnterpriseAccountSet
1837
        enableEnterpriseAccountSet(enterpriseAccountSetId);
1838

eddie.woo's avatar
eddie.woo committed
1839
        return OperationResultDto.success();
1840

eddie.woo's avatar
eddie.woo committed
1841
    }
1842

eddie.woo's avatar
eddie.woo committed
1843 1844
    /**
     * @param importData
1845
     * @param enterpriseAccountSetId
eddie.woo's avatar
eddie.woo committed
1846 1847
     * @return
     */
1848
    private List<EnterpriseAccount> transform(List<EnterpriseAccountDto> importData, String enterpriseAccountSetId) {
1849 1850

        if (CollectionUtils.isEmpty(importData)) {
eddie.woo's avatar
eddie.woo committed
1851 1852 1853
            return new ArrayList<>();
        }
        importData.stream().forEach(account -> {
1854 1855
            account.setId(CommonUtils.getUUID());
            account.setEnterpriseAccountSetId(enterpriseAccountSetId);
eddie.woo's avatar
eddie.woo committed
1856 1857 1858
            account.setIsActive(true);
            account.setCreateTime(new Date());
            account.setUpdateTime(new Date());
1859 1860 1861
            String userId = authUserHelper.getCurrentUserId();
            account.setCreatorId(userId);
            account.setUpdatorId(userId);
eddie.woo's avatar
eddie.woo committed
1862
        });
1863

eddie.woo's avatar
eddie.woo committed
1864 1865
        //set parent code, 
        List<String> validateCodeList = importData.stream().map(sa -> sa.getCode()).collect(Collectors.toList());
1866 1867
        for (EnterpriseAccountDto enterpriseAccountDto : importData) {
            if (enterpriseAccountDto.getParentCode() == null || enterpriseAccountDto.getParentCode().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1868 1869 1870
                enterpriseAccountDto.setParentCode(getMatchParentCode(enterpriseAccountDto.getCode(), validateCodeList));
            }
        }
1871

eddie.woo's avatar
eddie.woo committed
1872
        //set acct level,is leaf
1873
        List<String> parentCodeList = importData.stream().filter(sa -> sa.getParentCode() != null && !sa.getParentCode().isEmpty())
eddie.woo's avatar
eddie.woo committed
1874
                .map(sa -> sa.getParentCode()).collect(Collectors.toList());
1875
        for (EnterpriseAccountDto enterpriseAccountDto : importData) {
eddie.woo's avatar
eddie.woo committed
1876
            setAcctLevel(enterpriseAccountDto, importData);
1877
            if (CollectionUtils.isEmpty(parentCodeList)) {
eddie.woo's avatar
eddie.woo committed
1878
                enterpriseAccountDto.setIsLeaf(true);
1879 1880
            } else {
                if (parentCodeList.contains(enterpriseAccountDto.getCode())) {
eddie.woo's avatar
eddie.woo committed
1881
                    enterpriseAccountDto.setIsLeaf(false);
1882
                } else {
eddie.woo's avatar
eddie.woo committed
1883 1884 1885 1886
                    enterpriseAccountDto.setIsLeaf(true);
                }
            }
        }
1887

eddie.woo's avatar
eddie.woo committed
1888 1889 1890 1891 1892 1893 1894 1895
        //populate entity list
        List<EnterpriseAccount> enterpriseAccountList = new ArrayList<>();
        importData.stream().forEach(enterpriseAccountDto -> {
            EnterpriseAccount enterpriseAccount = new EnterpriseAccount();
            CommonUtils.copyProperties(enterpriseAccountDto, enterpriseAccount);
            enterpriseAccount.setRuleType(2);
            enterpriseAccountList.add(enterpriseAccount);
        });
1896

eddie.woo's avatar
eddie.woo committed
1897 1898
        return enterpriseAccountList;
    }
1899 1900


eddie.woo's avatar
eddie.woo committed
1901 1902
    /**
     * Get parent Code from existing validated code list
1903
     *
eddie.woo's avatar
eddie.woo committed
1904 1905 1906 1907 1908
     * @param code
     * @param validateCodeList
     * @return parent code
     */
    private String getMatchParentCode(String code, List<String> validateCodeList) {
1909 1910

        for (int i = code.length() - 1; i >= 0; i--) {
eddie.woo's avatar
eddie.woo committed
1911 1912
            String temp = code.substring(0, i);
            List<String> matchList = validateCodeList.stream().filter(vCode -> vCode.equals(temp)).collect(Collectors.toList());
1913
            if (matchList != null && matchList.size() == 1) {
eddie.woo's avatar
eddie.woo committed
1914 1915 1916 1917 1918
                return temp;
            }
        }
        return null;
    }
1919

eddie.woo's avatar
eddie.woo committed
1920 1921
    /**
     * Sets the acct level.
1922
     *
eddie.woo's avatar
eddie.woo committed
1923 1924
     * @param currentDto      - The current
     * @param validateDtoList - The validate list
eddie.woo's avatar
eddie.woo committed
1925 1926
     */
    private void setAcctLevel(EnterpriseAccountDto currentDto, List<EnterpriseAccountDto> validateDtoList) {
1927 1928

        if (currentDto.getParentCode() == null || currentDto.getParentCode().isEmpty()) {
eddie.woo's avatar
eddie.woo committed
1929 1930 1931 1932 1933 1934 1935
            currentDto.setAcctLevel(1);
            currentDto.setFullName(currentDto.getName());
            return;
        }
        EnterpriseAccountDto parentDto = null;
        Optional<EnterpriseAccountDto> ifparentDtoExist = validateDtoList.stream()
                .filter(sa -> sa.getCode().equals(currentDto.getParentCode())).findAny();
1936
        if (ifparentDtoExist.isPresent()) {
eddie.woo's avatar
eddie.woo committed
1937 1938
            parentDto = ifparentDtoExist.get();
        }
1939 1940
        if (parentDto != null) {
            if (parentDto.getAcctLevel() == null) {
eddie.woo's avatar
eddie.woo committed
1941 1942
                setAcctLevel(parentDto, validateDtoList);
            }
1943 1944 1945
            currentDto.setAcctLevel(parentDto.getAcctLevel() + 1);

            if (currentDto.getName() != null && !currentDto.getName().isEmpty()
eddie.woo's avatar
eddie.woo committed
1946 1947
                    && !currentDto.getName().contains(parentDto.getFullName() + EnterpriseAccountConstant.FullNameSeparator)) {
                currentDto.setFullName(parentDto.getFullName() + EnterpriseAccountConstant.FullNameSeparator + currentDto.getName());
1948
            } else {
eddie.woo's avatar
eddie.woo committed
1949 1950
                currentDto.setFullName(currentDto.getName());
            }
1951
        } else {
eddie.woo's avatar
eddie.woo committed
1952 1953 1954
            currentDto.setFullName(currentDto.getName());
        }
    }
1955

eddie.woo's avatar
eddie.woo committed
1956 1957 1958 1959 1960
    public OperationResultDto hasMappedCheck(String[] orgIds, String orgSetId) {
        //TODO 检查Mapping关系
        return null;
    }

eddie.woo's avatar
eddie.woo committed
1961
}