OrganizationServiceImpl.java 169 KB
Newer Older
eddie.woo's avatar
eddie.woo committed
1 2
package pwc.taxtech.atms.service.impl;

gary's avatar
gary committed
3
import com.alibaba.fastjson.JSON;
gary's avatar
gary committed
4
import com.alibaba.fastjson.JSONObject;
eddie.woo's avatar
eddie.woo committed
5
import com.google.common.collect.Lists;
gary's avatar
gary committed
6
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
eddie.woo's avatar
eddie.woo committed
7
import org.apache.commons.collections.CollectionUtils;
eddie.woo's avatar
eddie.woo committed
8 9 10 11 12 13 14
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.format.DateTimeFormat;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
gary's avatar
gary committed
15
import org.springframework.beans.BeanUtils;
eddie.woo's avatar
eddie.woo committed
16
import org.springframework.beans.factory.annotation.Autowired;
gary's avatar
gary committed
17
import org.springframework.beans.factory.annotation.Value;
gary's avatar
gary committed
18
import org.springframework.dao.DuplicateKeyException;
eddie.woo's avatar
eddie.woo committed
19 20 21 22 23 24 25 26 27 28 29 30 31
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;
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;
import pwc.taxtech.atms.common.ServiceTypeEnum;
import pwc.taxtech.atms.common.VatTaxPayerTypeEnum;
import pwc.taxtech.atms.common.message.EnterpriseAccountSetOrgMessage;
import pwc.taxtech.atms.common.message.LogMessage;
import pwc.taxtech.atms.common.message.OrganizationMessage;
gary's avatar
gary committed
32
import pwc.taxtech.atms.common.util.BeanUtil;
gary's avatar
gary committed
33
import pwc.taxtech.atms.common.util.HttpUtil;
gary's avatar
gary committed
34
import pwc.taxtech.atms.constant.*;
35 36
import pwc.taxtech.atms.dao.*;
import pwc.taxtech.atms.dpo.*;
gary's avatar
gary committed
37 38 39
import pwc.taxtech.atms.dpo.OrgBasicDto;
import pwc.taxtech.atms.dpo.OrgGeneralInfoMiddleDto;
import pwc.taxtech.atms.dpo.OrgInfoDto;
eddie.woo's avatar
eddie.woo committed
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import pwc.taxtech.atms.dto.AreaOrganizationStatistics;
import pwc.taxtech.atms.dto.AreaStatistics;
import pwc.taxtech.atms.dto.IndustryDto;
import pwc.taxtech.atms.dto.OperationLogDto;
import pwc.taxtech.atms.dto.OperationResultDto;
import pwc.taxtech.atms.dto.OrganizationStatistics;
import pwc.taxtech.atms.dto.OrganizationValidateDto;
import pwc.taxtech.atms.dto.UpdateLogParams;
import pwc.taxtech.atms.dto.dimension.AttributeTypeEnum;
import pwc.taxtech.atms.dto.dimension.DimensinTypeOrgDto;
import pwc.taxtech.atms.dto.dimension.DimensionOrgDto;
import pwc.taxtech.atms.dto.dimension.DimensionOrgDtoDashboard;
import pwc.taxtech.atms.dto.dimension.DimensionTypeEnum;
import pwc.taxtech.atms.dto.dimension.DimensionValueDisplayDto;
import pwc.taxtech.atms.dto.dimension.OrgDashboardParams;
eddie.woo's avatar
eddie.woo committed
55 56
import pwc.taxtech.atms.dto.navtree.DevTreeDto;
import pwc.taxtech.atms.dto.navtree.IvhTreeDto;
eddie.woo's avatar
eddie.woo committed
57
import pwc.taxtech.atms.dto.navtree.NavTreeDto;
gary's avatar
gary committed
58
import pwc.taxtech.atms.dto.organization.*;
eddie.woo's avatar
eddie.woo committed
59
import pwc.taxtech.atms.dto.organization.OrgGeneralInfoDto;
60
import pwc.taxtech.atms.dto.organization.OrganizationExtraDto;
eddie.woo's avatar
eddie.woo committed
61
import pwc.taxtech.atms.dto.user.NameDto;
gary's avatar
gary committed
62
import pwc.taxtech.atms.dto.vatdto.JsonExportDto;
63 64
import pwc.taxtech.atms.entity.*;
import pwc.taxtech.atms.entity.OrganizationExample.Criteria;
65
import pwc.taxtech.atms.exception.ApplicationException;
gary's avatar
gary committed
66
import pwc.taxtech.atms.thirdparty.ExcelUtil;
eddie.woo's avatar
eddie.woo committed
67

eddie.woo's avatar
eddie.woo committed
68
import javax.annotation.Resource;
gary's avatar
gary committed
69
import java.io.OutputStream;
70
import java.text.SimpleDateFormat;
gary's avatar
gary committed
71
import java.util.*;
72 73 74 75
import java.util.stream.Collectors;

import static java.util.Comparator.*;
import static java.util.stream.Collectors.toList;
gary's avatar
gary committed
76
import static pwc.taxtech.atms.common.CommonConstants.*;
77 78 79 80 81 82 83
import static pwc.taxtech.atms.common.CommonUtils.copyProperties;
import static pwc.taxtech.atms.common.OperateLogType.OperationLogOrganization;
import static pwc.taxtech.atms.common.OperationModule.Organization;
import static pwc.taxtech.atms.common.message.EnterpriseAccountSetOrgMessage.EffectiveDateAreaProblem;
import static pwc.taxtech.atms.common.message.EnterpriseAccountSetOrgMessage.EnterpriseAccountSetOrgDateTimeOverlap;
import static pwc.taxtech.atms.common.message.LogMessage.AddOrganization;

eddie.woo's avatar
eddie.woo committed
84 85 86 87
/**
 * @author rzhou038
 */
@Service
88
public class OrganizationServiceImpl extends BaseService{
eddie.woo's avatar
eddie.woo committed
89 90 91 92

    @Autowired
    private OrganizationMapper organizationMapper;

gary's avatar
gary committed
93 94 95
    @Autowired
    private OrganizationExtraMapper organizationExtraMapper;

eddie.woo's avatar
eddie.woo committed
96 97 98 99
    @Autowired
    private IndustryMapper industryMapper;

    @Autowired
100
    private StatisticAttributeServiceImpl statisticAttributeService;
eddie.woo's avatar
eddie.woo committed
101 102

    @Autowired
103
    private DimensionServiceImpl dimensionService;
eddie.woo's avatar
eddie.woo committed
104 105

    @Autowired
106
    private CommonServiceImpl commonService;
eddie.woo's avatar
eddie.woo committed
107 108

    @Autowired
109
    private RoleServiceImpl roleService;
eddie.woo's avatar
eddie.woo committed
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    @Autowired
    private BusinessUnitMapper businessUnitMapper;

    @Autowired
    private DimensionMapper dimensionMapper;

    @Autowired
    private UserDimensionValueMapper userDimensionValueMapper;

    @Autowired
    private UserDimensionValueOrgMapper userDimensionValueOrgMapper;

    @Autowired
    private UserOrganizationMapper userOrganizationMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private UserDimensionValueRoleMapper userDimensionValueRoleMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private OrganizationStructureMapper organizationStructureMapper;

    @Autowired
    private UserOrganizationRoleMapper userOrganizationRoleMapper;

    @Autowired
    private DimensionValueMapper dimensionValueMapper;

    @Autowired
148
    private OperationLogServiceImpl operationLogService;
eddie.woo's avatar
eddie.woo committed
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

    @Autowired
    private EnterpriseAccountSetOrgMapper enterpriseAccountSetOrgMapper;

    @Autowired
    private ServiceTypeMapper serviceTypeMapper;

    @Autowired
    private OrganizationServiceTemplateGroupMapper organizationServiceTemplateGroupMapper;
    @Autowired
    private AreaRegionMapper areaRegionMapper;

    @Autowired
    private TaxPayerReportRuleMapper taxPayerReportRuleMapper;

    @Autowired
    private TemplateGroupMapper templateGroupMapper;

    @Autowired
    private DimensionValueOrgMapper dimensionValueOrgMapper;

    @Autowired
    private EnterpriseAccountSetMapper enterpriseAccountSetMapper;
gary's avatar
gary committed
172

173
    @Autowired
174
    private DistributedIdService distributedIdService;
eddie.woo's avatar
eddie.woo committed
175

gary's avatar
gary committed
176 177 178
    @Autowired
    private BeanUtil beanUtil;

eddie.woo's avatar
eddie.woo committed
179 180 181
    @Resource
    private UserMapper userMapper;

eddie.woo's avatar
eddie.woo committed
182 183 184 185
    private static final Logger logger = LoggerFactory.getLogger(ProjectServiceImpl.class);

    public boolean isOrganizationStructureExists(String organizationStructureId) {
        OrganizationExample example = new OrganizationExample();
186
        example.createCriteria().andStructureIdEqualTo(organizationStructureId);
eddie.woo's avatar
eddie.woo committed
187 188 189 190 191
        return organizationMapper.countByExample(example) > 0;
    }

    /*
     * (non-Javadoc)
192
     *
eddie.woo's avatar
eddie.woo committed
193 194 195 196 197 198
     * @see
     * pwc.taxtech.atms.service.OrganizationService#getLinkedOrganization(java.util.
     * List)
     */
    public List<Organization> getLinkedOrganization(List<Area> areaList) {

199
        List<String> areaIdList = areaList.stream().map(area -> area.getId()).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
200 201

        OrganizationExample organizationExample = new OrganizationExample();
202
        pwc.taxtech.atms.entity.OrganizationExample.Criteria criteria = organizationExample.createCriteria();
eddie.woo's avatar
eddie.woo committed
203
        criteria.andIsActiveEqualTo(CommonConstants.ACTIVE_STATUS);
204
        criteria.andAreaIdIn(areaIdList);
eddie.woo's avatar
eddie.woo committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        List<Organization> organizationList = organizationMapper.selectByExample(organizationExample);
        return organizationList;
    }

    public List<NavTreeDto> getOrgListToJson(Integer useType) {
        List<OrganizationDto> orgList = getOrgList(useType);
        return orgList.stream().map(this::rotateOrganizationDtoToNavTreeDto).collect(Collectors.toList());
    }

    private NavTreeDto rotateOrganizationDtoToNavTreeDto(OrganizationDto organizationDto) {
        NavTreeDto navTreeDto = new NavTreeDto();
        navTreeDto.setLabel(organizationDto.getName());
        navTreeDto.setData(organizationDto);
        navTreeDto.setChildren(organizationDto.getSubOrgs().stream().map(this::rotateOrganizationDtoToNavTreeDto)
                .collect(Collectors.toList()));
        return navTreeDto;
    }

    public List<OrganizationDto> getOrgList(Integer useType) {
        List<OrganizationDto> orgDtoList = new ArrayList<>();
        List<Organization> orgList = findAllOrganizations();
        if (!orgList.isEmpty()) {
            // find rootOrg
            List<Organization> rootOrgs = null;
            if (useType == 1) {
230
                rootOrgs = orgList.stream().filter(x -> StringUtils.isEmpty(x.getParentId())).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
231 232
            } else {
                rootOrgs = orgList.stream()
gary's avatar
gary committed
233
                        .filter(x -> StringUtils.isEmpty(x.getParentId())&& CommonConstants.ACTIVE_STATUS.equals(x.getIsActive()))
eddie.woo's avatar
eddie.woo committed
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                        .collect(Collectors.toList());
            }

            List<ServiceType> serviceList = new ArrayList<>();
            for (Organization rootOrg : rootOrgs) {
                OrganizationDto rootDto = rotateOrganizationToOrganizationDto(rootOrg);
                OrganizationDto subOrgs = genarateSubOrgs(rootDto, orgList, serviceList, useType);
                orgDtoList.add(subOrgs);
            }
        }
        orgDtoList.sort((OrganizationDto o1, OrganizationDto o2) -> o1.getName().compareTo(o2.getName()));
        return orgDtoList;
    }

    private OrganizationDto genarateSubOrgs(OrganizationDto parentOrg, List<Organization> orgs,
249
                                            List<ServiceType> serviceList, Integer useType) {
250
        if (StringUtils.isNotEmpty(parentOrg.getParentId())) {
251
            Organization organization = orgs.stream().filter(x -> x.getId().equals(parentOrg.getParentId()))
eddie.woo's avatar
eddie.woo committed
252 253 254 255 256
                    .collect(Collectors.toList()).get(0);
            parentOrg.setParentName(organization == null ? null : organization.getName());
        }
        List<Organization> subOrgs = null;
        if (useType == 1) {
257
            subOrgs = orgs.stream().filter(x -> parentOrg.getId().equals(x.getParentId())).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
258
        } else {
259
            subOrgs = orgs.stream().filter(x -> parentOrg.getId().equals(x.getParentId())
eddie.woo's avatar
eddie.woo committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
                    && CommonConstants.ACTIVE_STATUS.equals(x.getIsActive())).collect(Collectors.toList());
        }
        parentOrg.setSubOrgs(new ArrayList<>());

        // create and add subtrees to the current node
        for (Organization subOrg : subOrgs) {
            OrganizationDto subDto = rotateOrganizationToOrganizationDto(subOrg);
            subDto.setLevel(parentOrg.getLevel() == null ? 1 : parentOrg.getLevel() + 1);
            parentOrg.getSubOrgs().add(genarateSubOrgs(subDto, orgs, serviceList, useType));
        }
        return parentOrg;
    }

    private OrganizationDto rotateOrganizationToOrganizationDto(Organization organization) {
        OrganizationDto organizationDto = new OrganizationDto();
        CommonUtils.copyProperties(organization, organizationDto);
        return organizationDto;
    }

    private IndustryDto rotateIndustryToIndustryDto(Industry industry) {
        IndustryDto industryDto = new IndustryDto();
        return CommonUtils.copyProperties(industry, industryDto);
    }

    /*
     * (non-Javadoc)
286
     *
eddie.woo's avatar
eddie.woo committed
287 288 289 290 291
     * @see pwc.taxtech.atms.service.OrganizationService#GetOrganizationFilterList()
     */
    public List<OrganizationDto> getOrganizationFilterList() {

        OrganizationExample example = new OrganizationExample();
gary's avatar
gary committed
292
        example.setOrderByClause("name ASC");
eddie.woo's avatar
eddie.woo committed
293 294 295 296 297 298 299 300 301 302 303
        List<Organization> organizationList = organizationMapper.selectByExampleWithAssociation(example);

        if (organizationList == null || organizationList.isEmpty()) {
            return new ArrayList<>();
        }
        List<OrganizationDto> organizationDtoList = new ArrayList<>();
        for (Organization organization : organizationList) {
            OrganizationDto organizationDto = new OrganizationDto();
            CommonUtils.copyProperties(organization, organizationDto);
            organizationDto.setAreaName(organization.getArea() != null ? organization.getArea().getName() : "");
            organizationDto.setBusinessUnitName(
304
                    organization.getBusinessUnitId() != null && organization.getBusinessUnit() != null ? organization.getBusinessUnit().getName() : "");
eddie.woo's avatar
eddie.woo committed
305 306 307 308 309 310 311 312 313 314 315 316 317
            organizationDtoList.add(organizationDto);
        }
        return organizationDtoList;
    }

    public List<Organization> findAllOrganizations() {
        OrganizationExample organizationExample = new OrganizationExample();
        return organizationMapper.selectByExample(organizationExample);
    }

    public List<IndustryDto> getProjectIndustryList() {
        logger.debug("获取Project Industrys Start");
        IndustryExample example = new IndustryExample();
318
        example.setOrderByClause("id asc");
319
        pwc.taxtech.atms.entity.IndustryExample.Criteria criteria = example.createCriteria();
eddie.woo's avatar
eddie.woo committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        criteria.andIsActiveEqualTo(true);

        List<Industry> industryList = industryMapper.selectByExample(example);
        List<String> distinctName = industryList.stream().map(ind -> ind.getName()).distinct()
                .collect(Collectors.toList());
        List<IndustryDto> retList = new ArrayList<IndustryDto>();
        // 遍历disName,将返回的industry转换为IndustryDto,加入到retList
        distinctName.stream().forEach(
                disName -> retList.add(rotateIndustryToIndustryDto(findFirstListByName(disName, industryList))));
        return retList;
    }

    // 返回industry中名字为industryName的第一个Industry
    private Industry findFirstListByName(String industryName, List<Industry> industryList) {
        return (industryName == null || industryList.isEmpty()) ? null
                : industryList.stream().filter(industry -> (Strings.equals(industry.getName(), industryName)))
336
                .findFirst().orElse(null);
eddie.woo's avatar
eddie.woo committed
337 338 339 340 341 342
    }

    public List<OrgBasicDto> getOrgListLevel() {
        return organizationMapper.selectIndBusiunitAreaOrgstrctReg(false);
    }

gary's avatar
gary committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    /**
     * 15/01/2019 15:14
     * 查询出所有机构信息及机构其他信息,合成dto[]返回。
     * 无其他信息的机构亦返回基本信息。
     * []
     * @author Gary J Li
     * @return List<OrgInfoDto>
     */
    public List<OrgInfoDto> getOrgInfo() {
        List<OrgInfoDto> orgInfoDtoList = new ArrayList<>();
        List<OrgBasicDto> orgBasicDtoList = organizationMapper.selectIndBusiunitAreaOrgstrctReg(false);
        List<OrganizationExtra> organizationExtraList = organizationExtraMapper.selectByExample(null);
        if (orgBasicDtoList != null && !orgBasicDtoList.isEmpty()) {
            for(OrgBasicDto orgBasicDto:orgBasicDtoList){
                OrgInfoDto orgInfoDto = new OrgInfoDto();
                addBasicInfo(orgInfoDto,orgBasicDto);
                for(OrganizationExtra organizationExtra:organizationExtraList){
                    // 机构没有其他信息时,也将机构基本信息拼入查询结果
                    if(StringUtils.equals(orgBasicDto.getId(),organizationExtra.getOrganizationId())){
                        addExtraInfo(orgInfoDto,organizationExtra);
                        break;
                    }
                }
                orgInfoDtoList.add(orgInfoDto);
            }
        }
        return orgInfoDtoList;
    }

    private void addBasicInfo(OrgInfoDto orgInfoDto,OrgBasicDto orgBasicDto) {
        BeanUtils.copyProperties(orgBasicDto,orgInfoDto);
gary's avatar
gary committed
374
        orgInfoDto.setIsActive(orgBasicDto.getIsActive());
gary's avatar
gary committed
375 376 377 378
    }

    private void addExtraInfo(OrgInfoDto orgInfoDto,OrganizationExtra orgExtra) {
        orgInfoDto.setUnifiedSocialCreditCode(orgExtra.getUnifiedSocialCreditCode());
gary's avatar
gary committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        orgInfoDto.setTaxRegStatus(orgExtra.getTaxRegStatus());
        orgInfoDto.setApplicableAccountingRule(orgExtra.getApplicableAccountingRule());
        orgInfoDto.setCompleteRecordTotalInstitutions(orgExtra.getCompleteRecordTotalInstitutions());
        orgInfoDto.setTaxClientPersonPhoneNum(orgExtra.getTaxClientPersonPhoneNum());
        orgInfoDto.setTaxClientPersonIdNum(orgExtra.getTaxClientPersonIdNum());
        orgInfoDto.setLocalTaxAdministratorPhoneNum(orgExtra.getLocalTaxAdministratorPhoneNum());
        orgInfoDto.setEtaWebsite(orgExtra.getEtaWebsite());
        orgInfoDto.setSignTripartiteAgreement(orgExtra.getSignTripartiteAgreement());
        orgInfoDto.setActualBusinessAddress(orgExtra.getActualBusinessAddress());
        orgInfoDto.setSmallMeagerProfit(orgExtra.getSmallMeagerProfit());
        orgInfoDto.setListedCompany(orgExtra.getListedCompany());
        orgInfoDto.setTaxPayerNumberVat(orgExtra.getTaxPayerNumberVat());
        orgInfoDto.setTaxPayerNumberCit(orgExtra.getTaxPayerNumberCit());
        orgInfoDto.setTaxClientPersonEmailAddress(orgExtra.getTaxClientPersonEmailAddress());
        orgInfoDto.setLegalPersonPhoneNumber(orgExtra.getLegalPersonPhoneNumber());
        orgInfoDto.setLegalPersonLandlineNum(orgExtra.getLegalPersonLandlineNum());
        orgInfoDto.setLegalPersonEmailAddress(orgExtra.getLegalPersonEmailAddress());
        orgInfoDto.setRegFinancialOfficerName(orgExtra.getRegFinancialOfficerName());
        orgInfoDto.setRegFinancialOfficerPhoneNum(orgExtra.getRegFinancialOfficerPhoneNum());
        orgInfoDto.setRegFinancialOfficerLandlineNum(orgExtra.getRegFinancialOfficerLandlineNum());
        orgInfoDto.setRegFinancialOfficerEmailAddress(orgExtra.getRegFinancialOfficerEmailAddress());
        orgInfoDto.setSecondaryApprovalAmount(orgExtra.getSecondaryApprovalAmount());
        orgInfoDto.setBusinessRegistrationNumber(orgExtra.getBusinessRegistrationNumber());
        orgInfoDto.setParValue(orgExtra.getParValue());
        orgInfoDto.setIssuedShares(orgExtra.getIssuedShares());
        orgInfoDto.setDirectors(orgExtra.getDirectors());
gary's avatar
gary committed
405 406 407 408 409 410 411 412 413 414 415 416 417
        orgInfoDto.setRegFinancialAccountingType(orgExtra.getRegFinancialAccountingType());
        orgInfoDto.setLowValueConsumablesAmortizationMethod(orgExtra.getLowValueConsumablesAmortizationMethod());
        orgInfoDto.setDepreciationMethod(orgExtra.getDepreciationMethod());
        orgInfoDto.setAccountingSoftware(orgExtra.getAccountingSoftware());
        orgInfoDto.setTaxClientPersonName(orgExtra.getTaxClientPersonName());
        orgInfoDto.setTicketHolderName(orgExtra.getTicketHolderName());
        orgInfoDto.setTicketHolderPhoneNum(orgExtra.getTicketHolderPhoneNum());
        orgInfoDto.setNationalTaxHallAddress(orgExtra.getNationalTaxHallAddress());
        orgInfoDto.setNationalTaxAdministratorName(orgExtra.getNationalTaxAdministratorName());
        orgInfoDto.setNationalTaxAdministratorPhoneNum(orgExtra.getNationalTaxAdministratorPhoneNum());
        orgInfoDto.setLocalTaxHallAddress(orgExtra.getLocalTaxHallAddress());
        orgInfoDto.setLocalTaxAdministratorName(orgExtra.getLocalTaxAdministratorName());
        orgInfoDto.setReportingCurrency(orgExtra.getReportingCurrency());
gary's avatar
gary committed
418 419
        orgInfoDto.setConsolidationTime(orgExtra.getConsolidationTime());
        orgInfoDto.setFiscalYearDeadline(orgExtra.getFiscalYearDeadline());
gary's avatar
gary committed
420 421
        orgInfoDto.setTaxAgent(orgExtra.getTaxAgent());
        orgInfoDto.setTaxAgentContact(orgExtra.getTaxAgentContact());
gary's avatar
gary committed
422 423 424
        orgInfoDto.setOtherFacts(orgExtra.getOtherFacts());
        orgInfoDto.setTaxReturnBusinessType(orgExtra.getTaxReturnBusinessType());
        orgInfoDto.setApplicableAccountingStandardsOrAccountingSystems(orgExtra.getApplicableAccountingStandardsOrAccountingSystems());
gary's avatar
gary committed
425 426
        orgInfoDto.setTaxRuleIntroduction(orgExtra.getTaxRuleIntroduction());
        orgInfoDto.setAuditRequirements(orgExtra.getAuditRequirements());
gary's avatar
gary committed
427
        orgInfoDto.setTaxCreditRating(orgExtra.getTaxCreditRating());
gary's avatar
gary committed
428 429
    }

430 431 432
    /**
     * Organization表中根据行业,事业部,区域关联起来
     */
eddie.woo's avatar
eddie.woo committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446
    private List<OrganizationDto> getOrganizationJoinResult(Boolean orgIsActive) {
        return organizationMapper.selectIndBusiunitAreaOrgstrct(orgIsActive);
    }

    public List<OrganizationDto> getOrganizationJoinResult() {
        return getOrganizationJoinResult(true);
    }

    public Boolean taxPayerNumberUniqueValidate(OrganizationValidateDto validateDto) {
        String innerId = Strings.sBlank(validateDto.getId()).trim();
        String innerNumber = Strings.sBlank(validateDto.getValue()).trim();
        if (Strings.isBlank(innerNumber))
            return true;
        OrganizationExample example = new OrganizationExample();
447
        pwc.taxtech.atms.entity.OrganizationExample.Criteria criteria = example.createCriteria();
eddie.woo's avatar
eddie.woo committed
448 449
        criteria.andTaxPayerNumberEqualTo(innerNumber);
        List<Organization> result = organizationMapper.selectByExample(example);
450
        return !result.stream().anyMatch(res -> (Strings.isBlank(innerId)) || !innerId.equals(res.getId()));
eddie.woo's avatar
eddie.woo committed
451 452 453 454 455
    }

    /**
     * 自定义维度显示属性,在机构管理顶部点击某个维度的时候,显示下面维度的属性,Orgchart结构树(Jack)
     */
456
    public List<DimensionOrgDtoDashboard> getOrgDashboard(String parentDimensionId, String parentOrgId,
457
                                                          OrgDashboardParams param) {
eddie.woo's avatar
eddie.woo committed
458 459 460 461 462 463 464 465 466 467
        List<String> expandedOrgList = (param == null ? null : param.getExpandedOrgList());
        String filterFlag = (param == null ? null : param.getFilterFlag());

        // C#中在此处新建了变量List<DimensionOrgDtoDashboard> displayList,但无任何引用,故删除。
        if (expandedOrgList == null) {
            expandedOrgList = new ArrayList<>();
        }
        List<StatisticAttributeDisplayDto> rawAttrList = new ArrayList<>();
        List<DimensionValueDisplayDto> dimensionValueList = new ArrayList<>();
        List<StatisticAttributeDisplayDto> attrDtoList = statisticAttributeService
468 469
                .getStatisticAttributeListByDimensionId(parentDimensionId, rawAttrList);
        if (!DimensionConstant.OrgSubChildrenId.equals(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
470
            List<OrganizationDto> query;
471 472
            query = getOrgDimensionMappingForDimension(parentDimensionId).stream()
                    .filter(org -> Objects.equals(org.getDimensionId(), parentDimensionId))
eddie.woo's avatar
eddie.woo committed
473 474 475 476
                    .collect(Collectors.toList());
            logger.debug("Size of query in getOrgDashboard is {}", query.size());
            query.stream().forEach(q -> addToDimensionValueList(q, dimensionValueList));
            logger.debug("Size of dimensionValueList in getOrgDashboard is {}", dimensionValueList.size());
477
            return getStatisticCount(dimensionValueList, parentDimensionId, query, attrDtoList);
eddie.woo's avatar
eddie.woo committed
478 479
        } else {
            // 机构基础数据包括区域,层级,自定义等等
480 481
            List<OrganizationDto> orgMappingResult = getOrgDimensionMappingForDimension(parentDimensionId).stream()
                    .filter(orgDto -> parentDimensionId != null && parentDimensionId.equals(orgDto.getDimensionId()))
eddie.woo's avatar
eddie.woo committed
482 483 484 485 486 487 488 489 490
                    .collect(Collectors.toList());

            List<StatisticAttributeDisplayDto> orgAttrList = rawAttrList.stream()
                    .sorted(Comparator.comparing(statisticAttributeDisplayDto -> Optional
                            .ofNullable(statisticAttributeDisplayDto.getOrderIndex()).orElse(0)))
                    .limit(2).collect(Collectors.toList());

            // 也就是UI显示的节点List
            List<OrganizationDto> orgDtoList = new ArrayList<>();
491 492 493
            String currentOrgId = "";
            if (Strings.isNotBlank(parentOrgId) && parentOrgId.contains("@@Current@@")) {
                currentOrgId = parentOrgId.replace("@@Current@@", "").trim();
eddie.woo's avatar
eddie.woo committed
494
            }
495 496 497
            if (Strings.isBlank(parentOrgId) || Strings.equals(parentOrgId, "0")) {
                // 如果父机构Id为空,那么获取第一层全部的机构
                orgDtoList = orgMappingResult.stream().filter(orgMapRes -> Strings.isBlank(orgMapRes.getParentId()))
eddie.woo's avatar
eddie.woo committed
498
                        .collect(Collectors.toList());
499 500
            } else if ("1".equals(parentOrgId)) {
                orgDtoList = orgMappingResult.stream().filter(orgMapRes -> Strings.isBlank(orgMapRes.getParentId())
eddie.woo's avatar
eddie.woo committed
501
                        && Strings.isNotBlank(orgMapRes.getTaxPayerNumber())).collect(Collectors.toList());
502 503
            } else if ("2".equals(parentOrgId)) {
                orgDtoList = orgMappingResult.stream().filter(orgMapRes -> Strings.isBlank(orgMapRes.getParentId())
eddie.woo's avatar
eddie.woo committed
504 505 506 507 508
                        && Strings.isBlank(orgMapRes.getTaxPayerNumber())).collect(Collectors.toList());
            } else {
                // 只获取指定节点的子节点信息

                // 创建临时变量
509
                String currentOrgIdTemp = currentOrgId;
eddie.woo's avatar
eddie.woo committed
510
                if ("0".equals(filterFlag) || Strings.isBlank(filterFlag)) {
511
                    if (Strings.isNotBlank(currentOrgIdTemp)) {
eddie.woo's avatar
eddie.woo committed
512
                        orgDtoList = orgMappingResult.stream()
513
                                .filter(x -> currentOrgIdTemp != null && currentOrgIdTemp.equals(x.getId()))
eddie.woo's avatar
eddie.woo committed
514 515 516
                                .collect(Collectors.toList());
                    } else {
                        orgDtoList = orgMappingResult.stream()
517
                                .filter(x -> parentOrgId != null && parentOrgId.equals(x.getParentId()))
eddie.woo's avatar
eddie.woo committed
518 519 520
                                .collect(Collectors.toList());
                    }
                } else if ("1".equals(filterFlag)) {
521 522 523
                    if (Strings.isNotBlank(currentOrgIdTemp)) {
                        orgDtoList = orgMappingResult.stream().filter(x -> currentOrgIdTemp != null
                                && currentOrgIdTemp.equals(x.getId()) && Strings.isNotBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
524 525
                                .collect(Collectors.toList());
                    } else {
526 527
                        orgDtoList = orgMappingResult.stream().filter(x -> parentOrgId != null
                                && parentOrgId.equals(x.getParentId()) && Strings.isNotBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
528 529 530
                                .collect(Collectors.toList());
                    }
                } else if ("2".equals(filterFlag)) {
531 532 533
                    if (Strings.isNotBlank(currentOrgIdTemp)) {
                        orgDtoList = orgMappingResult.stream().filter(x -> currentOrgIdTemp != null
                                && currentOrgIdTemp.equals(x.getId()) && Strings.isNotBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
534 535
                                .collect(Collectors.toList());
                    } else {
536 537
                        orgDtoList = orgMappingResult.stream().filter(x -> parentOrgId != null
                                && parentOrgId.equals(x.getParentId()) && Strings.isBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
538 539 540 541
                                .collect(Collectors.toList());
                    }
                }
            }
542 543
            if ("1".equals(parentOrgId) || "2".equals(parentOrgId)) {
                filterFlag = parentOrgId;
eddie.woo's avatar
eddie.woo committed
544 545
            }

546
            return getOrgChartDisplayData(orgDtoList, orgAttrList, parentDimensionId, orgMappingResult, attrDtoList,
eddie.woo's avatar
eddie.woo committed
547 548 549 550 551
                    expandedOrgList, filterFlag);
        }
    }

    private List<DimensionOrgDtoDashboard> getOrgChartDisplayData(List<OrganizationDto> orgList,
552
                                                                  List<StatisticAttributeDisplayDto> orgAttrList, String parentDimensionId,
553 554
                                                                  List<OrganizationDto> orgMappingResult, List<StatisticAttributeDisplayDto> attrDtoList,
                                                                  List<String> expandedOrgList, String filterFlag) {
eddie.woo's avatar
eddie.woo committed
555 556 557 558 559 560 561
        List<OrganizationDto> allOrgList = getAllOrgList();

        // 自定义维度与之关联的机构列表
        List<DimensionValueDisplayDto> dimensionValueList = getDimensionValueDisplayDtoList(orgList, orgAttrList,
                allOrgList);

        // 各种统计
562
        List<DimensionOrgDtoDashboard> statisticList = getStatisticCount(dimensionValueList, parentDimensionId,
eddie.woo's avatar
eddie.woo committed
563 564 565 566 567 568 569
                orgMappingResult, attrDtoList, allOrgList);

        // 获取orgQuery下的子机构
        // 判断是否存在子节点,如果存在的话,需要返回标记
        for (OrganizationDto item : orgList) {
            List<OrganizationDto> childrenOrgList = new ArrayList<>();
            if (!"1".equals(filterFlag) && !"2".equals(filterFlag)) {
570
                childrenOrgList = orgMappingResult.stream().filter(x -> Objects.equals(x.getParentId(), item.getId()))
eddie.woo's avatar
eddie.woo committed
571 572 573
                        .collect(Collectors.toList());
            } else if ("1".equals(filterFlag)) {
                childrenOrgList = orgMappingResult.stream().filter(
574
                        x -> Objects.equals(x.getParentId(), item.getId()) && Strings.isNotBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
575 576 577
                        .collect(Collectors.toList());
            } else if ("2".equals(filterFlag)) {
                childrenOrgList = orgMappingResult.stream().filter(
578
                        x -> Objects.equals(x.getParentId(), item.getId()) && Strings.isBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
579 580 581 582 583
                        .collect(Collectors.toList());
            }

            // 找出与之关联的统计卡片对象,并赋值给children属性
            DimensionOrgDtoDashboard childOrg = statisticList.stream()
584
                    .filter(x -> item.getId() != null && item.getId().equals(x.getDimensionValueId())).findFirst()
eddie.woo's avatar
eddie.woo committed
585 586 587 588
                    .orElse(null);
            Assert.notNull(childOrg, "Null childOrg");
            childOrg.setHasChildren(!childrenOrgList.isEmpty());

589
            if (expandedOrgList.contains(item.getId())) {
eddie.woo's avatar
eddie.woo committed
590 591 592 593
                // new added Jacob on 07-03
                List<DimensionValueDisplayDto> childrenDimensionValueList = getDimensionValueDisplayDtoList(
                        childrenOrgList, orgAttrList, allOrgList);
                List<DimensionOrgDtoDashboard> childrenStatisticList = getStatisticCount(childrenDimensionValueList,
594
                        parentDimensionId, orgMappingResult, attrDtoList, allOrgList);
eddie.woo's avatar
eddie.woo committed
595 596
                childOrg.setChildren(childrenStatisticList);

597
                getSubStatisticRecursion(childrenOrgList, orgAttrList, allOrgList, parentDimensionId, orgMappingResult,
eddie.woo's avatar
eddie.woo committed
598 599 600 601 602 603 604
                        attrDtoList, childrenStatisticList, expandedOrgList, filterFlag);
            }
        }
        return statisticList;
    }

    private void getSubStatisticRecursion(List<OrganizationDto> subOrgList,
605
                                          List<StatisticAttributeDisplayDto> orgAttrList, List<OrganizationDto> allOrgList, String parentDimensionId,
606 607
                                          List<OrganizationDto> orgMappingResult, List<StatisticAttributeDisplayDto> attrDtoList,
                                          List<DimensionOrgDtoDashboard> parentStatisticList, List<String> expandedOrgList, String filterFlag) {
eddie.woo's avatar
eddie.woo committed
608 609 610 611 612 613 614
        if (subOrgList.isEmpty())
            return;

        // 获取orgQuery下的子机构
        for (OrganizationDto item : subOrgList) {
            List<OrganizationDto> childrenOrgList = new ArrayList<>();
            if (!"1".equals(filterFlag) && !"2".equals(filterFlag)) {
615
                childrenOrgList = orgMappingResult.stream().filter(x -> Objects.equals(x.getParentId(), item.getId()))
eddie.woo's avatar
eddie.woo committed
616 617 618
                        .collect(Collectors.toList());
            } else if ("1".equals(filterFlag)) {
                childrenOrgList = orgMappingResult.stream().filter(
619
                        x -> Objects.equals(x.getParentId(), item.getId()) && Strings.isNotBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
620 621 622
                        .collect(Collectors.toList());
            } else if ("2".equals(filterFlag)) {
                childrenOrgList = orgMappingResult.stream().filter(
623
                        x -> Objects.equals(x.getParentId(), item.getId()) && Strings.isBlank(x.getTaxPayerNumber()))
eddie.woo's avatar
eddie.woo committed
624 625 626 627 628 629 630
                        .collect(Collectors.toList());
            }
            if (childrenOrgList.isEmpty()) {
                return;
            }
            // 找出与之关联的统计卡片对象,并赋值给children属性
            DimensionOrgDtoDashboard childOrg = parentStatisticList.stream()
631
                    .filter(x -> item.getId() != null && item.getId().equals(x.getDimensionValueId())).findFirst()
eddie.woo's avatar
eddie.woo committed
632 633 634 635
                    .orElse(null);
            Assert.notNull(childOrg, "Null childOrg");
            childOrg.setHasChildren(!childrenOrgList.isEmpty());

636
            if (expandedOrgList.contains(item.getId())) {
eddie.woo's avatar
eddie.woo committed
637 638 639
                List<DimensionValueDisplayDto> childrenDimensionValueList = getDimensionValueDisplayDtoList(
                        childrenOrgList, orgAttrList, allOrgList);
                List<DimensionOrgDtoDashboard> childrenStatisticList = getStatisticCount(childrenDimensionValueList,
640
                        parentDimensionId, orgMappingResult, attrDtoList, allOrgList);
eddie.woo's avatar
eddie.woo committed
641 642
                childOrg.setChildren(childrenStatisticList);

643
                getSubStatisticRecursion(childrenOrgList, orgAttrList, allOrgList, parentDimensionId, orgMappingResult,
eddie.woo's avatar
eddie.woo committed
644 645 646 647 648 649 650 651 652
                        attrDtoList, childrenStatisticList, expandedOrgList, filterFlag);
            }
        }
    }

    /**
     * 根据机构的列表 转化为展示DTO
     */
    private List<DimensionValueDisplayDto> getDimensionValueDisplayDtoList(List<OrganizationDto> orgQuery,
653
                                                                           List<StatisticAttributeDisplayDto> orgAttrList, List<OrganizationDto> orgAllData) {
eddie.woo's avatar
eddie.woo committed
654 655 656
        List<OrganizationDto> allCustomDimensionOrg = getAllCustomDimensionOrgList();
        return orgQuery.stream()
                .map(orgQ -> rotateOrgDtoToDimValDisplayDto(orgQ, orgAttrList, allCustomDimensionOrg, orgAllData))
657
                .filter(s -> !Strings.isBlank(s.getDimensionValueId())).distinct().collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
658 659 660
    }

    private DimensionValueDisplayDto rotateOrgDtoToDimValDisplayDto(OrganizationDto orgDto,
661 662
                                                                    List<StatisticAttributeDisplayDto> orgAttrList, List<OrganizationDto> allCustomDimensionOrg,
                                                                    List<OrganizationDto> orgAllData) {
eddie.woo's avatar
eddie.woo committed
663
        DimensionValueDisplayDto dVDDto = new DimensionValueDisplayDto();
664
        dVDDto.setDimensionValueId(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
665 666 667 668 669 670 671 672 673
        dVDDto.setDimensionValueName(orgDto.getName());
        dVDDto.setFirstAttrValue(getAttrValue(!orgAttrList.isEmpty() ? orgAttrList.get(0) : null, orgDto,
                allCustomDimensionOrg, orgAllData));
        dVDDto.setSecondAttrValue(getAttrValue(orgAttrList.size() > 1 ? orgAttrList.get(1) : null, orgDto,
                allCustomDimensionOrg, orgAllData));
        return dVDDto;
    }

    private String getAttrValue(StatisticAttributeDisplayDto statAttrDto, OrganizationDto org,
674
                                List<OrganizationDto> allCustomDimensionOrg, List<OrganizationDto> allOrgDto) {
eddie.woo's avatar
eddie.woo committed
675 676 677
        if (statAttrDto == null) {
            return null;
        }
678
        OrganizationDto orgData = allOrgDto.stream().filter(x -> Objects.equals(org.getId(), x.getId())).findFirst()
eddie.woo's avatar
eddie.woo committed
679 680 681
                .orElse(null);
        Assert.notNull(orgData, "Null OrgData");
        List<OrganizationDto> dimensionValueOrgList = allCustomDimensionOrg.stream()
682
                .filter(x -> Objects.equals(org.getId(), x.getId())).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
683 684 685 686 687
        String attrValueName = "";

        AttributeTypeEnum enumValue = AttributeTypeEnum.valueOf(statAttrDto.getAttributeType());
        Assert.notNull(enumValue, "Null AttributeTypeEnum");
        switch (enumValue) {
688
            case Area:
689
                attrValueName = getAreaName(org, orgData.getAreaId());
690 691
                break;
            case BusinessUnit:
692
                attrValueName = getBusinessUnitName(org, orgData.getBusinessUnitId());
693 694 695 696 697
                break;
            case Industry:
                attrValueName = org.getIndustryName();
                break;
            case OrganizationStructure:
698
                attrValueName = getStructureName(org, orgData.getStructureId());
699 700 701 702 703 704 705
                break;
            case OrgCode:
                attrValueName = org.getCode();
                break;
            case TaxPayerNumber:
                attrValueName = org.getTaxPayerNumber();
                break;
706 707 708
            case RegionId:
                // 原语句中orgData.getStructureId()未被使用,检查是否有问题
                // attrValueName = getRegion(org, orgData.getStructureId());
709 710 711 712
                attrValueName = getRegion(org);
                break;
            case SelfDimension:
                List<OrganizationDto> list = dimensionValueOrgList.stream()
713
                        .filter(x -> Objects.equals(x.getAttributeId(), statAttrDto.getAttributeId()))
714 715 716 717 718 719 720 721 722
                        .collect(Collectors.toList());
                if (!list.isEmpty()) {
                    attrValueName = list.get(0).getDimensionValueName();
                } else {
                    attrValueName = null;
                }
                break;
            default:
                logger.warn("enumValue not matched in getAttrValue");
eddie.woo's avatar
eddie.woo committed
723 724 725 726 727
        }
        return attrValueName;
    }

    private String getRegion(OrganizationDto org) {
728
        // C#中原传参businessUnitId未被使用,检查是否有问题
eddie.woo's avatar
eddie.woo committed
729
        Region region = null;
730
        if (org.getRegionId() != null) {
eddie.woo's avatar
eddie.woo committed
731
            RegionExample example = new RegionExample();
732
            pwc.taxtech.atms.entity.RegionExample.Criteria criteria = example.createCriteria();
733
            criteria.andIdEqualTo(org.getRegionId());
eddie.woo's avatar
eddie.woo committed
734 735 736 737 738 739 740 741 742
            region = regionMapper.selectByExample(example).stream().findFirst().orElse(null);
        }

        if (region != null) {
            return region.getName();
        }
        return "";
    }

743
    private String getAreaName(OrganizationDto org, String areaId) {
eddie.woo's avatar
eddie.woo committed
744
        if (Strings.isBlank(org.getAreaName())) {
745
            if (areaId != null) {
eddie.woo's avatar
eddie.woo committed
746
                AreaExample example = new AreaExample();
747
                pwc.taxtech.atms.entity.AreaExample.Criteria criteria = example.createCriteria();
748
                criteria.andIdEqualTo(areaId);
eddie.woo's avatar
eddie.woo committed
749 750 751 752 753 754 755 756 757 758
                org.setAreaName(
                        areaMapper.selectByExample(example).stream().map(am -> am.getName()).findFirst().orElse(null));
            } else {
                org.setAreaName(null);
            }

        }
        return org.getAreaName();
    }

759
    private String getBusinessUnitName(OrganizationDto org, String businessUnitId) {
eddie.woo's avatar
eddie.woo committed
760
        if (Strings.isBlank(org.getBusinessUnitName())) {
761
            if (businessUnitId != null) {
eddie.woo's avatar
eddie.woo committed
762
                BusinessUnitExample example = new BusinessUnitExample();
763
                pwc.taxtech.atms.entity.BusinessUnitExample.Criteria criteria = example.createCriteria();
764
                criteria.andIdEqualTo(businessUnitId);
eddie.woo's avatar
eddie.woo committed
765 766 767 768 769 770 771 772 773
                org.setBusinessUnitName(businessUnitMapper.selectByExample(example).stream().map(bu -> bu.getName())
                        .findFirst().orElse(null));
            } else {
                org.setBusinessUnitName(null);
            }
        }
        return org.getBusinessUnitName();
    }

774
    private String getStructureName(OrganizationDto org, String structureId) {
eddie.woo's avatar
eddie.woo committed
775
        if (Strings.isBlank(org.getStructureName())) {
776
            if (structureId != null) {
eddie.woo's avatar
eddie.woo committed
777
                OrganizationStructureExample example = new OrganizationStructureExample();
778
                pwc.taxtech.atms.entity.OrganizationStructureExample.Criteria criteria = example.createCriteria();
779
                criteria.andIdEqualTo(structureId);
eddie.woo's avatar
eddie.woo committed
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
                org.setStructureName(organizationStructureMapper.selectByExample(example).stream()
                        .map(os -> os.getName()).findFirst().orElse(null));
            } else {
                org.setStructureName(null);
            }
        }
        return org.getStructureName();
    }

    private List<OrganizationDto> getAllCustomDimensionOrgList() {
        return organizationMapper.getAllCustomDimensionOrgList();
    }

    private List<OrganizationDto> getAllOrgList() {
        return organizationMapper.selectByExample(null).stream().map(this::rotateOrgToOrgDto)
                .collect(Collectors.toList());
    }

    private OrganizationDto rotateOrgToOrgDto(Organization org) {
        OrganizationDto orgDto = new OrganizationDto();
800
        orgDto.setId(org.getId());
eddie.woo's avatar
eddie.woo committed
801
        orgDto.setName(org.getName());
802 803 804 805 806
        orgDto.setBusinessUnitId(org.getBusinessUnitId());
        orgDto.setStructureId(org.getStructureId());
        orgDto.setRegionId(org.getRegionId());
        orgDto.setAreaId(org.getAreaId());
        orgDto.setParentId(org.getParentId());
eddie.woo's avatar
eddie.woo committed
807 808 809 810
        return orgDto;
    }

    private List<DimensionOrgDtoDashboard> getStatisticCount(List<DimensionValueDisplayDto> dimensionValueList,
811 812
                                                             String parentDimensionId, List<OrganizationDto> query, List<StatisticAttributeDisplayDto> attrDtoList) {
        return getStatisticCount(dimensionValueList, parentDimensionId, query, attrDtoList, null);
eddie.woo's avatar
eddie.woo committed
813 814 815
    }

    private List<DimensionOrgDtoDashboard> getStatisticCount(List<DimensionValueDisplayDto> dimensionValueList,
816
                                                             final String parentDimensionId, List<OrganizationDto> query, List<StatisticAttributeDisplayDto> attrDtoList,
817
                                                             List<OrganizationDto> allOrgList) {
eddie.woo's avatar
eddie.woo committed
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
        List<DimensionOrgDtoDashboard> displayList = new ArrayList<>();
        // 获取自定义维度的所有机构
        List<OrganizationDto> allCustomDimensionOrg = getCustomDimensionOrgList();

        // 维度值的列表,多少维度,如产品维度,值为产品1,产品2,产品3 等
        List<UserDimensionValue> userDimensionValueList = new ArrayList<>();
        List<UserDimensionValueOrg> userDimensionValueOrgList = new ArrayList<>();
        List<UserOrganization> userOrganizationList = new ArrayList<>();
        List<UserOrgRoleDto> originalRoleList = new ArrayList<>();
        List<UserOrgRoleDto> userDimensionValueRoleList = new ArrayList<>();
        List<UserOrgRoleDto> userOrganizationRoleList = new ArrayList<>();
        List<OrganizationDto> userAllDimensionList = new ArrayList<>();
        // 如果有用户数的属性
        if (attrDtoList.stream().anyMatch(attDto -> AttributeTypeEnum.User.value().equals(attDto.getAttributeType()))) {
            populateUserRoleBasic(userDimensionValueList, userDimensionValueOrgList, userOrganizationList,
                    originalRoleList, userDimensionValueRoleList, userOrganizationRoleList);

835
            if (DimensionConstant.OrgSubChildrenId.equals(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
836 837 838 839 840 841 842 843 844 845 846 847 848
                userAllDimensionList = getDimensionValueOrgDtoList().stream().map(this::rotateToOrganizationDto)
                        .collect(Collectors.toList());
            }
        }
        List<OrganizationDto> userAllDimensionListTemp = userAllDimensionList;
        if (logger.isDebugEnabled())
            logger.debug("function: getStatisticCount before filter, Size of dimensionValueList:{} ",
                    dimensionValueList.size());
        for (DimensionValueDisplayDto val : dimensionValueList) {
            DimensionOrgDtoDashboard dtoDashboard = new DimensionOrgDtoDashboard();
            List<OrganizationDto> valueList;

            // 维度的属性值,如产品1,产品2,产品3
849
            dtoDashboard.setDimensionValueId(val.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
850 851 852 853 854 855
            dtoDashboard.setDimensionValue(val.getDimensionValueName());
            dtoDashboard.setFirstAttrName(val.getFirstAttrValue());
            dtoDashboard.setSecondAttrName(val.getSecondAttrValue());
            dtoDashboard.setHasChildren(false);

            // 每个维度值下面的属性统计
856
            if (!DimensionConstant.OrgSubChildrenId.equals(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
857
                valueList = query.stream()
858 859
                        .filter(q -> val.getDimensionValueId() != null
                                && val.getDimensionValueId().equals(q.getDimensionValueId()))
eddie.woo's avatar
eddie.woo committed
860 861
                        .collect(Collectors.toList());
            } else {
862
                String orgId = val.getDimensionValueId();
eddie.woo's avatar
eddie.woo committed
863 864 865 866
                // 获取该机构下所有的子机构,速度很差
                List<String> orgList = getChildrenOrgIdToList(orgId, allOrgList).stream()
                        .filter(str -> orgId != null && !orgId.equals(str)).collect(Collectors.toList());
                // 子机构
867
                valueList = query.stream().filter(q -> orgList.contains(q.getId())).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
868 869 870 871 872 873
            }

            List<UserOrgDto> dimensionUser = new ArrayList<>();
            // 如果有用户数的属性
            if (attrDtoList.stream()
                    .anyMatch(attrDto -> AttributeTypeEnum.User.value().equals(attrDto.getAttributeType()))) {
874
                if (DimensionConstant.OrgSubChildrenId.equals(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
875 876
                    // 某个机构下的维度列表
                    List<OrganizationDto> orgDimensionTempList = userAllDimensionListTemp.stream()
877 878
                            .filter(userDimension -> val.getDimensionValueId() != null
                                    && val.getDimensionValueId().equals(userDimension.getId()))
eddie.woo's avatar
eddie.woo committed
879 880 881
                            .collect(Collectors.toList());
                    dimensionUser = roleService.getUserByDimensionValue(orgDimensionTempList, userDimensionValueList,
                            userDimensionValueOrgList, userOrganizationList, originalRoleList,
882 883
                            userDimensionValueRoleList, userOrganizationRoleList, parentDimensionId,
                            val.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
884 885 886
                } else {
                    dimensionUser = roleService.getUserByDimensionValue(valueList, userDimensionValueList,
                            userDimensionValueOrgList, userOrganizationList, originalRoleList,
887 888
                            userDimensionValueRoleList, userOrganizationRoleList, parentDimensionId,
                            val.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
889 890 891 892 893

                }
            }

            // 自定义显示维度属性
894
            // 传参String parentDimensionId 和 dimensionValueId 在C#中未被引用,故删除
eddie.woo's avatar
eddie.woo committed
895 896 897
            dtoDashboard.setOrgDtoList(
                    getOrgDtoStatisticsList(valueList, attrDtoList, allCustomDimensionOrg, dimensionUser));

898 899
            if (!displayList.stream().anyMatch(display -> dtoDashboard.getDimensionValueId() != null
                    && dtoDashboard.getDimensionValueId().equals(display.getDimensionValueId()))) {
eddie.woo's avatar
eddie.woo committed
900 901 902 903 904 905 906 907 908
                displayList.add(dtoDashboard);
            }

        }
        if (logger.isDebugEnabled())
            logger.debug("function: getStatisticCount after filter, Size of displayList: {}", displayList.size());
        return displayList;
    }

909
    // 传参String parentDimensionId 和 dimensionValueId 在C#中未被引用,故删除
910 911 912 913

    /**
     * 根据自定义属性,统计属性的值
     */
eddie.woo's avatar
eddie.woo committed
914
    private List<DimensionOrgDto> getOrgDtoStatisticsList(List<OrganizationDto> orgDtoList,
915 916
                                                          List<StatisticAttributeDisplayDto> attributeDtoList, List<OrganizationDto> allCustomDimensionOrg,
                                                          List<UserOrgDto> dimensionUserList) {
eddie.woo's avatar
eddie.woo committed
917 918
        List<DimensionOrgDto> dtoList = new ArrayList<>();
        // 统计的时候去掉没有机构的数据
919
        List<OrganizationDto> orgDtoListTemp = orgDtoList.stream().filter(s -> Strings.isNotBlank(s.getId()))
eddie.woo's avatar
eddie.woo committed
920 921 922 923
                .collect(Collectors.toList());
        // 自定义显示属性列表统计
        for (StatisticAttributeDisplayDto item : attributeDtoList) {
            DimensionOrgDto temp = new DimensionOrgDto();
924 925
            // 自定义维度Id
            temp.setAttributeId(item.getAttributeId());
eddie.woo's avatar
eddie.woo committed
926 927 928 929 930 931 932 933
            // 自定义维度名字
            temp.setAttributeName(item.getAttributeName());

            // 事业部
            if (AttributeTypeEnum.BusinessUnit.value().equals(item.getAttributeType())) {
                temp.setAttributeType(AttributeTypeEnum.BusinessUnit.value());
                // 统计当前维度,多少个事业部
                temp.setAttributeValueCount((int) (orgDtoListTemp.stream()
934
                        .map(org -> org.getBusinessUnitId() + org.getBusinessUnitName()).distinct().count()));
eddie.woo's avatar
eddie.woo committed
935 936 937 938 939
            } else if (AttributeTypeEnum.Area.value().equals(item.getAttributeType())) {
                // 覆盖区域
                temp.setAttributeType(AttributeTypeEnum.Area.value());
                // 统计当前维度,多少个覆盖区域
                temp.setAttributeValueCount((int) (orgDtoListTemp.stream().map(org -> {
940
                    return org.getAreaId();
eddie.woo's avatar
eddie.woo committed
941 942 943 944 945 946
                }).distinct().count()));
            } else if (AttributeTypeEnum.OrganizationStructure.value().equals(item.getAttributeType())) {
                // 机构层级
                temp.setAttributeType(AttributeTypeEnum.OrganizationStructure.value());
                // 统计当前维度,多少个子公司
                temp.setAttributeValueCount((int) (orgDtoListTemp.stream().map(org -> {
947
                    return org.getStructureId();
eddie.woo's avatar
eddie.woo committed
948 949 950 951 952 953
                }).distinct().count()));
            } else if (AttributeTypeEnum.OrgSubChildren.value().equals(item.getAttributeType())) {
                // 机构数
                temp.setAttributeType(AttributeTypeEnum.OrgSubChildren.value());
                // 统计当前维度,多少个机构
                temp.setAttributeValueCount(
954
                        (int) (orgDtoListTemp.stream().map(OrganizationDto::getId).distinct().count()));
eddie.woo's avatar
eddie.woo committed
955 956 957 958 959
            } else if (AttributeTypeEnum.User.value().equals(item.getAttributeType())) {
                // 用户数
                temp.setAttributeType(AttributeTypeEnum.User.value());
                // 统计当前维度,多少个用户数
                temp.setAttributeValueCount((int) (dimensionUserList.stream().map(du -> {
960
                    return (du.getUserId());
eddie.woo's avatar
eddie.woo committed
961 962 963 964 965 966
                }).distinct().count()));
            } else if (AttributeTypeEnum.Industry.value().equals(item.getAttributeType())) {
                // 所属行业
                temp.setAttributeType(AttributeTypeEnum.Industry.value());
                // 统计当前维度,多少个所属行业
                temp.setAttributeValueCount((int) (orgDtoListTemp.stream().map(org -> {
967
                    return org.getIndustryId();
eddie.woo's avatar
eddie.woo committed
968 969 970 971 972 973 974
                }).distinct().count()));
            } else {
                // 自定义的维度
                temp.setAttributeType(AttributeTypeEnum.SelfDimension.value());
                List<OrganizationDto> query = new ArrayList<>();
                allCustomDimensionOrg.stream().forEach(customDO -> {
                    orgDtoListTemp.stream().forEach(orgDto -> {
975
                        if (Objects.equals(customDO.getId(), orgDto.getId())) {
eddie.woo's avatar
eddie.woo committed
976
                            OrganizationDto tempQuery = new OrganizationDto();
977
                            tempQuery.setAttributeId(customDO.getAttributeId());
eddie.woo's avatar
eddie.woo committed
978
                            tempQuery.setAttributeName(customDO.getAttributeName());
979
                            tempQuery.setDimensionValueId(customDO.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
980 981 982 983 984 985
                            tempQuery.setDimensionValueName(customDO.getDimensionValueName());
                            query.add(tempQuery);
                        }
                    });
                });
                temp.setAttributeValueCount(
986 987
                        (int) query.stream().filter(q -> Objects.equals(item.getAttributeId(), q.getAttributeId()))
                                .map(q -> q.getDimensionValueId()).distinct().count());
eddie.woo's avatar
eddie.woo committed
988 989 990 991 992 993 994 995 996
            }
            dtoList.add(temp);
        }

        return dtoList;
    }

    private OrganizationDto rotateToOrganizationDto(DimensionValueOrgDto sDto) {
        OrganizationDto tDto = new OrganizationDto();
997
        tDto.setId(sDto.getOrganizationId());
eddie.woo's avatar
eddie.woo committed
998
        tDto.setName(sDto.getOrganizationName());
999
        tDto.setDimensionId(sDto.getDimensionId());
eddie.woo's avatar
eddie.woo committed
1000
        tDto.setDimensionName(sDto.getDimensionName());
1001
        tDto.setDimensionValueId(sDto.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
1002 1003 1004 1005
        tDto.setDimensionValueName(sDto.getDimensionValue());
        return tDto;
    }

1006
    private List<String> getChildrenOrgIdToList(String parentOrgId, List<OrganizationDto> orgList) {
eddie.woo's avatar
eddie.woo committed
1007
        List<String> childrenOrgIdList = new ArrayList<>();
1008
        childrenOrgIdList.add(parentOrgId);
eddie.woo's avatar
eddie.woo committed
1009
        List<OrganizationDto> query = orgList.stream()
1010
                .filter(org -> parentOrgId != null && parentOrgId.equals(org.getParentId()))
eddie.woo's avatar
eddie.woo committed
1011 1012
                .collect(Collectors.toList());
        query.stream().forEach(item -> {
1013 1014
            childrenOrgIdList.add(item.getId());
            getChildrenOrgIdRecursion(item.getId(), childrenOrgIdList, orgList);
eddie.woo's avatar
eddie.woo committed
1015 1016 1017 1018 1019
        });
        return childrenOrgIdList;
    }

    private void getChildrenOrgIdRecursion(String orgId, List<String> childrenOrgIdList,
1020
                                           List<OrganizationDto> orgList) {
1021
        List<OrganizationDto> query = orgList.stream().filter(org -> orgId != null && orgId.equals(org.getParentId()))
eddie.woo's avatar
eddie.woo committed
1022 1023 1024 1025 1026
                .collect(Collectors.toList());
        if (query.isEmpty()) {
            return;
        }
        query.stream().forEach(item -> {
1027 1028
            childrenOrgIdList.add(item.getId());
            getChildrenOrgIdRecursion(item.getId(), childrenOrgIdList, orgList);
eddie.woo's avatar
eddie.woo committed
1029 1030 1031 1032 1033 1034 1035 1036 1037
        });
    }

    public List<DimensionValueOrgDto> getDimensionValueOrgDtoList() {
        return organizationMapper.getDimensionValueOrgDtoList();
    }

    /**
     * 由于C#中OrganizationService.cs line 2356~2357以下代码被注释,故JAVA中未join
1038
     * statDimension表做联合查询。 join sd in stat Dimension on d.id equals sd.DimensionId
eddie.woo's avatar
eddie.woo committed
1039 1040 1041 1042 1043 1044 1045
     * from sdTp in sdTemp.DefaultIfEmpty()
     */
    private List<OrganizationDto> getCustomDimensionOrgList() {
        return organizationMapper.getCustomDimensionOrgList();
    }

    private void populateUserRoleBasic(List<UserDimensionValue> userDimensionValueList,
1046 1047 1048
                                       List<UserDimensionValueOrg> userDimensionValueOrgList, List<UserOrganization> userOrganizationList,
                                       List<UserOrgRoleDto> originalRoleList, List<UserOrgRoleDto> userDimensionValueRoleList,
                                       List<UserOrgRoleDto> userOrganizationRoleList) {
eddie.woo's avatar
eddie.woo committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

        userDimensionValueList.addAll(userDimensionValueMapper.getUserDimensionValueList());
        userDimensionValueOrgList
                .addAll(userDimensionValueOrgMapper.selectByExample(new UserDimensionValueOrgExample()));
        userOrganizationList.addAll(userOrganizationMapper.getUserOrganizationList());
        /*
         * .NET中以下代码单纯从数据库查询出role表并join下列表进行联合查询,JAVA中将该逻辑直接在MapperXML中表达 var roleList =
         * (from r in this._dbContext.Set<Role>() select r);
         */
        originalRoleList.addAll(userRoleMapper.getOriginalRoleList());
        userDimensionValueRoleList.addAll(userDimensionValueRoleMapper.getUserDimensionValueRoleList());
        userOrganizationRoleList.addAll(userOrganizationRoleMapper.getUserOrganizationRoleList());
    }

    private void addToDimensionValueList(OrganizationDto orgDto, List<DimensionValueDisplayDto> dimensionValueList) {
1064 1065 1066
        // 判定当Dimension List中没有任何一个DimensionValueId 与传入的Organization相等时执行
        Boolean hasValueWithDimensionValueId = !dimensionValueList.stream()
                .anyMatch(dv -> Objects.equals(orgDto.getDimensionValueId(), dv.getDimensionValueId()));
eddie.woo's avatar
eddie.woo committed
1067

1068
        if (StringUtils.isNotEmpty(orgDto.getDimensionId()) && hasValueWithDimensionValueId) {
eddie.woo's avatar
eddie.woo committed
1069
            DimensionValueDisplayDto dValue = new DimensionValueDisplayDto();
1070
            dValue.setDimensionValueId(orgDto.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
1071 1072 1073 1074 1075
            dValue.setDimensionValueName(orgDto.getDimensionValueName());
            dimensionValueList.add(dValue);
        }
    }

1076
    private List<OrganizationDto> getOrgDimensionMappingForDimension(String dimensionId) {
eddie.woo's avatar
eddie.woo committed
1077
        List<OrganizationDto> basicQuery = new ArrayList<>();
1078
        DimensinTypeOrgDto dimensionDto = dimensionService.getDimensionById(dimensionId);
eddie.woo's avatar
eddie.woo committed
1079 1080 1081 1082
        Integer dimensionType = dimensionDto.getDimensionType();
        List<OrganizationDto> query = basicQuery;
        if (DimensionTypeEnum.BusinessUnit.value().equals(dimensionType)) {
            basicQuery = getBusinessUnitListJoinResult();
1083
            query = basicQuery.stream().map(bQuery -> transBUAndOSCResult(bQuery, dimensionId, dimensionDto)).distinct()
eddie.woo's avatar
eddie.woo committed
1084 1085 1086
                    .collect(Collectors.toList());
        } else if (DimensionTypeEnum.OrgSubChildren.value().equals(dimensionType)) {
            basicQuery = getOrganizationJoinResult();
1087
            query = basicQuery.stream().map(bQuery -> transBUAndOSCResult(bQuery, dimensionId, dimensionDto)).distinct()
eddie.woo's avatar
eddie.woo committed
1088 1089
                    .collect(Collectors.toList());
        } else if (DimensionTypeEnum.SelfDimension.value().equals(dimensionType)) {
1090
            // query = dimensionMapper.getBusinessUnitListJoinDimensionResult(dimensionId,
eddie.woo's avatar
eddie.woo committed
1091 1092
            // true).stream()
            // .map(this::filterOrgDtoNullValueForSelfDimension).collect(Collectors.toList());
1093
            query = dimensionMapper.getBusinessUnitListJoinDimensionResult(dimensionId, true);
eddie.woo's avatar
eddie.woo committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
        } else {
            /**
             * C#中源代码将查询结果赋值给basicQuery未做任何后续传出处理,无意义 basicQuery =
             * getOrganizationJoinResult();
             */
        }
        return query;
    }

    private List<OrganizationDto> getBusinessUnitListJoinResult() {
        return businessUnitMapper.getBusinessUnitListJoinResult();
    }

    // private OrganizationDto filterOrgDtoNullValue(OrganizationDto orgDto) {
    // orgDto.setStructureName(orgDto.getStructureName() == null ? "" :
    // orgDto.getStructureName());
1110 1111 1112
    // orgDto.setIndustryId(orgDto.getIndustryId() == null ? "" :
    // orgDto.getIndustryId());
    // orgDto.setRegionId(orgDto.getRegionId() == null ? "" : orgDto.getRegionId());
eddie.woo's avatar
eddie.woo committed
1113 1114
    // orgDto.setRegionName(orgDto.getRegionName() == null ? "" :
    // orgDto.getRegionName());
1115 1116 1117
    // orgDto.setStructureId(orgDto.getStructureId() == null ? "" :
    // orgDto.getStructureId());
    // orgDto.setAreaId(orgDto.getAreaId() == null ? "" : orgDto.getAreaId());
eddie.woo's avatar
eddie.woo committed
1118 1119 1120 1121
    // orgDto.setAreaName(orgDto.getAreaName() == null ? "" : orgDto.getAreaName());
    // orgDto.setClientCode(orgDto.getClientCode() == null ? "" :
    // orgDto.getClientCode());
    // orgDto.setCode(orgDto.getCode() == null ? "" : orgDto.getCode());
1122
    // orgDto.setParentId(orgDto.getParentId() == null ? "" : orgDto.getParentId());
eddie.woo's avatar
eddie.woo committed
1123 1124 1125 1126
    // orgDto.setpLevel(orgDto.getpLevel() == null ? 0 : orgDto.getpLevel());
    // return orgDto;
    // }

1127
    private OrganizationDto transBUAndOSCResult(OrganizationDto rawDto, String dimensionId,
1128
                                                DimensinTypeOrgDto dimensionDto) {
eddie.woo's avatar
eddie.woo committed
1129
        OrganizationDto newDto = new OrganizationDto();
1130
        newDto.setBusinessUnitId(rawDto.getBusinessUnitId());
eddie.woo's avatar
eddie.woo committed
1131
        newDto.setBusinessUnitName(rawDto.getBusinessUnitName());
1132
        newDto.setId(rawDto.getId());
eddie.woo's avatar
eddie.woo committed
1133
        newDto.setName(rawDto.getName());
1134
        newDto.setDimensionId(dimensionId);
eddie.woo's avatar
eddie.woo committed
1135
        newDto.setDimensionName(dimensionDto.getName());
1136
        newDto.setDimensionValueId(rawDto.getBusinessUnitId());
eddie.woo's avatar
eddie.woo committed
1137 1138
        newDto.setDimensionValueName(rawDto.getBusinessUnitName());

1139 1140
        newDto.setAttributeId(rawDto.getAttributeId());
        newDto.setIndustryId(rawDto.getIndustryId());
eddie.woo's avatar
eddie.woo committed
1141
        newDto.setIndustryName(rawDto.getIndustryName());
1142
        newDto.setRegionId(rawDto.getRegionId());
eddie.woo's avatar
eddie.woo committed
1143
        newDto.setRegionName(rawDto.getRegionName());
1144 1145
        newDto.setStructureId(rawDto.getStructureId());
        newDto.setAreaId(rawDto.getAreaId());
eddie.woo's avatar
eddie.woo committed
1146 1147 1148
        newDto.setAreaName(rawDto.getAreaName());
        newDto.setClientCode(rawDto.getClientCode());
        newDto.setCode(rawDto.getCode());
1149
        newDto.setParentId(rawDto.getParentId());
1150
        newDto.setpLevel(rawDto.getpLevel());
eddie.woo's avatar
eddie.woo committed
1151 1152 1153 1154
        newDto.setTaxPayerNumber(rawDto.getTaxPayerNumber());

        // OrganizationDto newDto = CommonUtils.copyProperties(rawDto, new
        // OrganizationDto());
1155
        // newDto.setDimensionId(dimensionId);
eddie.woo's avatar
eddie.woo committed
1156
        // newDto.setDimensionName(dimensionDto.getName());
1157
        // newDto.setDimensionValueId(rawDto.getBusinessUnitId());
eddie.woo's avatar
eddie.woo committed
1158 1159 1160 1161 1162 1163 1164
        // newDto.setDimensionValueName(rawDto.getBusinessUnitName());
        // newDto.setStructureName(null);
        return newDto;
    }

    // private OrganizationDto filterOrgDtoNullValueForSelfDimension(OrganizationDto
    // orgDto) {
1165
    // orgDto.setId(orgDto.getId() == null ? "" : orgDto.getId());
eddie.woo's avatar
eddie.woo committed
1166 1167
    // orgDto.setName(orgDto.getName() == null ? "" : orgDto.getName());
    // orgDto.setpLevel(orgDto.getpLevel() == null ? 0 : orgDto.getpLevel());
1168
    // orgDto.setParentId(orgDto.getParentId() == null ? "" : orgDto.getParentId());
eddie.woo's avatar
eddie.woo committed
1169 1170 1171 1172 1173 1174
    // orgDto.setCode(orgDto.getCode() == null ? "" : orgDto.getCode());
    // orgDto.setClientCode(orgDto.getClientCode() == null ? "" :
    // orgDto.getClientCode());
    // orgDto.setBusinessUnitName(orgDto.getBusinessUnitName() == null ? "" :
    // orgDto.getBusinessUnitName());
    // orgDto.setAreaName(orgDto.getAreaName() == null ? "" : orgDto.getAreaName());
1175 1176 1177
    // orgDto.setAreaId(orgDto.getAreaId() == null ? "" : orgDto.getAreaId());
    // orgDto.setStructureId(orgDto.getStructureId() == null ? "" :
    // orgDto.getStructureId());
eddie.woo's avatar
eddie.woo committed
1178 1179
    // orgDto.setRegionName(orgDto.getRegionName() == null ? "" :
    // orgDto.getRegionName());
1180
    // orgDto.setRegionId(orgDto.getRegionId() == null ? "" : orgDto.getRegionId());
eddie.woo's avatar
eddie.woo committed
1181 1182
    // orgDto.setIndustryName(orgDto.getIndustryName() == null ? "" :
    // orgDto.getIndustryName());
1183 1184 1185
    // orgDto.setIndustryId(orgDto.getIndustryId() == null ? "" :
    // orgDto.getIndustryId());
    // orgDto.setBusinessUnitId(orgDto.getBusinessUnitId() == null ? "" :
eddie.woo's avatar
eddie.woo committed
1186
    // orgDto.getStructureName());
1187 1188
    // orgDto.setAttributeId(orgDto.getAttributeId() == null ? "" :
    // orgDto.getAttributeId());
eddie.woo's avatar
eddie.woo committed
1189 1190 1191
    // return orgDto;
    // }

1192
    public List<OrganizationDto> getOrganizationListByAreaId(String areaId, String attributeId) {
eddie.woo's avatar
eddie.woo committed
1193 1194 1195 1196 1197 1198 1199 1200

        List<AreaRegionDto> provinceRegionList = areaRegionMapper
                .selectByRegionLevelType(CommonConstants.REGION_LEVELTYPE_PROVINCE);

        List<Organization> organizationList = organizationMapper.selectByExample(null);
        List<OrganizationDto> allList = new ArrayList<>();
        organizationList.forEach(a -> {
            OrganizationDto organizationDto = new OrganizationDto();
1201 1202
            organizationDto.setId(a.getId());
            organizationDto.setParentId(a.getParentId());
eddie.woo's avatar
eddie.woo committed
1203 1204 1205 1206
            organizationDto.setName(a.getName());
            allList.add(organizationDto);
        });

1207
        List<OrganizationDto> orgList = organizationMapper.selectIndBusUnitAreaOrgStrctReg(true, areaId,
eddie.woo's avatar
eddie.woo committed
1208 1209 1210 1211 1212
                CommonConstants.REGION_LEVELTYPE_CITY);
        orgList.forEach(a -> {
            if (StringUtils.isNotEmpty(a.getParentName())) {
                List<AreaRegionDto> areaRegionList = new ArrayList<>();
                provinceRegionList.forEach(b -> {
1213
                    if (StringUtils.equals(b.getRegionId(), a.getParentName()))
eddie.woo's avatar
eddie.woo committed
1214 1215 1216 1217 1218 1219 1220
                        areaRegionList.add(b);
                });
                String provinceName = areaRegionList.isEmpty() ? null : areaRegionList.get(0).getRegionName();
                if (!StringUtils.equals(a.getRegionName(), provinceName)) {
                    a.setRegionName(provinceName + a.getRegionName());
                }
            }
1221
            a.setParentId(getParentId(a, allList, orgList));
eddie.woo's avatar
eddie.woo committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
        });

        return orgList;
    }

    public AreaOrganizationStatistics getAreaStatistics() {
        AreaExample example = new AreaExample();
        example.createCriteria().andIsActiveEqualTo(true);
        List<Area> areaList = areaMapper.selectByExample(example);

1232
        List<Area> firstRegionLevelList = areaList.stream().filter(sa -> sa.getParentId() == null).collect(toList());
eddie.woo's avatar
eddie.woo committed
1233 1234
        List<AreaRegionDto> provinceRegionList = areaRegionMapper
                .selectByRegionLevelType(AreaConstant.LevelTypeProvince);
1235 1236
        // 保证AreaId不为null
        provinceRegionList.stream().forEach(x -> x.setAreaId(Strings.sBlank(x.getAreaId())));
eddie.woo's avatar
eddie.woo committed
1237 1238 1239 1240 1241 1242 1243 1244

        OrganizationExample exampleOrg = new OrganizationExample();
        exampleOrg.createCriteria().andIsActiveEqualTo(true);
        List<OrganizationStatistics> orgList = organizationMapper.selectByExample(exampleOrg).stream()
                .map(this::convertToOrganizationStatistics).collect(toList());

        List<OrganizationDto> orgDtoList = orgList.stream().map(from -> {
            OrganizationDto to = new OrganizationDto();
1245 1246
            to.setAreaId(from.getAreaId());
            to.setId(from.getId());
eddie.woo's avatar
eddie.woo committed
1247
            to.setName(from.getName());
1248
            to.setBusinessUnitId(from.getBusinessUnitId());
eddie.woo's avatar
eddie.woo committed
1249 1250 1251 1252 1253 1254
            return to;
        }).collect(toList());

        List<DimensionValueOrgDto> dimensionValueOrgList = getDimensionValueOrgDtoList();

        Map<String, Integer> areaUserCount = roleService.getActiveUserRoleList(orgDtoList, dimensionValueOrgList,
1255
                DimensionConstant.AreaId);
eddie.woo's avatar
eddie.woo committed
1256 1257 1258

        List<AreaStatistics> areaRetList = new ArrayList<>();
        List<StatisticAttributeDisplayDto> rawAttrList = new ArrayList<>();
1259
        statisticAttributeService.getStatisticAttributeListByDimensionId(DimensionConstant.AreaId, rawAttrList);
eddie.woo's avatar
eddie.woo committed
1260 1261 1262

        for (Area item : firstRegionLevelList) {
            AreaStatistics areaStatics = new AreaStatistics();
1263
            areaStatics.setId(item.getId());
eddie.woo's avatar
eddie.woo committed
1264 1265
            areaStatics.setName(item.getName());

1266
            Map<String, Integer> tmpAttributeStatics = getAttributeStaticsByAreaId(item.getId(), orgList, rawAttrList,
eddie.woo's avatar
eddie.woo committed
1267 1268 1269
                    areaUserCount, dimensionValueOrgList);
            areaStatics.setAttributeStatics(tmpAttributeStatics);

1270
            List<String> provinceNameList = getProvinceNameList(item.getId(), provinceRegionList, areaList);
eddie.woo's avatar
eddie.woo committed
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
            areaStatics.setProvinceNameList(provinceNameList.stream().distinct().collect(toList()));
            areaRetList.add(areaStatics);
        }

        AreaOrganizationStatistics result = new AreaOrganizationStatistics();
        result.setAreaList(areaRetList);
        result.setAttributeList(rawAttrList);
        return result;
    }

1281
    private List<String> getProvinceNameList(String areaId, List<AreaRegionDto> provinceList, List<Area> areaList) {
eddie.woo's avatar
eddie.woo committed
1282
        // 找到城市列表
1283
        List<AreaRegionDto> citys = provinceList.stream().filter(sa -> Objects.equals(areaId, sa.getAreaId()))
eddie.woo's avatar
eddie.woo committed
1284 1285 1286 1287 1288 1289
                .collect(toList());
        List<String> retList = new ArrayList<>();
        if (!Lang.isEmpty(citys)) {
            List<String> tmpList = citys.stream().map(AreaRegionDto::getRegionName).distinct().collect(toList());
            retList.addAll(tmpList);
        }
1290
        List<Area> subArea = areaList.stream().filter(sa -> Objects.equals(areaId, sa.getParentId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
1291
        for (Area sub : subArea) {
1292
            List<String> tempCitys = getProvinceNameList(sub.getId(), provinceList, areaList);
eddie.woo's avatar
eddie.woo committed
1293 1294 1295 1296 1297 1298 1299
            if (!Lang.isEmpty(tempCitys))
                retList.addAll(tempCitys);

        }
        return retList;
    }

1300
    private Map<String, Integer> getAttributeStaticsByAreaId(String areaId, List<OrganizationStatistics> allOrgList,
1301 1302
                                                             List<StatisticAttributeDisplayDto> rawAttrList, Map<String, Integer> areaUserCount,
                                                             List<DimensionValueOrgDto> dimensionValueOrgList) {
1303 1304
        int userCount = Optional.ofNullable(areaUserCount.get(areaId)).orElse(0);
        List<OrganizationStatistics> orgList = allOrgList.stream().filter(sa -> Objects.equals(areaId, sa.getAreaId()))
eddie.woo's avatar
eddie.woo committed
1305 1306 1307 1308
                .collect(toList());
        // 机构数,用户数,区域,事业部,行业,地区
        List<DimensionValueOrgDto> selfDimensionList = dimensionValueOrgList.stream().filter(
                (DimensionValueOrgDto sa) -> rawAttrList.stream().anyMatch((StatisticAttributeDisplayDto sb) -> Objects
1309
                        .equals(sb.getBelongDimensionId(), sa.getDimensionId())))
eddie.woo's avatar
eddie.woo committed
1310 1311 1312 1313 1314 1315 1316 1317
                .collect(toList());
        Map<String, Integer> dic = new HashMap<>();
        for (StatisticAttributeDisplayDto item : rawAttrList) {
            if (AttributeTypeEnum.User.value().equals(item.getAttributeType())) {
                // 用户数
                item.setCount(userCount);
            } else if (AttributeTypeEnum.OrgSubChildren.value().equals(item.getAttributeType())) {
                // 机构数
1318
                item.setCount((int) allOrgList.stream().filter(sa -> Objects.equals(areaId, sa.getAreaId())).count());
eddie.woo's avatar
eddie.woo committed
1319 1320 1321
            } else if (AttributeTypeEnum.SelfDimension.value().equals(item.getAttributeType())) {
                // 自定义区域
                item.setCount((int) selfDimensionList.stream()
1322 1323
                        .filter(sa -> Objects.equals(item.getBelongDimensionId(), sa.getDimensionId()))
                        .map(DimensionValueOrgDto::getDimensionValueId).distinct().count());
eddie.woo's avatar
eddie.woo committed
1324 1325
            } else if (AttributeTypeEnum.Industry.value().equals(item.getAttributeType())) {
                // 行业
1326 1327 1328
                item.setCount((int) orgList.stream().filter(sa -> sa.getIndustryId() != null)
                        .map(OrganizationStatistics::getIndustryId).distinct().count());
            } else if (AttributeTypeEnum.RegionId.value().equals(item.getAttributeType())) {
eddie.woo's avatar
eddie.woo committed
1329
                // 行政地区
1330 1331
                item.setCount((int) orgList.stream().filter(sa -> sa.getCityId() != null)
                        .map(OrganizationStatistics::getCityId).distinct().count());
eddie.woo's avatar
eddie.woo committed
1332 1333 1334 1335 1336
            } else if (AttributeTypeEnum.Area.value().equals(item.getAttributeType())) {
                // 区域维度
                item.setCount(1);
            } else if (AttributeTypeEnum.BusinessUnit.value().equals(item.getAttributeType())) {
                // 事业部
1337 1338
                item.setCount((int) orgList.stream().filter(sa -> sa.getBusinessUnitId() != null)
                        .map(OrganizationStatistics::getBusinessUnitId).distinct().count());
eddie.woo's avatar
eddie.woo committed
1339
            } else if (AttributeTypeEnum.OrganizationStructure.value().equals(item.getAttributeType())) {
1340 1341
                item.setCount((int) orgList.stream().filter(sa -> sa.getStructureId() != null)
                        .map(OrganizationStatistics::getStructureId).distinct().count());
eddie.woo's avatar
eddie.woo committed
1342
            }
1343
            dic.put(item.getAttributeId(), item.getCount());
eddie.woo's avatar
eddie.woo committed
1344 1345 1346 1347 1348 1349 1350 1351 1352
        }

        return dic;
    }

    private OrganizationStatistics convertToOrganizationStatistics(Organization from) {
        OrganizationStatistics to = new OrganizationStatistics();
        to.setUserCount(0);
        to.setName(from.getName());
1353 1354 1355 1356 1357 1358 1359
        to.setId(from.getId());
        to.setBusinessUnitId(from.getBusinessUnitId());
        to.setCityId(from.getRegionId());
        to.setIndustryId(from.getIndustryId());
        to.setParentId(from.getParentId());
        to.setStructureId(from.getStructureId());
        to.setAreaId(from.getAreaId());
eddie.woo's avatar
eddie.woo committed
1360 1361 1362
        return to;
    }

1363 1364
    /**
     */
1365 1366 1367 1368
    public OrgDto getOrgCustomDashbord(final String dimensionValueId, final String parentDimensionId,
                                       final String attributeId) {
        Assert.hasText(parentDimensionId, "Empty parentDimensionId");
        Assert.hasText(dimensionValueId, "Empty dimensionValueId");
eddie.woo's avatar
eddie.woo committed
1369
        OrgDto orgDto = new OrgDto();
1370
        List<OrganizationDto> orgDtoList = getOrgCustomDashbord$getOrgDtoList(dimensionValueId, parentDimensionId);
eddie.woo's avatar
eddie.woo committed
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
        List<OrganizationDto> orgDtoTempList = new ArrayList<>();

        List<OrganizationDto> orgTemp = getCustomDimensionOrgList();
        // join 两个变量:orgDtoList, orgTemp
        logger.debug("join 两个变量:orgDtoList, size[{}] orgTemp, size[{}]", orgDtoList.size(), orgTemp.size());
        // 代码理解:join的结果就是取orgTemp的字段,加上orgDtoTempList的name字段
        // 疑问:orgTemp的name字段与orgDtoTempList的name字段有什么区别?应该都是等价于Organization.name?
        List<OrgCustomDto> customOrgList = new ArrayList<>();
        for (OrganizationDto p : orgDtoList) {
            for (OrganizationDto d : orgTemp) {
1381 1382
                if (d.getId() != null && d.getId().equals(p.getId())) {
                    // on p.id equals d.id
eddie.woo's avatar
eddie.woo committed
1383
                    OrgCustomDto tmp = new OrgCustomDto();
1384
                    tmp.setAttributeId(d.getAttributeId());
eddie.woo's avatar
eddie.woo committed
1385
                    tmp.setAttributeName(d.getAttributeName());
1386
                    tmp.setDimensionId(d.getDimensionId());
eddie.woo's avatar
eddie.woo committed
1387
                    tmp.setDimensionName(d.getDimensionName());
1388
                    tmp.setDimensionValueId(d.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
1389
                    tmp.setDimensionValueName(d.getDimensionValueName());
1390
                    tmp.setOrgId(p.getId()); // 其实就是d.getId()
eddie.woo's avatar
eddie.woo committed
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
                    tmp.setOrgName(p.getName()); // 只有orgName使用了p.name
                    customOrgList.add(tmp);
                }
            }
        }
        orgDto.setOrgCustomDtoList(customOrgList);
        orgDto.setOrgCountList(new ArrayList<>());
        orgDto.setOrgDtoList(new ArrayList<>());

        // 如果是事业部
1401 1402
        if (attributeId.toLowerCase().equals(DimensionConstant.Attribute.BusinessUnitId)) {
            getOrgCustomDashbord$BusinessUnitId(orgDto, orgDtoList, orgDtoTempList);
eddie.woo's avatar
eddie.woo committed
1403 1404
        }
        // 如果是所属行业
1405 1406
        else if (attributeId.toLowerCase().equals(DimensionConstant.Attribute.IndustryId)) {
            getOrgCustomDashbord$IndustryId(orgDto, orgDtoList, orgDtoTempList);
eddie.woo's avatar
eddie.woo committed
1407 1408
        }
        // 如果是机构数
1409 1410
        else if (attributeId.toLowerCase().equals(DimensionConstant.Attribute.OrgSubChildrenId)) {
            getOrgCustomDashbord$OrgSubChildrenId(orgDto, orgDtoList, orgDtoTempList);
eddie.woo's avatar
eddie.woo committed
1411 1412
        }
        // 如果是机构层级
1413 1414
        else if (attributeId.toLowerCase().equals(DimensionConstant.Attribute.OrganizationStructureId)) {
            getOrgCustomDashbord$OrganizationStructureId(orgDto, orgDtoList, orgDtoTempList);
eddie.woo's avatar
eddie.woo committed
1415 1416
        }
        // 覆盖区域
1417 1418
        else if (attributeId.toLowerCase().equals(DimensionConstant.Attribute.AreaId)) {
            getOrgCustomDashbord$AreaId(orgDto, orgDtoList, orgDtoTempList);
eddie.woo's avatar
eddie.woo committed
1419 1420 1421
        }
        // 如果是自定义属性,维度值的列表,多少维度,如产品维度,值为产品1,产品2,产品3 等
        else {
1422
            getOrgCustomDashbord$DimensionValueId(attributeId, orgDto, orgDtoList, orgDtoTempList, orgTemp);
eddie.woo's avatar
eddie.woo committed
1423 1424
        }

1425
        if (attributeId.toLowerCase().equals(DimensionConstant.Attribute.OrgSubChildrenId)) {
eddie.woo's avatar
eddie.woo committed
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
            List<OrgDisplayDto> tmplist = populateOrgLevel(orgDtoTempList);
            orgDto.setOrgDtoList(tmplist);
        } else {
            List<OrgDisplayDto> tmplist = orgDtoTempList.stream().map(this::convertToOrgDisplayDto).collect(toList());
            orgDto.setOrgDtoList(tmplist);
        }

        return orgDto;
    }

1436
    public void getOrgCustomDashbord$DimensionValueId(final String attributeId, OrgDto orgDto,
1437
                                                      List<OrganizationDto> orgDtoList, List<OrganizationDto> orgDtoTempList, List<OrganizationDto> orgTemp) {
eddie.woo's avatar
eddie.woo committed
1438 1439 1440 1441 1442
        // 把orgDtoList LEFT JION orgTemp 放到customFilter变量
        List<OrgCustomDto> customFilter = new ArrayList<>();
        for (OrganizationDto p : orgDtoList) {
            for (OrganizationDto d : orgTemp) {
                OrganizationDto dtp = null;
1443
                if (Objects.equals(d.getAttributeId(), attributeId) && Objects.equals(d.getId(), p.getId())) {
eddie.woo's avatar
eddie.woo committed
1444 1445 1446
                    dtp = d;
                }
                OrgCustomDto joinItem = new OrgCustomDto();
1447
                joinItem.setDimensionId(dtp == null ? "" : dtp.getDimensionId());
eddie.woo's avatar
eddie.woo committed
1448
                joinItem.setDimensionName(dtp == null ? "" : dtp.getDimensionName());
1449
                joinItem.setDimensionValueId(dtp == null ? "" : dtp.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
1450
                joinItem.setDimensionValueName(dtp == null ? "" : dtp.getDimensionValueName());
1451
                joinItem.setOrgId(p.getId());
eddie.woo's avatar
eddie.woo committed
1452 1453 1454 1455 1456 1457 1458 1459
                joinItem.setOrgName(p.getName());
                customFilter.add(joinItem);
            }
        }
        customFilter = customFilter.stream().distinct().collect(toList());

        List<Map<String, String>> dimensionValueList = customFilter.stream().map((x) -> {
            Map<String, String> map = new HashMap<>();
1460
            map.put("id", x.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
            map.put("Name", x.getDimensionValueName());
            return map;
        }).distinct().collect(toList());

        for (Map<String, String> val : dimensionValueList) {
            OrganizationDto orgdto = new OrganizationDto();
            orgdto.setName(val.get("Name"));
            orgdto.setLevel(LevelConstant.FirstLevel);
            // 加入第0级节点
            orgDtoTempList.add(orgdto);

1472 1473
            // Group by id (DimensionValueId)
            // 代码分析:目的是为了找出OrgId的集合 groupList.item.getOrgId
eddie.woo's avatar
eddie.woo committed
1474
            List<OrgCustomDto> groupList = customFilter.stream()
1475
                    .filter(x -> Objects.equals(val.get("id"), x.getDimensionValueId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
1476

1477
            // 代码分析:通过OrgId的集合,把原始的Org集合选出来
eddie.woo's avatar
eddie.woo committed
1478
            groupList.forEach(g -> {
1479
                orgDtoList.stream().filter(s -> Objects.equals(s.getId(), g.getOrgId())).forEach(r -> {
eddie.woo's avatar
eddie.woo committed
1480 1481 1482 1483 1484 1485
                    r.setLevel(LevelConstant.FirstLevel + 1);
                    orgDtoTempList.add(r);
                });
            });

            boolean noneMatch = orgDto.getOrgCountList().stream()
1486
                    .noneMatch(x -> Objects.equals(val.get("id"), x.getId()));
eddie.woo's avatar
eddie.woo committed
1487 1488
            if (noneMatch) {
                OrgCountDto org = new OrgCountDto();
1489
                org.setId(val.get("id"));
eddie.woo's avatar
eddie.woo committed
1490 1491
                org.setName(val.get("Name"));
                org.setCount((int) customFilter.stream()
1492
                        .filter(s -> Objects.equals(val.get("id"), s.getDimensionValueId())).count());
eddie.woo's avatar
eddie.woo committed
1493 1494 1495 1496 1497 1498 1499 1500 1501
                orgDto.getOrgCountList().add(org);
            }
        }
    }

    private List<OrgDisplayDto> populateOrgLevel(List<OrganizationDto> orgDtoList) {
        List<OrgDisplayDto> displayList = new ArrayList<>();

        // FIXME C#中可能有Bug, SQL字段少了IsActive, 先照原样复制过来
1502 1503
        // SELECT id, ParentId from Organization
        List<OrganizationDto> orgList = organizationMapper.selectOnlyIdAndParentId();
eddie.woo's avatar
eddie.woo committed
1504
        for (OrganizationDto item : orgDtoList) {
1505
            if (item.getParentId() == null)
eddie.woo's avatar
eddie.woo committed
1506 1507 1508
                continue;

            // 找到了parentId
1509
            boolean foundParentId = orgDtoList.stream().anyMatch(x -> item.getParentId().equals(x.getId()));
eddie.woo's avatar
eddie.woo committed
1510 1511 1512
            if (foundParentId)
                continue;

1513 1514
            // 重新设置ParentId
            item.setParentId(getParentId(item, orgList, orgDtoList));
eddie.woo's avatar
eddie.woo committed
1515 1516 1517 1518
        }

        List<OrganizationDto> topList = orgDtoList.stream().filter(p -> {
            return orgDtoList.stream().noneMatch(sa -> {
1519
                return Objects.equals(sa.getId(), p.getParentId());
eddie.woo's avatar
eddie.woo committed
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
            });
        }).collect(toList());

        for (OrganizationDto top : topList) {
            top.setLevel(LevelConstant.FirstLevel);
            OrgDisplayDto display = convertToOrgDisplayDto(top);
            displayList.add(display);
            List<OrgDisplayDto> subList = getChildren(top, orgDtoList);
            displayList.addAll(subList);
        }

        return displayList;
    }

    private List<OrgDisplayDto> getChildren(OrganizationDto current, List<OrganizationDto> orgList) {
        List<OrgDisplayDto> retList = new ArrayList<>();
1536
        List<OrganizationDto> subList = orgList.stream().filter(sa -> Objects.equals(sa.getParentId(), current.getId()))
eddie.woo's avatar
eddie.woo committed
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
                .collect(toList());
        subList.forEach(item -> {
            item.setLevel(LevelConstant.FirstLevel + 1);
            retList.add(convertToOrgDisplayDto(item));
            List<OrgDisplayDto> children = getChildren(item, orgList);
            if (Lang.isEmpty(children)) {
                // 疑问: C#代码中,为什么把level设为0?
                item.setLevel(LevelConstant.FirstLevel);
            }
            retList.addAll(children);
        });

        return retList;
    }

1552
    private String getParentId(OrganizationDto current, List<OrganizationDto> allList,
1553
                               List<OrganizationDto> orgDtoList) {
1554
        if (current.getParentId() == null)
eddie.woo's avatar
eddie.woo committed
1555 1556
            return null;

1557 1558
        // 这个是为了处理脏数据,那种Id 和 ParentId 是一样的情况
        if (current.getParentId().equals(current.getId()))
eddie.woo's avatar
eddie.woo committed
1559 1560 1561
            return null;

        // 代码理解:从全量中找到父节点
1562
        OrganizationDto findParent = allList.stream().filter(sa -> current.getParentId().equals(sa.getId())).findFirst()
eddie.woo's avatar
eddie.woo committed
1563 1564 1565 1566 1567 1568 1569 1570
                .orElse(null);

        // 处理脏数据
        if (findParent == null)
            return null;

        if (BooleanUtils.isTrue(findParent.getIsActive())) {
            // 代码理解:从目标集合中找到这个节点
1571
            OrganizationDto parent = orgDtoList.stream().filter(sa -> Objects.equals(sa.getId(), findParent.getId()))
eddie.woo's avatar
eddie.woo committed
1572 1573
                    .findFirst().orElse(null);
            if (parent != null)
1574
                return parent.getId();
eddie.woo's avatar
eddie.woo committed
1575
        }
1576
        return getParentId(findParent, allList, orgDtoList);
eddie.woo's avatar
eddie.woo committed
1577 1578 1579 1580
    }

    private OrgDisplayDto convertToOrgDisplayDto(OrganizationDto from) {
        OrgDisplayDto to = copyProperties(from, new OrgDisplayDto());
1581
        to.setPLevel(from.getpLevel());
eddie.woo's avatar
eddie.woo committed
1582
        to.setOrgName(from.getName());
1583
        to.setOrgId(from.getId());
eddie.woo's avatar
eddie.woo committed
1584 1585 1586 1587 1588 1589 1590
        to.setPLevel(Optional.ofNullable(to.getPLevel()).orElse(0));
        to.setLevel(Optional.ofNullable(to.getLevel()).orElse(0));
        to.setSubsidiaryCount(Optional.ofNullable(to.getSubsidiaryCount()).orElse(0));
        to.setAreaCount(Optional.ofNullable(to.getAreaCount()).orElse(0));
        return to;
    }

1591 1592 1593
    /**
     * 从getOrgCustomDashbord抽取出来的方法
     */
1594
    private void getOrgCustomDashbord$OrgSubChildrenId(OrgDto orgDto, List<OrganizationDto> orgDtoList,
1595
                                                       List<OrganizationDto> orgDtoTempList) {
eddie.woo's avatar
eddie.woo committed
1596 1597 1598 1599 1600 1601
        // 删除无用的dimensionValueList变量
        orgDtoTempList.clear();
        // C#的代码是改变指针,这里改为clear, addAll
        orgDtoTempList.addAll(orgDtoList);
        OrgCountDto org = new OrgCountDto();
        org.setName(OrganizationMessage.OrganizationCount);
1602
        // 统计businessUnitId数量
eddie.woo's avatar
eddie.woo committed
1603 1604 1605 1606
        org.setCount(orgDtoList.size());
        orgDto.getOrgCountList().add(org);
    }

1607 1608 1609
    /**
     * 从getOrgCustomDashbord抽取出来的方法
     */
1610
    private void getOrgCustomDashbord$AreaId(OrgDto orgDto, List<OrganizationDto> orgDtoList,
1611
                                             List<OrganizationDto> orgDtoTempList) {
1612
        // 找出IndustryId的列表,去重复
eddie.woo's avatar
eddie.woo committed
1613 1614
        List<Map<String, String>> dimensionValueList = orgDtoList.stream().map((OrganizationDto x) -> {
            Map<String, String> map = new HashMap<>();
1615
            map.put("id", x.getAreaId());
eddie.woo's avatar
eddie.woo committed
1616 1617 1618 1619
            map.put("Name", x.getAreaName());
            return map;
        }).distinct().collect(toList());

1620
        // 遍历BU Id的列表
eddie.woo's avatar
eddie.woo committed
1621 1622 1623 1624 1625 1626 1627 1628 1629
        for (Map<String, String> val : dimensionValueList) {
            OrganizationDto orgdto = new OrganizationDto();
            orgdto.setName(val.get("Name"));
            orgdto.setLevel(LevelConstant.FirstLevel);
            // 加入第0级节点
            orgDtoTempList.add(orgdto);

            // 找出这个BU对应的OrganizationDto列表
            List<OrganizationDto> groupList = orgDtoList.stream()
1630
                    .filter(x -> Objects.equals(val.get("id"), x.getAreaId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
1631 1632 1633 1634 1635 1636 1637 1638

            groupList.forEach((OrganizationDto r) -> {
                r.setLevel(LevelConstant.FirstLevel + 1);
                // 加入第1级节点
                orgDtoTempList.add(r);
            });

            boolean noSuchItemById = orgDto.getOrgCountList().stream()
1639
                    .noneMatch(x -> Objects.equals(val.get("id"), x.getId()));
eddie.woo's avatar
eddie.woo committed
1640 1641
            if (noSuchItemById) {
                OrgCountDto org = new OrgCountDto();
1642
                org.setId(val.get("id"));
eddie.woo's avatar
eddie.woo committed
1643
                org.setName(val.get("Name"));
1644
                // 统计businessUnitId数量
eddie.woo's avatar
eddie.woo committed
1645
                org.setCount(
1646
                        (int) orgDtoList.stream().filter(x -> Objects.equals(val.get("id"), x.getAreaId())).count());
eddie.woo's avatar
eddie.woo committed
1647 1648 1649 1650 1651
                orgDto.getOrgCountList().add(org);
            }
        }
    }

1652 1653 1654
    /**
     * 从getOrgCustomDashbord抽取出来的方法
     */
1655
    private void getOrgCustomDashbord$OrganizationStructureId(OrgDto orgDto, List<OrganizationDto> orgDtoList,
1656
                                                              List<OrganizationDto> orgDtoTempList) {
1657
        // 找出IndustryId的列表,去重复
eddie.woo's avatar
eddie.woo committed
1658 1659
        List<Map<String, String>> dimensionValueList = orgDtoList.stream().map((OrganizationDto x) -> {
            Map<String, String> map = new HashMap<>();
1660
            map.put("id", x.getStructureId());
eddie.woo's avatar
eddie.woo committed
1661 1662 1663 1664
            map.put("Name", x.getStructureName());
            return map;
        }).distinct().collect(toList());

1665
        // 遍历BU Id的列表
eddie.woo's avatar
eddie.woo committed
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
        for (Map<String, String> val : dimensionValueList) {

            OrganizationDto orgdto = new OrganizationDto();
            orgdto.setName(val.get("Name"));
            orgdto.setLevel(LevelConstant.FirstLevel);
            // 加入第0级节点
            orgDtoTempList.add(orgdto);

            // 找出这个BU对应的OrganizationDto列表
            List<OrganizationDto> groupList = orgDtoList.stream()
1676
                    .filter(x -> Objects.equals(val.get("id"), x.getStructureId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
1677 1678 1679 1680 1681 1682 1683 1684

            groupList.forEach((OrganizationDto r) -> {
                r.setLevel(LevelConstant.FirstLevel + 1);
                // 加入第1级节点
                orgDtoTempList.add(r);
            });

            boolean noSuchItemById = orgDto.getOrgCountList().stream()
1685
                    .noneMatch(x -> Objects.equals(val.get("id"), x.getId()));
eddie.woo's avatar
eddie.woo committed
1686 1687
            if (noSuchItemById) {
                OrgCountDto org = new OrgCountDto();
1688
                org.setId(val.get("id"));
eddie.woo's avatar
eddie.woo committed
1689
                org.setName(val.get("Name"));
1690 1691
                // 统计businessUnitId数量
                org.setCount((int) orgDtoList.stream().filter(x -> Objects.equals(val.get("id"), x.getStructureId()))
eddie.woo's avatar
eddie.woo committed
1692 1693 1694 1695 1696 1697
                        .count());
                orgDto.getOrgCountList().add(org);
            }
        }
    }

1698 1699 1700
    /**
     * 从getOrgCustomDashbord抽取出来的方法
     */
1701
    private void getOrgCustomDashbord$IndustryId(OrgDto orgDto, List<OrganizationDto> orgDtoList,
1702
                                                 List<OrganizationDto> orgDtoTempList) {
1703
        // 找出IndustryId的列表,去重复
eddie.woo's avatar
eddie.woo committed
1704 1705
        List<Map<String, String>> dimensionValueList = orgDtoList.stream().map((OrganizationDto x) -> {
            Map<String, String> map = new HashMap<>();
1706
            map.put("id", x.getIndustryId());
eddie.woo's avatar
eddie.woo committed
1707 1708 1709 1710
            map.put("Name", x.getIndustryName());
            return map;
        }).distinct().collect(toList());

1711
        // 遍历BU Id的列表
eddie.woo's avatar
eddie.woo committed
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
        for (Map<String, String> val : dimensionValueList) {

            OrganizationDto orgdto = new OrganizationDto();
            orgdto.setName(val.get("Name"));
            orgdto.setLevel(LevelConstant.FirstLevel);
            // 加入第0级节点
            orgDtoTempList.add(orgdto);

            // 找出这个BU对应的OrganizationDto列表
            List<OrganizationDto> groupList = orgDtoList.stream()
1722
                    .filter(x -> Objects.equals(val.get("id"), x.getIndustryId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
1723 1724 1725 1726 1727 1728 1729 1730

            groupList.forEach((OrganizationDto r) -> {
                r.setLevel(LevelConstant.FirstLevel + 1);
                // 加入第1级节点
                orgDtoTempList.add(r);
            });

            boolean noSuchItemById = orgDto.getOrgCountList().stream()
1731
                    .noneMatch(x -> Objects.equals(val.get("id"), x.getId()));
eddie.woo's avatar
eddie.woo committed
1732 1733
            if (noSuchItemById) {
                OrgCountDto org = new OrgCountDto();
1734
                org.setId(val.get("id"));
eddie.woo's avatar
eddie.woo committed
1735
                org.setName(val.get("Name"));
1736 1737
                // 统计businessUnitId数量
                org.setCount((int) orgDtoList.stream().filter(x -> Objects.equals(val.get("id"), x.getIndustryId()))
eddie.woo's avatar
eddie.woo committed
1738 1739 1740 1741 1742 1743
                        .count());
                orgDto.getOrgCountList().add(org);
            }
        }
    }

1744 1745 1746
    /**
     * 从getOrgCustomDashbord抽取出来的方法
     */
1747
    private void getOrgCustomDashbord$BusinessUnitId(OrgDto orgDto, List<OrganizationDto> orgDtoList,
1748
                                                     List<OrganizationDto> orgDtoTempList) {
1749
        // 找出BU Id的列表,去重复
eddie.woo's avatar
eddie.woo committed
1750 1751
        List<Map<String, String>> dimensionValueList = orgDtoList.stream().map((OrganizationDto x) -> {
            Map<String, String> map = new HashMap<>();
1752
            map.put("id", x.getBusinessUnitId());
eddie.woo's avatar
eddie.woo committed
1753 1754 1755 1756
            map.put("Name", x.getBusinessUnitName());
            return map;
        }).distinct().collect(toList());

1757
        // 遍历BU Id的列表
eddie.woo's avatar
eddie.woo committed
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
        for (Map<String, String> val : dimensionValueList) {

            OrganizationDto orgdto = new OrganizationDto();
            orgdto.setName(val.get("Name"));
            orgdto.setLevel(LevelConstant.FirstLevel);
            // 加入第0级节点
            orgDtoTempList.add(orgdto);

            // 找出这个BU对应的OrganizationDto列表
            List<OrganizationDto> groupList = orgDtoList.stream()
1768
                    .filter(x -> Objects.equals(val.get("id"), x.getBusinessUnitId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
1769 1770 1771 1772 1773 1774 1775 1776

            groupList.forEach((OrganizationDto r) -> {
                r.setLevel(LevelConstant.FirstLevel + 1);
                // 加入第1级节点
                orgDtoTempList.add(r);
            });

            boolean noSuchItemById = orgDto.getOrgCountList().stream()
1777
                    .noneMatch(x -> Objects.equals(val.get("id"), x.getId()));
eddie.woo's avatar
eddie.woo committed
1778 1779
            if (noSuchItemById) {
                OrgCountDto org = new OrgCountDto();
1780
                org.setId(val.get("id"));
eddie.woo's avatar
eddie.woo committed
1781
                org.setName(val.get("Name"));
1782 1783
                // 统计businessUnitId数量
                org.setCount((int) orgDtoList.stream().filter(x -> Objects.equals(val.get("id"), x.getBusinessUnitId()))
eddie.woo's avatar
eddie.woo committed
1784 1785 1786 1787 1788 1789
                        .count());
                orgDto.getOrgCountList().add(org);
            }
        }
    }

1790 1791 1792
    /**
     * 从getOrgCustomDashbord抽取出来的方法
     */
1793 1794
    private List<OrganizationDto> getOrgCustomDashbord$getOrgDtoList(final String dimensionValueId,
                                                                     final String parentDimensionId) {
eddie.woo's avatar
eddie.woo committed
1795 1796
        List<OrganizationDto> orgDtoList = null;

1797
        if (DimensionConstant.OrgSubChildrenId.equals(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
1798 1799 1800
            // 如果是机构
            // 查找所有该父机构下的所有子机构
            List<OrganizationDto> allOrgList = getAllOrgList();
1801 1802 1803 1804 1805 1806 1807 1808
            String parentOrgId = dimensionValueId;
            // orgList 所有的子机构的Id List
            List<String> orgList = getChildrenOrgIdToList(parentOrgId, allOrgList).stream()
                    .filter(x -> !parentOrgId.equals(x)).collect(toList());

            // 然后用所有的子机构的Id List在内存中条件过滤
            orgDtoList = getOrgDimensionMappingForDimension(parentDimensionId).stream()
                    .filter(x -> orgList.contains(x.getId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
1809 1810 1811 1812 1813
        } else {
            // 如果不是机构
            // getOrgDimensionMappingForDimension查出的是全量的数据
            // 然后用dimensionId和dimensionValueId两个字段在内存中条件过滤
            orgDtoList = getOrgDimensionMappingForDimension(
1814
                    parentDimensionId)
1815
                    .stream()
1816 1817
                    .filter(organizationDto -> (parentDimensionId.equals(organizationDto.getDimensionId())
                            && dimensionValueId.equals(organizationDto.getDimensionValueId())))
1818
                    .collect(toList());
eddie.woo's avatar
eddie.woo committed
1819 1820
        }
        // 去除机构为空的值
1821
        orgDtoList.removeIf(x -> Strings.isBlank(x.getId()));
eddie.woo's avatar
eddie.woo committed
1822 1823 1824 1825 1826 1827
        return orgDtoList;
    }

    /**
     * 获取维度的名称,维度值的名称
     */
1828
    public OrgCustomDto getDimensionValueName(String dimensionId, String dimensionValueId) {
eddie.woo's avatar
eddie.woo committed
1829
        OrgCustomDto customDto = new OrgCustomDto();
1830
        DimensinTypeOrgDto dimensionDto = dimensionService.getDimensionById(dimensionId);
eddie.woo's avatar
eddie.woo committed
1831 1832 1833
        Integer dimensionType = dimensionDto.getDimensionType();
        customDto.setDimensionName(dimensionDto.getName());
        if (DimensionTypeEnum.BusinessUnit.value().equals(dimensionType)) {
1834
            BusinessUnit value = dimensionValueId != null ? businessUnitMapper.selectByPrimaryKey(dimensionValueId)
eddie.woo's avatar
eddie.woo committed
1835 1836 1837 1838 1839
                    : null;
            if (value != null) {
                customDto.setDimensionValueName(value.getName());
            }
        } else if (DimensionTypeEnum.OrganizationStructure.value().equals(dimensionType)) {
1840 1841
            OrganizationStructure value = dimensionValueId != null
                    ? organizationStructureMapper.selectByPrimaryKey(dimensionValueId)
eddie.woo's avatar
eddie.woo committed
1842 1843 1844 1845 1846
                    : null;
            if (value != null) {
                customDto.setDimensionValueName(value.getName());
            }
        } else if (DimensionTypeEnum.SelfDimension.value().equals(dimensionType)) {
1847
            DimensionValue value = dimensionValueId != null ? dimensionValueMapper.selectByPrimaryKey(dimensionValueId)
eddie.woo's avatar
eddie.woo committed
1848 1849 1850 1851 1852 1853 1854 1855
                    : null;
            if (value != null) {
                customDto.setDimensionValueName(value.getName());
            }
        }
        return customDto;
    }

1856
    @SuppressWarnings({"rawtypes", "deprecation"})
1857
    public OperationResultDto disableOrgs(List<String> orgIds) {
eddie.woo's avatar
eddie.woo committed
1858 1859
        try {
            List<OperationLogDto> logList = new ArrayList<>();
1860 1861
            for (String orgId : orgIds) {
                Organization rootOrg = orgId != null ? organizationMapper.selectByPrimaryKey(orgId) : null;
eddie.woo's avatar
eddie.woo committed
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
                Assert.notNull(rootOrg, "rootOrg is null");
                if (rootOrg.getIsActive()) {
                    rootOrg.setIsActive(false);
                    organizationMapper.updateByPrimaryKey(rootOrg);
                    OperationLogDto opLog = new OperationLogDto();
                    opLog.setAction(OperationAction.Update.value());
                    opLog.setOperationContent(LogMessage.IsActive);
                    opLog.setOperationObject(rootOrg.getName());
                    opLog.setOriginalState(BooleanUtils.isTrue(rootOrg.getIsActive()) ? "False" : "True");
                    opLog.setUpdateState(BooleanUtils.isTrue(rootOrg.getIsActive()) ? "True" : "False");
                    opLog.setModule(OperationModule.Organization.value());
                    opLog.setComment("");
                    opLog.setLogType(OperateLogType.OperationLogOrganization.value());
                    logList.add(opLog);
                }
            }
            operationLogService.addOperationLogList(logList);
            return new OperationResultDto(true);
        } catch (Exception ex) {
            logger.error("DisableOrgs出错了:" + ex, ex);
            logger.error("标记回滚, ready to call setRollbackOnly");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new OperationResultDto(false, ex.getMessage());
        }
    }

1888
    @SuppressWarnings({"rawtypes"})
1889 1890
    public OperationResultDto enableOrgs(String orgId) {
        Organization curOrg = orgId != null ? organizationMapper.selectByPrimaryKey(orgId) : null;
eddie.woo's avatar
eddie.woo committed
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
        if (curOrg == null) {
            return new OperationResultDto(false, OrganizationMessage.NotFindOrgEnable);
        } else {
            if (!curOrg.getIsActive()) {
                curOrg.setIsActive(true);
                organizationMapper.updateByPrimaryKey(curOrg);
                OperationLogDto opLog = new OperationLogDto();
                opLog.setAction(OperationAction.Update.value());
                opLog.setOperationContent(LogMessage.IsActive);
                opLog.setOperationObject(curOrg.getName());
                opLog.setOriginalState(LogMessage.Disable);
                opLog.setUpdateState(LogMessage.Enable);
                opLog.setIp("");
                opLog.setModule(OperationModule.Organization.value());
                opLog.setComment("");
                opLog.setLogType(OperateLogType.OperationLogOrganization.value());
                operationLogService.addOperationLog(opLog);
            }
            return new OperationResultDto(true);
        }
    }

1913 1914
    public OrganizationDto getSingleOrgByOrgId(String orgId) {
        OrganizationDto result = organizationMapper.getSingleOrgByOrgIdToOrgDto(orgId).stream().findFirst()
eddie.woo's avatar
eddie.woo committed
1915 1916 1917 1918 1919 1920
                .orElse(null);
        Assert.notNull(result, "result is null");
        result.setLevel(result.getLevel() == null ? 0 : result.getLevel());
        result.setIsSystemDimension(result.getIsSystemDimension() == null ? false : result.getIsSystemDimension());

        // 查询机构账套
1921
        List<EnterpriseAccountSetOrgDto> query1 = enterpriseAccountSetOrgMapper.getSingleOrgByOrgIdToEASODto(orgId);
eddie.woo's avatar
eddie.woo committed
1922 1923 1924 1925 1926 1927 1928 1929 1930
        for (EnterpriseAccountSetOrgDto p : query1) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
            p.setExpiredDateStr(p.getExpiredDate() == null ? "" : formatter.format(p.getExpiredDate()));
            p.setEffectiveDateStr(p.getEffectiveDate() == null ? "" : formatter.format(p.getEffectiveDate()));
        }
        result.setEnterpriseAccountSetOrgList(query1);
        // 查询机构服务
        List<ServiceType> serviceType = serviceTypeMapper.selectByExample(null);
        List<OrganizationServiceTemplateGroupDto> query2 = organizationServiceTemplateGroupMapper
1931
                .getSingleOrgByOrgIdToOSTGDto(orgId);
eddie.woo's avatar
eddie.woo committed
1932
        for (OrganizationServiceTemplateGroupDto mapping : query2) {
1933
            ServiceType st = serviceType.stream().filter(n -> Objects.equals(n.getId(), mapping.getServiceTypeId()))
eddie.woo's avatar
eddie.woo committed
1934 1935 1936 1937 1938 1939
                    .findFirst().orElse(null);
            if (st != null) {
                mapping.setServiceTypeName(st.getName());
            }
        }
        result.setOrganizationServiceTemplateGroupList(query2);
1940
        if (StringUtils.isEmpty(result.getParentId())) {
eddie.woo's avatar
eddie.woo committed
1941 1942 1943
            result.setParentName("");
        } else {
            Organization tParent = organizationMapper.selectByExample(null).stream()
1944
                    .filter(sa -> Objects.equals(sa.getId(), result.getParentId())).findFirst().orElse(null);
eddie.woo's avatar
eddie.woo committed
1945 1946 1947
            Assert.notNull(tParent, "tParent is null");
            result.setParentName(tParent.getName());
        }
1948
        result.setDimensionValueOrgList(dimensionService.getAllDimensionOrgListByOrgId(result.getId()));
eddie.woo's avatar
eddie.woo committed
1949 1950 1951
        return result;
    }

gary's avatar
gary committed
1952
    public OrganizationExtraDto getSingleOrgExtraByOrgId(String orgId) {
1953 1954
        OrganizationExtraDto organizationExtraDto = new OrganizationExtraDto();
        OrganizationExtra organizationExtra = organizationExtraMapper.selectByOrgId(orgId).stream().findFirst()
gary's avatar
gary committed
1955
                .orElse(null);
1956 1957 1958
        if(null!=organizationExtra){
            beanUtil.copyProperties(organizationExtra,organizationExtraDto);
        }
1959
        return organizationExtraDto;
gary's avatar
gary committed
1960 1961
    }

eddie.woo's avatar
eddie.woo committed
1962 1963 1964 1965 1966 1967 1968
    public Boolean codeUniqueValidate(OrganizationValidateDto validateDto) {
        String innerId = Strings.isBlank(validateDto.getId()) ? "" : validateDto.getId().trim();
        String innerCode = Strings.isBlank(validateDto.getValue()) ? "" : validateDto.getValue().trim();
        return Strings.isBlank(innerCode)
                || organizationMapper.countForCodeUniqueValidate(innerId, innerCode).equals(0);
    }

1969
    @SuppressWarnings({"rawtypes", "unchecked"})
eddie.woo's avatar
eddie.woo committed
1970 1971 1972 1973 1974 1975
    public OperationResultDto<Object> addOrg(OrganizationDto orgDto) {
        try {
            OperationResultDto result = checkExist(orgDto);
            if (result != null && !BooleanUtils.isTrue(result.getResult())) {
                return new OperationResultDto(result.getResult(), result.getResultMsg());
            }
1976 1977
            if (Objects.equals(orgDto.getParentId(), OrganizationConstant.NoParentId)) {
                orgDto.setParentId(null);
1978
                orgDto.setpLevel(0);
eddie.woo's avatar
eddie.woo committed
1979 1980 1981
            } else {
                // 机构添加层级
                Organization query = null;
1982
                query = orgDto.getParentId() != null ? organizationMapper.selectByPrimaryKey(orgDto.getParentId())
eddie.woo's avatar
eddie.woo committed
1983 1984
                        : null;
                if (query != null) {
1985
                    orgDto.setpLevel(query.getpLevel() + 1);
eddie.woo's avatar
eddie.woo committed
1986 1987 1988
                }
            }

1989
            orgDto.setId(CommonUtils.getUUID());
eddie.woo's avatar
eddie.woo committed
1990 1991 1992
            Date now = new Date();
            orgDto.setCreateTime(now);
            orgDto.setUpdateTime(now);
eddie.woo's avatar
eddie.woo committed
1993 1994

            OrganizationValidateDto vailOrgDto = new OrganizationValidateDto();
1995
            vailOrgDto.setId(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
1996 1997 1998 1999 2000 2001 2002
            vailOrgDto.setValue(orgDto.getCode());

            if (!codeUniqueValidate(vailOrgDto)) {
                return new OperationResultDto(false, OrganizationMessage.OrgNameOrCodeIsExiste);
            }

            vailOrgDto = new OrganizationValidateDto();
2003
            vailOrgDto.setId(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
2004 2005 2006 2007 2008 2009 2010
            vailOrgDto.setValue(orgDto.getTaxPayerNumber());

            if (!taxPayerNumberUniqueValidate(vailOrgDto)) {
                return new OperationResultDto(false, OrganizationMessage.OrgNameOrCodeTaxPaymentNoIsExist);
            }

            Organization org = copyProperties(orgDto, new Organization());
2011
            org.setpLevel(orgDto.getpLevel());
gary's avatar
gary committed
2012 2013 2014 2015 2016 2017 2018 2019 2020
            if (StringUtils.isEmpty(org.getClientCode())) {
                org.setClientCode("null");
            }
            if (StringUtils.isEmpty(org.getName())) {
                org.setName(org.getEnglishName());
            }
            if (StringUtils.isEmpty(org.getStructureId())) {
                org.setStructureId("null");
            }
gary's avatar
gary committed
2021
            organizationMapper.insertSelective(org);
eddie.woo's avatar
eddie.woo committed
2022 2023 2024 2025 2026 2027 2028 2029 2030
            OperationResultDto<Object> validateSetRet = validateEnterpriseAccountSetDateTimeOverlap(
                    orgDto.getEnterpriseAccountSetOrgList());
            if (!validateSetRet.getResult()) {
                logger.error("标记回滚, ready to call setRollbackOnly");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return validateSetRet;
            }

            // 添加账套
gary's avatar
gary committed
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
            if(!orgDto.getOversea()){
                for (EnterpriseAccountSetOrgDto p : orgDto.getEnterpriseAccountSetOrgList()) {
                    EnterpriseAccountSetOrg enterpriseAccountSetOrg = new EnterpriseAccountSetOrg();
                    enterpriseAccountSetOrg.setId(CommonUtils.getUUID());
                    enterpriseAccountSetOrg.setEnterpriseAccountSetId(p.getEnterpriseAccountSetId());
                    enterpriseAccountSetOrg.setOrganizationId(orgDto.getId());
                    if (!Strings.isEmpty(p.getEffectiveDateStr())) {
                        enterpriseAccountSetOrg.setEffectiveDate(DateTimeFormat.forPattern("yyyy-MM-dd")
                                .parseDateTime(p.getEffectiveDateStr() + "-01").toDate());
                        p.setEffectiveDate(DateTimeFormat.forPattern("yyyy-MM-dd")
                                .parseDateTime(p.getEffectiveDateStr() + "-01").toDate());
                    }
eddie.woo's avatar
eddie.woo committed
2043

gary's avatar
gary committed
2044 2045 2046 2047 2048 2049 2050
                    if (!Strings.isEmpty(p.getExpiredDateStr())) {
                        enterpriseAccountSetOrg.setExpiredDate(DateTimeFormat.forPattern("yyyy-MM-dd")
                                .parseDateTime(p.getExpiredDateStr() + "-01").plusMonths(1).minusDays(1).toDate());
                        p.setExpiredDate(DateTimeFormat.forPattern("yyyy-MM-dd")
                                .parseDateTime(p.getExpiredDateStr() + "-01").plusMonths(1).minusDays(1).toDate());
                    }
                    enterpriseAccountSetOrgMapper.insert(enterpriseAccountSetOrg);
eddie.woo's avatar
eddie.woo committed
2051 2052
                }

gary's avatar
gary committed
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
                // 添加服务
                // For VAT, update Rule Engine tables after updating
                // OrganizationServiceTemplateGroup
                // .NET中定义了以下变量,但未被使用,故在此处注释 defaultRule, reportRules
                OrganizationServiceTemplateGroupDto vatSetting = orgDto.getOrganizationServiceTemplateGroupList().stream()
                        .filter(t -> ServiceTypeEnum.VAT.toString().equals(t.getServiceTypeId())).findFirst().orElse(null);
                if (vatSetting != null) { // If currently no rule and new rule should be added
                    TemplateGroup templateGrp = vatSetting.getTemplateGroupId() != null
                            ? templateGroupMapper.selectByPrimaryKey(vatSetting.getTemplateGroupId())
                            : null;
                    // In organization module tax payer type is 1&2 while 0&1 in rule engine
                    Integer newTaxPayerType = (templateGrp != null && templateGrp.getPayTaxType() != null)
                            ? templateGrp.getPayTaxType() - 1
                            : VatTaxPayerTypeEnum.General.value();
                    TaxPayerReportRule newRule = new TaxPayerReportRule();
                    newRule.setId(distributedIdService.nextId());
                    newRule.setIsDefault(false);
                    newRule.setOrganizationId(orgDto.getId());
                    newRule.setTemplateGroupId(vatSetting.getTemplateGroupId());
                    newRule.setTaxPayerType(newTaxPayerType); // Use tax payer type related to template group
                    newRule.setCreateTime(now);
                    newRule.setUpdateTime(now);
                    taxPayerReportRuleMapper.insert(newRule);
                }
                for (OrganizationServiceTemplateGroupDto p : orgDto.getOrganizationServiceTemplateGroupList()) {
                    OrganizationServiceTemplateGroup orgServiceTempGroup = new OrganizationServiceTemplateGroup();
                    orgServiceTempGroup.setId(distributedIdService.nextId());
                    orgServiceTempGroup.setOrganizationId(orgDto.getId());
                    orgServiceTempGroup.setServiceTypeId(p.getServiceTypeId());
                    orgServiceTempGroup.setTemplateGroupId(p.getTemplateGroupId());
                    organizationServiceTemplateGroupMapper.insert(orgServiceTempGroup);
                }
eddie.woo's avatar
eddie.woo committed
2085

gary's avatar
gary committed
2086
                // CopyModelTree(orgDto);//__restoreroy__
eddie.woo's avatar
eddie.woo committed
2087

gary's avatar
gary committed
2088 2089
                addOrgSelfDimensionList(orgDto);
            }
eddie.woo's avatar
eddie.woo committed
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
            // C#中的内部类CommonLogParams 在JAVA中已经被合并到OperationLogDto中
            UpdateLogParams tempCommonLogParms = new UpdateLogParams();
            tempCommonLogParms.setOperationModule(Organization.value());
            tempCommonLogParms.setComment(AddOrganization);
            tempCommonLogParms.setOperateLogType(OperationLogOrganization.value());
            tempCommonLogParms.setOperationContent(org.getName());
            tempCommonLogParms.setOperationAction(OperationAction.New.value());
            tempCommonLogParms.setOperationObject(orgDto.getName());
            tempCommonLogParms.setUpdateState("");
            tempCommonLogParms.setOriginalState("");
            operationLogService.addOrDeleteDataAddLog(tempCommonLogParms);
            return new OperationResultDto(true);
        } catch (Exception e) {
            logger.error("addOrg出错:" + e, e);
            logger.error("标记回滚, ready to call setRollbackOnly");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
gary's avatar
gary committed
2106
            return new OperationResultDto(false, SystemError);
eddie.woo's avatar
eddie.woo committed
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
        }
    }

    // C#中形参userName在函数中未被使用,故删除
    private void addOrgSelfDimensionList(OrganizationDto orgDto) {
        if (orgDto.getDimensionValueOrgList() == null || orgDto.getDimensionValueOrgList().isEmpty()) {
            return;
        }
        List<DimensionValueOrg> addList = new ArrayList<>();
        // C#中的内部类CommonLogParams 在JAVA中已经被合并到OperationLogDto中
        // C#中进行联合查询获取到DimensionValue和Dimension的表,但无调用。 dimensionLogList未被使用,故将其删除
        for (DimensionValueOrgDto item : orgDto.getDimensionValueOrgList()) {
            DimensionValueOrg dvOrg = new DimensionValueOrg();
            // C#中下文UpdateTime 与 CreateTime在数据库中并无对应字段,故删除
2121 2122 2123
            dvOrg.setOrganizationId(orgDto.getId());
            dvOrg.setId(CommonUtils.getUUID());
            dvOrg.setDimensionValueId(item.getDimensionValueId());
eddie.woo's avatar
eddie.woo committed
2124 2125 2126 2127 2128 2129 2130 2131
            addList.add(dvOrg);
        }
        if (!addList.isEmpty()) {
            addList.stream().forEach(x -> dimensionValueOrgMapper.insert(x));
        }

    }

2132
    @SuppressWarnings({"rawtypes", "unchecked"})
eddie.woo's avatar
eddie.woo committed
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
    public OperationResultDto<Object> validateEnterpriseAccountSetDateTimeOverlap(
            List<EnterpriseAccountSetOrgDto> list) {
        if (list != null && !list.isEmpty()) {
            for (EnterpriseAccountSetOrgDto p : list) {
                p.setEffectiveDate(null);
                p.setExpiredDate(null);
                if (Strings.isNotBlank(p.getEffectiveDateStr())) {
                    p.setEffectiveDate(DateTimeFormat.forPattern("yyyy-MM-dd")
                            .parseDateTime(p.getEffectiveDateStr() + "-01").toDate());
                }
                if (Strings.isNotBlank(p.getExpiredDateStr())) {
                    p.setExpiredDate(DateTimeFormat.forPattern("yyyy-MM-dd")
                            .parseDateTime(p.getExpiredDateStr() + "-01").plusMonths(1).minusDays(1).toDate());
                }
            }
            if (list.stream().anyMatch(sa -> sa.getEffectiveDate().after(sa.getExpiredDate()))) {
                return new OperationResultDto(false, EffectiveDateAreaProblem);
            }

            List<EnterpriseAccountSetOrgDto> overlapList = new ArrayList<>();
            if (commonService.isOrganizationDateTimeOverlap(list)) {
                list.stream().filter(sa -> sa.getOverlapList() != null && !sa.getOverlapList().isEmpty())
                        .forEach(s -> overlapList.add(s));
            }
            if (!overlapList.isEmpty()) {
                return new OperationResultDto(false, EnterpriseAccountSetOrgDateTimeOverlap, overlapList);
            }
            // 一年之内不能设置两个一样的账套,即:不能设置这种,账套A,2017年1月到3月,账套A,2017年4月到5月
2161
            List<String> acountList = list.stream().map(EnterpriseAccountSetOrgDto::getEnterpriseAccountSetId)
eddie.woo's avatar
eddie.woo committed
2162 2163 2164
                    .distinct().collect(Collectors.toList());
            for (String accountId : acountList) {
                List<EnterpriseAccountSetOrgDto> tempList = list.stream()
2165
                        .filter(sa -> Strings.equals(sa.getEnterpriseAccountSetId(), accountId))
eddie.woo's avatar
eddie.woo committed
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
                        .collect(Collectors.toList());
                if (!CommonUtils.validateOnlyOncePerYear(tempList)) {
                    return new OperationResultDto(false,
                            EnterpriseAccountSetOrgMessage.EnterpriseAccountSetOrgOnlyOncePerYear);
                }
            }
        }
        return new OperationResultDto(true);
    }

    @SuppressWarnings("rawtypes")
    private OperationResultDto checkExist(OrganizationDto orgDto) {
        Assert.notNull(orgDto, "orgDto null point error");
        Organization queryRoot = null;
gary's avatar
gary committed
2180
        if ((null==orgDto.getOversea()||!orgDto.getOversea()) && orgDto.getParentId() != null) {
eddie.woo's avatar
eddie.woo committed
2181 2182 2183
            OrganizationExample example = new OrganizationExample();
            Criteria criteria = example.createCriteria();
            criteria.andClientCodeEqualTo(orgDto.getClientCode());
2184 2185
            if (orgDto.getId() != null) {
                criteria.andIdNotEqualTo(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
2186 2187 2188
            }
            queryRoot = organizationMapper.selectByExample(example).stream().findFirst().orElse(null);
        }
2189
        if (queryRoot != null && orgDto.getId() != null && Strings.equals(orgDto.getId(), CommonConstants.EMPTY_UUID)) {
eddie.woo's avatar
eddie.woo committed
2190 2191 2192
            return new OperationResultDto(false, OrganizationMessage.ClientCodeIsExist);
        }
        OperationResultDto operationResult = checkOrgNameOrOrgCode(orgDto);
gary's avatar
gary committed
2193
        if (operationResult.getResult() && (null==orgDto.getOversea()||!orgDto.getOversea())) {
eddie.woo's avatar
eddie.woo committed
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209
            operationResult = checkCodeTaxPaymentNo(orgDto);
        }
        return operationResult;
    }

    @SuppressWarnings("rawtypes")
    private OperationResultDto checkCodeTaxPaymentNo(OrganizationDto orgDto) {

        OrganizationExample example = new OrganizationExample();
        Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(orgDto.getName()).andCodeEqualTo(orgDto.getCode());
        if (orgDto.getTaxPayerNumber() != null) {
            criteria.andTaxPayerNumberEqualTo(orgDto.getTaxPayerNumber());
        } else {
            criteria.andTaxPayerNumberIsNull();
        }
2210 2211
        if (orgDto.getId() != null) {
            criteria.andIdNotEqualTo(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
2212 2213 2214 2215 2216 2217 2218 2219 2220
        }
        Organization query = organizationMapper.selectByExample(example).stream().findFirst().orElse(null);
        if (query != null) {
            return new OperationResultDto(false, OrganizationMessage.OrgNameOrCodeTaxPaymentNoIsExist);
        }
        return new OperationResultDto(true);
    }

    @SuppressWarnings("rawtypes")
2221
    public OperationResultDto updateOrgToDimension(String dimensionValueId, String parentDimensionId,
2222
                                                   List<OrgBasicDto> orgList) {
2223
        if (orgList == null || dimensionValueId == null || parentDimensionId == null) {
eddie.woo's avatar
eddie.woo committed
2224 2225
            throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
        }
2226
        String dimensionName = dimensionService.getDimensionById(parentDimensionId).getName();
eddie.woo's avatar
eddie.woo committed
2227
        // 事业部,更新机构表
2228
        if (DimensionConstant.BusinessUnitId.equalsIgnoreCase(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
2229
            for (OrgBasicDto model : orgList) {
2230
                Organization old = organizationMapper.selectByPrimaryKey(model.getId());
eddie.woo's avatar
eddie.woo committed
2231 2232 2233 2234
                if (old == null) {
                    throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
                }
                Organization copy = CommonUtils.copyProperties(old, new Organization());
2235 2236
                old.setBusinessUnitId(dimensionValueId);
                logger.debug("Start to update organization [ {} ]", old.getId());
eddie.woo's avatar
eddie.woo committed
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
                organizationMapper.updateByPrimaryKey(old);
                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setOperateLogType(OperateLogType.OperationLogOrganization.value());
                updateLogParams.setComment("");
                updateLogParams.setOperationModule(OperationModule.BasicDataBusinessUnit.value());
                updateLogParams.setOperationContent(dimensionName);
                updateLogParams.setOriginalState(copy);
                updateLogParams.setUpdateState(old);
                updateLogParams.setOperationObject(model.getName());
                updateLogParams.setOperationAction(OperationAction.Update.value());
                operationLogService.updateDataAddLog(updateLogParams);
            }
2249
        } else if (DimensionConstant.OrgSubChildrenId.equalsIgnoreCase(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
2250

2251
        } else if (DimensionConstant.AreaId.equalsIgnoreCase(parentDimensionId)) {
eddie.woo's avatar
eddie.woo committed
2252 2253 2254
            List<UpdateLogParams> logList = new ArrayList<>();
            List<NameDto> areaNameDtoList = areaMapper.selectByExample(new AreaExample()).stream()
                    .map(sa -> CommonUtils.copyProperties(sa, new NameDto())).collect(Collectors.toList());
2255
            NameDto newArea = areaNameDtoList.stream().filter(sa -> Objects.equals(sa.getId(), dimensionValueId))
eddie.woo's avatar
eddie.woo committed
2256 2257 2258 2259
                    .findFirst().orElse(null);
            String newAreaName = newArea == null ? "" : newArea.getName();
            // 区域
            for (OrgBasicDto model : orgList) {
2260
                Organization old = organizationMapper.selectByPrimaryKey(model.getId());
eddie.woo's avatar
eddie.woo committed
2261 2262 2263 2264
                if (old == null) {
                    throw new ApplicationException(CommonConstants.JSONNULLOBJECT);
                }
                Organization copy = CommonUtils.copyProperties(old, new Organization());
2265 2266
                if (!dimensionValueId.equalsIgnoreCase(old.getAreaId())) {
                    old.setAreaId(dimensionValueId);
eddie.woo's avatar
eddie.woo committed
2267
                    NameDto oldArea = areaNameDtoList.stream()
2268
                            .filter(sa -> Objects.equals(sa.getId(), copy.getAreaId())).findFirst().orElse(null);
eddie.woo's avatar
eddie.woo committed
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
                    String oldAreaName = oldArea == null ? "" : oldArea.getName();
                    UpdateLogParams updateLogParams = new UpdateLogParams();
                    updateLogParams.setOperateLogType(OperateLogType.OperationLogOrganization.value());
                    updateLogParams.setComment("");
                    updateLogParams.setOperationModule(OperationModule.Organization.value());
                    updateLogParams.setOperationContent(OrganizationMessage.AreaLogMessage);
                    updateLogParams.setOriginalState(oldAreaName);
                    updateLogParams.setUpdateState(newAreaName);
                    updateLogParams.setOperationObject(copy.getName());
                    updateLogParams.setOperationAction(OperationAction.Update.value());
                    logList.add(updateLogParams);
2280
                    logger.debug("Start to update Organization [ {} ]", old.getId());
eddie.woo's avatar
eddie.woo committed
2281 2282 2283 2284 2285 2286 2287 2288 2289
                    organizationMapper.updateByPrimaryKey(old);
                }
            }
            operationLogService.addOrDeleteDataAddLog(logList);
        } else {
            // 自定义的时候,更新DimensionValurOrg Table
            List<DimensionValueOrgDto> orgDtoList = new ArrayList<>();
            for (OrgBasicDto model : orgList) {
                DimensionValueOrgExample dimensionValueOrgExample = new DimensionValueOrgExample();
2290 2291
                dimensionValueOrgExample.createCriteria().andDimensionValueIdEqualTo(dimensionValueId)
                        .andOrganizationIdEqualTo(model.getId());
eddie.woo's avatar
eddie.woo committed
2292 2293
                List<DimensionValueOrg> query = dimensionValueOrgMapper.selectByExample(dimensionValueOrgExample);
                if ((query == null || query.isEmpty())
2294 2295
                        && orgDtoList.stream().noneMatch(s -> Objects.equals(s.getOrganizationId(), model.getId())
                        && Objects.equals(s.getDimensionValueId(), dimensionValueId))) {
eddie.woo's avatar
eddie.woo committed
2296
                    DimensionValueOrgDto dto = new DimensionValueOrgDto();
2297 2298 2299
                    dto.setId(CommonUtils.getUUID());
                    dto.setDimensionValueId(dimensionValueId);
                    dto.setOrganizationId(model.getId());
eddie.woo's avatar
eddie.woo committed
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
                    orgDtoList.add(dto);
                }
                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setOperateLogType(OperateLogType.OperationLogOrganization.value());
                updateLogParams.setComment("");
                updateLogParams.setOperationModule(OperationModule.BasicDataDimensionValue.value());
                updateLogParams.setOperationContent(dimensionName);
                updateLogParams.setOriginalState("");
                updateLogParams.setUpdateState("");
                updateLogParams.setOperationObject(model.getName());
                updateLogParams.setOperationAction(OperationAction.New.value());
                operationLogService.addOrDeleteDataAddLog(updateLogParams);
            }
            // 添加新数据
            List<DimensionValueOrg> attr = orgDtoList.stream()
                    .map(s -> CommonUtils.copyProperties(s, new DimensionValueOrg())).collect(Collectors.toList());
            for (DimensionValueOrg oneAttr : attr) {
2317
                logger.debug("Start to insert DimensionValueOrg [ {} ]", oneAttr.getId());
eddie.woo's avatar
eddie.woo committed
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
                dimensionValueOrgMapper.insert(oneAttr);
            }
        }
        OperationResultDto operationResultDto = new OperationResultDto();
        operationResultDto.setResult(true);
        return operationResultDto;
    }

    @SuppressWarnings("rawtypes")
    private OperationResultDto checkOrgNameOrOrgCode(OrganizationDto orgDto) {
        OrganizationExample example = new OrganizationExample();
gary's avatar
gary committed
2329
        if (null!=orgDto.getOversea()&&orgDto.getOversea()&&null!=orgDto.getEnglishName()) {
gary's avatar
gary committed
2330 2331 2332
            return new OperationResultDto(true);
        }
        if (orgDto.getId() == null) {
eddie.woo's avatar
eddie.woo committed
2333 2334 2335
            example.or().andClientCodeEqualTo(orgDto.getClientCode()).andNameEqualTo(orgDto.getName());
            example.or().andClientCodeEqualTo(orgDto.getClientCode()).andCodeEqualTo(orgDto.getCode());
        } else {
2336
            example.or().andClientCodeEqualTo(orgDto.getClientCode()).andIdNotEqualTo(orgDto.getId())
eddie.woo's avatar
eddie.woo committed
2337
                    .andNameEqualTo(orgDto.getName());
2338
            example.or().andClientCodeEqualTo(orgDto.getClientCode()).andIdNotEqualTo(orgDto.getId())
eddie.woo's avatar
eddie.woo committed
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
                    .andCodeEqualTo(orgDto.getCode());
        }
        Organization query = organizationMapper.selectByExample(example).stream().findFirst().orElse(null);
        if (query != null) {
            return new OperationResultDto(false, OrganizationMessage.OrgNameOrCodeIsExiste);
        }
        return new OperationResultDto(true);
    }

    /**
     * update a org info
     */
2351
    @SuppressWarnings({"rawtypes", "unchecked"})
eddie.woo's avatar
eddie.woo committed
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
    public OperationResultDto<Object> updateOrg(OrganizationDto orgDto) {
        try {
            Assert.notNull(orgDto, "orgDto Null Exception on updateOrg");
            if (orgDto.getEnterpriseAccountSetOrgList() == null) {
                orgDto.setEnterpriseAccountSetOrgList(new ArrayList<>());
            }

            OperationResultDto result = checkOrgNameOrOrgCode(orgDto);
            if (result != null && result.getResult()) {
                result = this.checkCodeTaxPaymentNo(orgDto);
            }
            if (result != null && !BooleanUtils.isTrue(result.getResult())) {
                return new OperationResultDto(result.getResult(), result.getResultMsg());
            }
2366
            Organization org = orgDto.getId() != null ? organizationMapper.selectByPrimaryKey(orgDto.getId()) : null;
eddie.woo's avatar
eddie.woo committed
2367 2368 2369 2370 2371 2372
            if (org == null) {
                return new OperationResultDto(false, OrganizationMessage.NotFindOrg);
            }

            // code唯一验证
            OrganizationValidateDto orgValidateDto1 = new OrganizationValidateDto();
2373
            orgValidateDto1.setId(org.getId());
eddie.woo's avatar
eddie.woo committed
2374 2375 2376 2377 2378 2379 2380
            orgValidateDto1.setValue(orgDto.getCode());
            if (!codeUniqueValidate(orgValidateDto1)) {
                return new OperationResultDto(false, OrganizationMessage.OrgNameOrCodeIsExiste);
            }

            // 纳税人识别号唯一性验证
            OrganizationValidateDto orgValidateDto2 = new OrganizationValidateDto();
2381
            orgValidateDto2.setId(org.getId());
eddie.woo's avatar
eddie.woo committed
2382 2383 2384 2385 2386 2387 2388 2389
            orgValidateDto2.setValue(orgDto.getTaxPayerNumber());
            if (!taxPayerNumberUniqueValidate(orgValidateDto2)) {
                return new OperationResultDto(false, OrganizationMessage.OrgNameOrCodeIsExiste);
            }
            Organization orgOriginal = new Organization();
            orgOriginal = CommonUtils.copyProperties(org, orgOriginal);
            orgOriginal.setpLevel(orgOriginal.getpLevel());
            // 上级机构验证
2390 2391 2392
            if (Strings.isBlank(orgDto.getParentId())
                    || Strings.equals(orgDto.getParentId(), OrganizationConstant.NoParentId)) {
                orgDto.setParentId(null);
eddie.woo's avatar
eddie.woo committed
2393 2394 2395
                org.setpLevel(0);
            } else {
                // 机构添加层级
2396
                Organization query = organizationMapper.selectByPrimaryKey(orgDto.getParentId());
eddie.woo's avatar
eddie.woo committed
2397 2398 2399 2400 2401
                if (query != null) {
                    org.setpLevel(query.getpLevel() + 1);
                }
            }

2402
            if (!Strings.equals(orgDto.getParentId(), org.getParentId())) {
eddie.woo's avatar
eddie.woo committed
2403
                // 如果修改了上级机构
2404 2405 2406
                OperationResultDto<Object> checkParentIdRet = checkParentId(orgDto);
                if (checkParentIdRet != null && !checkParentIdRet.getResult()) {
                    return checkParentIdRet;
eddie.woo's avatar
eddie.woo committed
2407 2408
                }
            }
2409 2410

            /*org.setName(orgDto.getName());
eddie.woo's avatar
eddie.woo committed
2411
            org.setTaxPayerNumber(orgDto.getTaxPayerNumber());
2412 2413 2414 2415 2416
            org.setParentId(orgDto.getParentId());
            org.setStructureId(orgDto.getStructureId());
            org.setRegionId(orgDto.getRegionId());
            org.setAreaId(orgDto.getAreaId());
            org.setIndustryId(orgDto.getIndustryId());
2417 2418 2419 2420
            org.setBusinessUnitId(orgDto.getBusinessUnitId());*/

            beanUtil.copyProperties(orgDto,org);
            org.setUpdateTime(new Date());
eddie.woo's avatar
eddie.woo committed
2421 2422
            Organization orgUpdate = org;

2423
            organizationMapper.updateByPrimaryKeySelective(org);
eddie.woo's avatar
eddie.woo committed
2424 2425 2426 2427 2428 2429 2430 2431 2432

            OperationResultDto<Object> validatesetRet = validateEnterpriseAccountSetDateTimeOverlap(
                    orgDto.getEnterpriseAccountSetOrgList());
            if (!validatesetRet.getResult()) {
                return validatesetRet;
            }

            // 更新机构账套
            EnterpriseAccountSetOrgExample example = new EnterpriseAccountSetOrgExample();
2433
            pwc.taxtech.atms.entity.EnterpriseAccountSetOrgExample.Criteria criteria = example.createCriteria();
2434 2435
            if (orgDto.getId() != null) {
                criteria.andOrganizationIdEqualTo(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
2436
            } else {
2437
                criteria.andOrganizationIdIsNull();
eddie.woo's avatar
eddie.woo committed
2438 2439 2440
            }
            List<EnterpriseAccountSetOrg> enterpriseAccountSetOrgList = enterpriseAccountSetOrgMapper
                    .selectByExample(example);
gary's avatar
gary committed
2441 2442 2443

            EnterpriseAccountSetOrgExample e2 = new EnterpriseAccountSetOrgExample();

eddie.woo's avatar
eddie.woo committed
2444 2445 2446
            for (EnterpriseAccountSetOrgDto p : orgDto.getEnterpriseAccountSetOrgList()) {
                p.setEffectiveDate(Strings.isBlank(p.getEffectiveDateStr()) ? p.getEffectiveDate()
                        : DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(p.getEffectiveDateStr() + "-01")
2447
                        .toDate());
eddie.woo's avatar
eddie.woo committed
2448 2449
                p.setExpiredDate(Strings.isBlank(p.getExpiredDateStr()) ? p.getExpiredDate()
                        : DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(p.getExpiredDateStr() + "-01")
2450
                        .plusMonths(1).minusDays(1).toDate());
eddie.woo's avatar
eddie.woo committed
2451
                if (enterpriseAccountSetOrgList != null
2452
                        && enterpriseAccountSetOrgList.stream().anyMatch(t -> Strings.equals(t.getId(), p.getId()))) {
eddie.woo's avatar
eddie.woo committed
2453
                    EnterpriseAccountSetOrg tempDto = enterpriseAccountSetOrgList.stream()
2454
                            .filter(t -> Strings.equals(t.getId(), p.getId())).findFirst().orElse(null);
eddie.woo's avatar
eddie.woo committed
2455 2456
                    Assert.notNull(tempDto, "tempDto null exception on updateOrg");
                    tempDto.setEffectiveDate(p.getEffectiveDate());
2457
                    tempDto.setEnterpriseAccountSetId(p.getEnterpriseAccountSetId());
eddie.woo's avatar
eddie.woo committed
2458 2459 2460 2461
                    tempDto.setExpiredDate(p.getExpiredDate());
                    enterpriseAccountSetOrgMapper.updateByPrimaryKey(tempDto);
                } else {
                    EnterpriseAccountSetOrg temp = new EnterpriseAccountSetOrg();
2462 2463 2464
                    temp.setId(CommonUtils.getUUID());
                    temp.setEnterpriseAccountSetId(p.getEnterpriseAccountSetId());
                    temp.setOrganizationId(p.getOrganizationId());
eddie.woo's avatar
eddie.woo committed
2465 2466 2467 2468 2469 2470 2471
                    temp.setEffectiveDate(p.getEffectiveDate());
                    temp.setExpiredDate(p.getExpiredDate());
                    enterpriseAccountSetOrgMapper.insert(temp);
                }
            }

            List<EnterpriseAccountSetOrg> deleteSetList = enterpriseAccountSetOrgList.stream().filter(p -> orgDto
2472
                    .getEnterpriseAccountSetOrgList().stream().noneMatch(sa -> Strings.equals(sa.getId(), p.getId())))
eddie.woo's avatar
eddie.woo committed
2473 2474 2475 2476
                    .collect(Collectors.toList());

            if (deleteSetList != null && !deleteSetList.isEmpty()) {
                deleteSetList.stream()
2477
                        .forEach(delSet -> enterpriseAccountSetOrgMapper.deleteByPrimaryKey(delSet.getId()));
eddie.woo's avatar
eddie.woo committed
2478 2479 2480
            }

            OrganizationServiceTemplateGroupExample oSTGExample = new OrganizationServiceTemplateGroupExample();
2481
            pwc.taxtech.atms.entity.OrganizationServiceTemplateGroupExample.Criteria oSTGCriteria = oSTGExample
eddie.woo's avatar
eddie.woo committed
2482
                    .createCriteria();
2483 2484
            if (orgDto.getId() != null) {
                oSTGCriteria.andOrganizationIdEqualTo(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
2485
            } else {
2486
                oSTGCriteria.andOrganizationIdIsNull();
eddie.woo's avatar
eddie.woo committed
2487 2488 2489 2490 2491 2492 2493
            }
            List<OrganizationServiceTemplateGroup> currentOrganizationServiceTemplateGroupList = organizationServiceTemplateGroupMapper
                    .selectByExample(oSTGExample);

            List<OrganizationServiceTemplateGroup> updateOrganizationServiceTemplateGroupList = new ArrayList<>();
            TaxPayerReportRuleExample taxExample = new TaxPayerReportRuleExample();
            taxExample.or().andIsDefaultEqualTo(true);
2494 2495
            Assert.notNull(orgDto.getId(), "orgDto id null exception on updateOrg");
            String sqlValue = "%" + orgDto.getId() + "%";
2496
            taxExample.or().andOrganizationIdLike(sqlValue);
eddie.woo's avatar
eddie.woo committed
2497 2498
            List<TaxPayerReportRule> reportRules = taxPayerReportRuleMapper.selectByExample(taxExample);
            TaxPayerReportRule activeRule = reportRules.stream()
2499
                    .filter(t -> t.getOrganizationId() == null ? false : t.getOrganizationId().contains(orgDto.getId()))
eddie.woo's avatar
eddie.woo committed
2500 2501 2502 2503 2504
                    .findFirst().orElse(null);
            // C#中在此处定义的defaultRule在下文中未被引用,JAVA中将其删除

            // 更新机构服务
            currentOrganizationServiceTemplateGroupList.stream()
2505
                    .forEach(tg -> organizationServiceTemplateGroupMapper.deleteByPrimaryKey(tg.getId()));
eddie.woo's avatar
eddie.woo committed
2506 2507 2508

            // For VAT, update Rule Engine tables instead of
            OrganizationServiceTemplateGroupDto vatSetting = orgDto.getOrganizationServiceTemplateGroupList().stream()
2509
                    .filter(t -> Strings.equals(t.getServiceTypeId(), ServiceTypeEnum.VAT.value().toString()))
eddie.woo's avatar
eddie.woo committed
2510 2511
                    .findFirst().orElse(null);
            if (vatSetting != null) {
2512 2513
                TemplateGroup templateGrp = vatSetting.getTemplateGroupId() != null
                        ? templateGroupMapper.selectByPrimaryKey(vatSetting.getTemplateGroupId())
eddie.woo's avatar
eddie.woo committed
2514 2515 2516 2517 2518
                        : null;
                // In organization module tax payer type is 1&2 while 0&1 in rule engine
                int newTaxPayerType = (templateGrp != null && templateGrp.getPayTaxType() != null)
                        ? (templateGrp.getPayTaxType() - 1)
                        : (VatTaxPayerTypeEnum.General.value());
2519
                if ((activeRule != null)
2520
                        && (Long.compare(activeRule.getTemplateGroupId(), vatSetting.getTemplateGroupId()) != 0)) {
eddie.woo's avatar
eddie.woo committed
2521
                    // Multiple organizations in 1 rule
2522
                    if (!Strings.equals(activeRule.getOrganizationId(), orgDto.getId())) {
2523
                        activeRule.setOrganizationId(
2524
                                activeRule.getOrganizationId().replace(orgDto.getId(), "").replace(",,", ","));
eddie.woo's avatar
eddie.woo committed
2525 2526
                        Date now = new Date();
                        TaxPayerReportRule newRule = new TaxPayerReportRule();
2527
                        newRule.setId(distributedIdService.nextId());
eddie.woo's avatar
eddie.woo committed
2528
                        newRule.setIsDefault(false);
2529 2530
                        newRule.setOrganizationId(orgDto.getId());
                        newRule.setTemplateGroupId(vatSetting.getTemplateGroupId());
eddie.woo's avatar
eddie.woo committed
2531 2532 2533
                        newRule.setTaxPayerType(newTaxPayerType); // Use tax payer type related to template group
                        newRule.setCreateTime(now);
                        newRule.setUpdateTime(now);
2534 2535 2536 2537 2538 2539 2540 2541
                        TaxPayerReportRuleExample exam = new TaxPayerReportRuleExample();
                        exam.createCriteria().andOrganizationIdEqualTo(orgDto.getId()).andTemplateGroupIdEqualTo(vatSetting.getTemplateGroupId());
                        List<TaxPayerReportRule> rules = taxPayerReportRuleMapper.selectByExample(exam);
                        if (!rules.isEmpty()) {
                            newRule.setId(rules.get(0).getId());
                            taxPayerReportRuleMapper.updateByPrimaryKeySelective(newRule);
                        } else
                            taxPayerReportRuleMapper.insertSelective(newRule);
eddie.woo's avatar
eddie.woo committed
2542
                    } else {
2543
                        activeRule.setTemplateGroupId(vatSetting.getTemplateGroupId());
eddie.woo's avatar
eddie.woo committed
2544
                        activeRule.setTaxPayerType(newTaxPayerType);
2545
                        taxPayerReportRuleMapper.updateByPrimaryKeySelective(activeRule);
eddie.woo's avatar
eddie.woo committed
2546 2547 2548 2549
                    }
                } else { // If currently no rule and new rule should be added
                    Date now = new Date();
                    TaxPayerReportRule newRule = new TaxPayerReportRule();
2550
                    newRule.setId(distributedIdService.nextId());
eddie.woo's avatar
eddie.woo committed
2551
                    newRule.setIsDefault(false);
2552 2553
                    newRule.setOrganizationId(orgDto.getId());
                    newRule.setTemplateGroupId(vatSetting.getTemplateGroupId());
eddie.woo's avatar
eddie.woo committed
2554 2555 2556
                    newRule.setTaxPayerType(newTaxPayerType); // Use tax payer type related to template group
                    newRule.setCreateTime(now);
                    newRule.setUpdateTime(now);
2557 2558 2559 2560 2561 2562 2563 2564 2565

                    TaxPayerReportRuleExample exam = new TaxPayerReportRuleExample();
                    exam.createCriteria().andOrganizationIdEqualTo(orgDto.getId()).andTemplateGroupIdEqualTo(vatSetting.getTemplateGroupId());
                    List<TaxPayerReportRule> rules = taxPayerReportRuleMapper.selectByExample(exam);
                    if (!rules.isEmpty()) {
                        newRule.setId(rules.get(0).getId());
                        taxPayerReportRuleMapper.updateByPrimaryKeySelective(newRule);
                    } else
                        taxPayerReportRuleMapper.insertSelective(newRule);
eddie.woo's avatar
eddie.woo committed
2566 2567
                }
            } else if (activeRule != null) { // If no setting, remove non-default rule
2568
                taxPayerReportRuleMapper.deleteByPrimaryKey(activeRule.getId());
eddie.woo's avatar
eddie.woo committed
2569 2570 2571
            }
            for (OrganizationServiceTemplateGroupDto p : orgDto.getOrganizationServiceTemplateGroupList()) {
                OrganizationServiceTemplateGroup temp = new OrganizationServiceTemplateGroup();
2572 2573 2574 2575
                temp.setId(distributedIdService.nextId());
                temp.setOrganizationId(orgDto.getId());
                temp.setServiceTypeId(p.getServiceTypeId());
                temp.setTemplateGroupId(p.getTemplateGroupId());
eddie.woo's avatar
eddie.woo committed
2576
                updateOrganizationServiceTemplateGroupList.add(temp);
2577
                organizationServiceTemplateGroupMapper.insertSelective(temp);
eddie.woo's avatar
eddie.woo committed
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601
            }

            // 更新自定义属性
            // C#中的内部类CommonLogParams 在JAVA中替换成UpdateLogParams中
            List<UpdateLogParams> selfDimensionList;
            selfDimensionList = updateSelfDimensionList(orgDto);

            UpdateLogParams updateLogParams = new UpdateLogParams();
            updateLogParams.setOriginalState(orgOriginal);
            updateLogParams.setUpdateState(orgUpdate);
            updateLogParams.setOperationModule(Organization.value());
            updateLogParams.setOperateLogType(OperationLogOrganization.value());
            updateLogParams.setOperationContent(orgUpdate.getName());
            updateLogParams.setOperationObject(org.getName());
            updateLogParams.setOperationAction(OperationAction.Update.value());
            updateLogParams.setComment("");
            operationLogService.updateDataAddLog(updateLogParams);

            updateEnterpriseAccountSetOrgLog(org.getName(), enterpriseAccountSetOrgList,
                    orgDto.getEnterpriseAccountSetOrgList());
            updateOrganizationServiceTemplateGroupLog(org.getName(), currentOrganizationServiceTemplateGroupList,
                    updateOrganizationServiceTemplateGroupList);
            operationLogService.addOrDeleteDataAddLog(selfDimensionList);
            return new OperationResultDto(true);
gary's avatar
gary committed
2602 2603 2604
        } catch (DuplicateKeyException e) {
            //万不得已出此下策
            return new OperationResultDto(true, "保存成功!");
eddie.woo's avatar
eddie.woo committed
2605 2606 2607 2608 2609 2610 2611 2612
        } catch (Exception ex) {
            logger.error("UpdateOrg出错了:" + ex, ex);
            logger.error("标记回滚, ready to call setRollbackOnly");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new OperationResultDto(false, ex.getMessage());
        }
    }

gary's avatar
gary committed
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
    /**
     * 16/01/2019 14:26
     * 根据唯一主键进行更新机构其他信息,缺少逻辑校验
     * [orgExtraDto]
     * @author Gary J Li
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public OperationResultDto<Object> updateOrgExtra(OrganizationExtraDto orgExtraDto) {
        try {
            OrganizationExtra orgExtra = new OrganizationExtra();
            BeanUtils.copyProperties(orgExtraDto,orgExtra);
            // 根据唯一主键进行更新
2626 2627 2628 2629 2630 2631 2632 2633
            if(null==orgExtra.getId()){
                orgExtra.setId(idService.nextId());
                organizationExtraMapper.insertSelective(orgExtra);
            }else{
                OrganizationExtraExample orgExtraExample = new OrganizationExtraExample();
                orgExtraExample.createCriteria().andIdEqualTo(orgExtraDto.getId());
                organizationExtraMapper.updateByExampleSelective(orgExtra,orgExtraExample);
            }
gary's avatar
gary committed
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
            // todo 暂时未做校验
            return new OperationResultDto(true);
        }catch (Exception ex) {
            logger.error("UpdateOrgExtra出错了:" + ex, ex);
            logger.error("标记回滚, ready to call setRollbackOnly");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new OperationResultDto(false, ex.getMessage());
        }
    }

eddie.woo's avatar
eddie.woo committed
2644
    private void updateOrganizationServiceTemplateGroupLog(String operateObject,
2645
                                                           List<OrganizationServiceTemplateGroup> currentList, List<OrganizationServiceTemplateGroup> updateList) {
eddie.woo's avatar
eddie.woo committed
2646 2647 2648 2649 2650 2651
        currentList = currentList == null ? new ArrayList<>() : currentList;
        updateList = updateList == null ? new ArrayList<>() : updateList;
        // 新增
        List<OrganizationServiceTemplateGroup> tempCurrentList = currentList;
        List<OrganizationServiceTemplateGroup> addList = updateList.stream()
                .filter(p -> !tempCurrentList.stream()
2652
                        .anyMatch(sa -> Strings.equals(sa.getServiceTypeId(), p.getServiceTypeId())))
eddie.woo's avatar
eddie.woo committed
2653 2654 2655 2656 2657 2658
                .collect(Collectors.toList());

        // 删除
        List<OrganizationServiceTemplateGroup> tempUpdateList = updateList;
        List<OrganizationServiceTemplateGroup> deleteList = currentList.stream()
                .filter(p -> !tempUpdateList.stream()
2659
                        .anyMatch(sa -> Strings.equals(sa.getServiceTypeId(), p.getServiceTypeId())))
eddie.woo's avatar
eddie.woo committed
2660 2661 2662 2663 2664
                .collect(Collectors.toList());

        // 修改
        List<OrganizationServiceTemplateGroup> updates = updateList.stream()
                .filter(p -> tempCurrentList.stream()
2665 2666
                        .anyMatch(sa -> Strings.equals(sa.getServiceTypeId(), p.getServiceTypeId())
                                && (Long.compare(sa.getTemplateGroupId(), p.getTemplateGroupId()) != 0)))
eddie.woo's avatar
eddie.woo committed
2667 2668 2669 2670 2671 2672 2673 2674
                .collect(Collectors.toList());

        List<UpdateLogParams> addLogList = new ArrayList<>();

        List<TemplateGroup> queryTemplate = templateGroupMapper.selectByExample(null);
        List<ServiceType> queryService = serviceTypeMapper.selectByExample(null);

        for (OrganizationServiceTemplateGroup item : addList) {
2675
            ServiceType st1 = queryService.stream().filter(sa -> Strings.equals(sa.getId(), item.getServiceTypeId()))
eddie.woo's avatar
eddie.woo committed
2676 2677 2678
                    .findFirst().orElse(null);
            Assert.notNull(st1, "queryService result null exception in updateOrganizationServiceTemplateGroupLog");
            TemplateGroup st2 = queryTemplate.stream()
2679
                    .filter(sa -> Long.compare(sa.getId(), item.getTemplateGroupId()) == 0).findFirst().orElse(null);
eddie.woo's avatar
eddie.woo committed
2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
            Assert.notNull(st2, "queryTemplate result null exception in updateOrganizationServiceTemplateGroupLog");
            String updateStr = st1.getName() + CommonConstants.OneSpace + st2.getName();
            UpdateLogParams updateLogParams = new UpdateLogParams();
            updateLogParams.setUpdateState(updateStr);
            updateLogParams.setOriginalState("");
            updateLogParams.setOperationContent(OrganizationMessage.OrganizationServiceTemplateGroup);
            updateLogParams.setOperationObject(operateObject);
            updateLogParams.setOperationModule(OperationModule.Organization.value());
            updateLogParams.setOperateLogType(OperateLogType.OperationLogOrganization.value());
            updateLogParams.setComment("");
            updateLogParams.setOperationAction(OperationAction.New.value());
            addLogList.add(updateLogParams);
        }

2694 2695
        //todo: just for test at here, remove comment later
//        for (OrganizationServiceTemplateGroup item : deleteList) {
2696
//            ServiceType st1 = queryService.stream().filter(sa -> Strings.equals(sa.getId(), item.getServiceTypeId()))
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713
//                    .findFirst().orElse(null);
//            Assert.notNull(st1, "queryService result null exception on updateOrganizationServiceTemplateGroupLog");
//            TemplateGroup st2 = queryTemplate.stream()
//                    .filter(sa -> Long.compare(sa.getId(), item.getTemplateGroupId())==0).findFirst().orElse(null);
//            Assert.notNull(st2, "queryTemplate result null exception on updateOrganizationServiceTemplateGroupLog");
//            String updateStr = st1.getName() + CommonConstants.OneSpace + st2.getName();
//            UpdateLogParams updateLogParams = new UpdateLogParams();
//            updateLogParams.setUpdateState("");
//            updateLogParams.setOriginalState(updateStr);
//            updateLogParams.setOperationContent(OrganizationMessage.OrganizationServiceTemplateGroup);
//            updateLogParams.setOperationObject(operateObject);
//            updateLogParams.setOperationModule(OperationModule.Organization.value());
//            updateLogParams.setOperateLogType(OperateLogType.OperationLogOrganization.value());
//            updateLogParams.setComment("");
//            updateLogParams.setOperationAction(OperationAction.Delete.value());
//            addLogList.add(updateLogParams);
//        }
eddie.woo's avatar
eddie.woo committed
2714

2715 2716 2717 2718 2719 2720
//        for (OrganizationServiceTemplateGroup item : updates) {
//            OrganizationServiceTemplateGroup current = currentList.stream()
//                    .filter(sa -> Strings.equals(sa.getServiceTypeId(), item.getServiceTypeId())).findFirst()
//                    .orElse(null);
//            if (current != null) {
//                ServiceType tService = queryService.stream()
2721
//                        .filter(sa -> Strings.equals(sa.getId(), item.getServiceTypeId())).findFirst().orElse(null);
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750
//                Assert.notNull(tService, "tService null exception in updateOrganizationServiceTemplateGroupLog");
//                String serviceName = tService.getName();
//
//                TemplateGroup updateTemplate = queryTemplate.stream()
//                        .filter(sa -> Long.compare(sa.getId(), item.getTemplateGroupId())==0).findFirst().orElse(null);
//                Assert.notNull(updateTemplate,
//                        "updateTemplate null exception in updateOrganizationServiceTemplateGroupLog");
//                String updateStr = updateTemplate.getName();
//
//                TemplateGroup currentTemplate = queryTemplate.stream()
//                        .filter(sa -> Long.compare(sa.getId(), current.getTemplateGroupId())==0).findFirst()
//                        .orElse(null);
//                Assert.notNull(currentTemplate,
//                        "currentTemplate null exception in updateOrganizationServiceTemplateGroupLog");
//                String currentStr = currentTemplate.getName();
//
//                UpdateLogParams updateLogParams = new UpdateLogParams();
//                updateLogParams.setUpdateState(updateStr);
//                updateLogParams.setOriginalState(currentStr);
//                updateLogParams.setOperationContent(OrganizationMessage.OrganizationServiceTemplateGroup);
//                updateLogParams.setOperationObject(operateObject + DashSignSeparator + serviceName);
//                updateLogParams.setOperationModule(OperationModule.Organization.value());
//                updateLogParams.setOperateLogType(OperateLogType.OperationLogOrganization.value());
//                updateLogParams.setComment("");
//                updateLogParams.setOperationAction(OperationAction.Update.value());
//                addLogList.add(updateLogParams);
//            }
//
//        }
eddie.woo's avatar
eddie.woo committed
2751 2752 2753 2754
        operationLogService.addOrDeleteDataAddLog(addLogList);
    }

    private void updateEnterpriseAccountSetOrgLog(String operateObject, List<EnterpriseAccountSetOrg> currentList,
2755
                                                  List<EnterpriseAccountSetOrgDto> updateList) {
eddie.woo's avatar
eddie.woo committed
2756 2757 2758 2759 2760 2761
        List<String> fromList = new ArrayList<>();
        List<String> toList = new ArrayList<>();
        List<EnterpriseAccountSet> set = enterpriseAccountSetMapper.selectByExample(null);
        if (currentList != null && !currentList.isEmpty()) {
            fromList = set.stream()
                    .filter(q -> currentList.stream()
2762 2763
                            .anyMatch(p -> Strings.equals(p.getEnterpriseAccountSetId(), q.getId())))
                    .sorted(comparing(EnterpriseAccountSet::getId, nullsFirst(naturalOrder())))
eddie.woo's avatar
eddie.woo committed
2764 2765 2766 2767 2768
                    .map(EnterpriseAccountSet::getName).collect(Collectors.toList());
        }
        if (updateList != null && !updateList.isEmpty()) {
            toList = set.stream()
                    .filter(q -> updateList.stream()
2769 2770
                            .anyMatch(p -> Strings.equals(p.getEnterpriseAccountSetId(), q.getId())))
                    .sorted(comparing(EnterpriseAccountSet::getId, nullsFirst(naturalOrder())))
eddie.woo's avatar
eddie.woo committed
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789
                    .map(EnterpriseAccountSet::getName).collect(Collectors.toList());
        }
        String from = String.join(Comma, fromList);
        String to = String.join(Comma, toList);

        if (!Strings.equals(from, to)) {
            UpdateLogParams log = new UpdateLogParams();
            log.setOperationAction(OperationAction.Update.value());
            log.setComment("");
            log.setOperateLogType(OperateLogType.OperationLogOrganization.value());
            log.setOperationModule(OperationModule.Organization.value());
            log.setOperationObject(operateObject);
            log.setOperationContent(OrganizationMessage.RelevantEnterpriseAccountSet);
            log.setOriginalState(from);
            log.setUpdateState(to);
            operationLogService.addOrDeleteDataAddLog(log);
        }
    }

gary's avatar
gary committed
2790 2791 2792 2793 2794 2795 2796
    /**
     * 19/02/2019 19:26
     *
     * [userId]
     * @author Gary J Li
     * @return
     */
gary's avatar
gary committed
2797
    public List<OrgSelectDto> getOrgSimpleList() {
gary's avatar
gary committed
2798
        String userId = authUserHelper.getCurrentUserId();
gary's avatar
gary committed
2799
        List<OrgSelectDto> orgSelectDtos = Lists.newArrayList();
gary's avatar
gary committed
2800 2801 2802 2803 2804 2805 2806 2807
        UserOrganizationExample userOrganizationExample = new UserOrganizationExample();
        userOrganizationExample.createCriteria().andUserIdEqualTo(userId);
        List<UserOrganization> userOrganizations = userOrganizationMapper.selectByExample(userOrganizationExample);
        List<String> orgIds = userOrganizations.stream().map(UserOrganization::getOrganizationId).collect(Collectors.toList());
        OrganizationExample organizationExample = new OrganizationExample();
        organizationExample.createCriteria().andIdIn(orgIds);
        List<Organization> organizations = organizationMapper.selectByExample(organizationExample);
        organizations.forEach(o -> {
gary's avatar
gary committed
2808 2809
            OrgSelectDto orgSelectDto = beanUtil.copyProperties(o,new OrgSelectDto());
            orgSelectDtos.add(orgSelectDto);
gary's avatar
gary committed
2810
        });
gary's avatar
gary committed
2811
        return orgSelectDtos;
gary's avatar
gary committed
2812 2813
    }

eddie.woo's avatar
eddie.woo committed
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828
    /**
     * 修改自定义纬度的值
     */
    private List<UpdateLogParams> updateSelfDimensionList(OrganizationDto orgDto) {
        Assert.notNull(orgDto, "orgDto null exception in updateSelfDimensionList");
        List<UpdateLogParams> logList = new ArrayList<>();
        DimensionExample example1 = new DimensionExample();
        example1.createCriteria().andIsActiveEqualTo(true);
        List<Dimension> dimensionList = dimensionMapper.selectByExample(example1);

        DimensionValueExample example2 = new DimensionValueExample();
        example2.createCriteria().andIsActiveEqualTo(true);
        List<DimensionValue> dimensionValueList = dimensionValueMapper.selectByExample(example2);

        DimensionValueOrgExample example3 = new DimensionValueOrgExample();
2829
        example3.createCriteria().andOrganizationIdEqualTo(orgDto.getId());
eddie.woo's avatar
eddie.woo committed
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
        List<DimensionValueOrg> oldDimensionOrgList = dimensionValueOrgMapper.selectByExample(example3);
        List<DimensionValueOrgDto> newDimensionOrgList = orgDto.getDimensionValueOrgList();

        if (newDimensionOrgList == null) {
            newDimensionOrgList = new ArrayList<>();
        }

        if (oldDimensionOrgList.isEmpty() && newDimensionOrgList.isEmpty()) {
            return logList;
        }
        List<DimensionValueJoinDimensionDto> queryInfo = dimensionValueMapper.selectDimensionValueJoinDimension();

        List<DimensionValueOrg> updateDimensionOrgList = new ArrayList<>();
        List<DimensionValueOrg> addDimensionOrgList = new ArrayList<>();
        List<DimensionValueOrg> deleteDimensionOrgList = new ArrayList<>();

        for (Dimension dimension : dimensionList) {
            List<String> valueList = dimensionValueList.stream()
2848 2849
                    .filter(p -> Strings.equals(p.getDimensionId(), dimension.getId()))
                    .map(p -> p.getId().toLowerCase()).collect(Collectors.toList());
eddie.woo's avatar
eddie.woo committed
2850 2851

            DimensionValueOrg old = oldDimensionOrgList.stream()
2852
                    .filter(p -> valueList.contains(p.getDimensionValueId().toLowerCase())).findFirst().orElse(null);
eddie.woo's avatar
eddie.woo committed
2853 2854

            DimensionValueOrgDto newObj = newDimensionOrgList.stream()
2855
                    .filter(p -> valueList.contains(p.getDimensionValueId().toLowerCase())).findFirst().orElse(null);
eddie.woo's avatar
eddie.woo committed
2856 2857 2858 2859 2860 2861 2862 2863

            // 都没有值
            if (old == null && newObj == null) {
                continue;
            }

            // 两个都有值
            if (old != null && newObj != null) {
2864
                old.setDimensionValueId(newObj.getDimensionId());
eddie.woo's avatar
eddie.woo committed
2865 2866 2867
                updateDimensionOrgList.add(old);

                DimensionValueJoinDimensionDto info = queryInfo.stream()
2868
                        .filter(sa -> Strings.equals(sa.getDimensionValueId(), old.getDimensionValueId())).findFirst()
eddie.woo's avatar
eddie.woo committed
2869 2870
                        .orElse(null);
                DimensionValueJoinDimensionDto newInfo = queryInfo.stream()
2871
                        .filter(sa -> Strings.equals(sa.getDimensionValueId(), newObj.getDimensionValueId()))
eddie.woo's avatar
eddie.woo committed
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
                        .findFirst().orElse(null);
                // 修改
                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setOperationAction(OperationAction.Update.value());
                updateLogParams.setComment("");
                updateLogParams.setOperateLogType(OperationLogOrganization.value());
                updateLogParams.setOperationModule(Organization.value());
                updateLogParams.setOperationObject(orgDto.getName());
                updateLogParams.setOperationContent(info == null ? "" : info.getDimensionName());
                updateLogParams.setOriginalState(info == null ? "" : info.getDimensionValue());
                updateLogParams.setUpdateState(newInfo == null ? "" : newInfo.getDimensionValue());
                logList.add(updateLogParams);
            }

            if (old != null && newObj == null) {
                // 需要删除
                deleteDimensionOrgList.add(old);
                DimensionValueJoinDimensionDto info = queryInfo.stream()
2890
                        .filter(sa -> Strings.equals(sa.getDimensionValueId(), old.getDimensionValueId())).findFirst()
eddie.woo's avatar
eddie.woo committed
2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
                        .orElse(null);

                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setOperationAction(OperationAction.Update.value());
                updateLogParams.setComment("");
                updateLogParams.setOperateLogType(OperationLogOrganization.value());
                updateLogParams.setOperationModule(Organization.value());
                updateLogParams.setOperationObject(orgDto.getName());
                updateLogParams.setOperationContent(info == null ? "" : info.getDimensionName());
                updateLogParams.setOriginalState(info == null ? "" : info.getDimensionValue());
                updateLogParams.setUpdateState("");
                logList.add(updateLogParams);
            }

            if (old == null && newObj != null) {
                // 需要添加
                DimensionValueOrg dimensionValueOrg = new DimensionValueOrg();
2908 2909 2910
                dimensionValueOrg.setDimensionValueId(newObj.getDimensionValueId());
                dimensionValueOrg.setOrganizationId(orgDto.getId());
                dimensionValueOrg.setId(CommonUtils.getUUID());
eddie.woo's avatar
eddie.woo committed
2911 2912 2913
                addDimensionOrgList.add(dimensionValueOrg);

                DimensionValueJoinDimensionDto info = queryInfo.stream()
2914
                        .filter(sa -> Strings.equals(sa.getDimensionValueId(), newObj.getDimensionValueId()))
eddie.woo's avatar
eddie.woo committed
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
                        .findFirst().orElse(null);
                UpdateLogParams updateLogParams = new UpdateLogParams();
                updateLogParams.setOperationAction(OperationAction.Update.value());
                updateLogParams.setComment("");
                updateLogParams.setOperateLogType(OperationLogOrganization.value());
                updateLogParams.setOperationModule(Organization.value());
                updateLogParams.setOperationObject(orgDto.getName());
                updateLogParams.setOperationContent(info == null ? "" : info.getDimensionName());
                updateLogParams.setOriginalState("");
                updateLogParams.setUpdateState(info == null ? "" : info.getDimensionValue());
                logList.add(updateLogParams);
            }
        }
        if (!addDimensionOrgList.isEmpty()) {
            addDimensionOrgList.stream().forEach(d -> dimensionValueOrgMapper.insert(d));
        }

        if (!updateDimensionOrgList.isEmpty()) {
            updateDimensionOrgList.stream().forEach(d -> dimensionValueOrgMapper.updateByPrimaryKey(d));
        }

        if (!deleteDimensionOrgList.isEmpty()) {
2937
            deleteDimensionOrgList.stream().forEach(d -> dimensionValueOrgMapper.deleteByPrimaryKey(d.getId()));
eddie.woo's avatar
eddie.woo committed
2938 2939 2940 2941
        }
        return logList;
    }

2942
    @SuppressWarnings({"rawtypes", "unchecked"})
2943 2944 2945
    private OperationResultDto<Object> checkParentId(OrganizationDto orgDto) {
        if (Strings.equals(orgDto.getParentId(), orgDto.getId())) {
            return new OperationResultDto(false, OrganizationMessage.ParentIdCannotEqualsId);
eddie.woo's avatar
eddie.woo committed
2946 2947 2948 2949 2950
        }

        OrganizationExample example = new OrganizationExample();
        example.createCriteria().andIsActiveEqualTo(true);
        List<Organization> orgList = organizationMapper.selectByExample(example);
2951 2952 2953 2954
        List<Organization> subList = this.getSubOrganization(orgDto.getId(), orgList);
        Assert.notNull(subList, "subList null exception in checkParentId");
        if (subList.stream().anyMatch(sa -> Strings.equals(sa.getId(), sa.getParentId()))) {
            return new OperationResultDto(false, OrganizationMessage.ParentIdCannotBeSubId);
eddie.woo's avatar
eddie.woo committed
2955 2956 2957 2958 2959 2960 2961 2962 2963
        }
        return new OperationResultDto(true);
    }

    /**
     * 获取所有子机构
     */
    private List<Organization> getSubOrganization(String orgid, List<Organization> orglist) {
        List<Organization> retList = new ArrayList<>();
2964
        List<Organization> subList = orglist.stream().filter(sa -> Strings.equals(sa.getParentId(), orgid))
eddie.woo's avatar
eddie.woo committed
2965 2966 2967 2968 2969 2970 2971
                .collect(Collectors.toList());

        if (!subList.isEmpty()) {
            subList.stream().forEach(s -> retList.add(s));
        }

        for (Organization item : subList) {
2972
            List<Organization> tempList = getSubOrganization(item.getId(), orglist);
eddie.woo's avatar
eddie.woo committed
2973 2974 2975 2976 2977 2978 2979
            if (!tempList.isEmpty()) {
                tempList.stream().forEach(t -> retList.add(t));
            }
        }
        return retList;
    }

2980 2981
    public OrgGeneralInfoDto getGeneralInfo(String orgId) {
        return getOrgGeneralInfo(orgId);
eddie.woo's avatar
eddie.woo committed
2982 2983
    }

eddie.woo's avatar
eddie.woo committed
2984 2985 2986 2987 2988 2989 2990
    public List<DevTreeDto> getOrgIvhTreeList(Integer useType, String orgSetId) {
        //todo
        List<DevTreeDto> result = Lists.newArrayList();
        List<IvhTreeDto> orgDtoList = Lists.newArrayList();
        List<Organization> orgList;
        OrganizationExample orgExample = new OrganizationExample();

2991
        if (useType < 2) {
eddie.woo's avatar
eddie.woo committed
2992
            orgList = organizationMapper.selectByExample(orgExample);
2993
        } else {
eddie.woo's avatar
eddie.woo committed
2994 2995
            EnterpriseAccountSetOrgExample tmpExample = new EnterpriseAccountSetOrgExample();
            EnterpriseAccountSetOrgExample.Criteria criteria = tmpExample.createCriteria();
2996
            criteria.andEnterpriseAccountSetIdEqualTo(orgSetId);
eddie.woo's avatar
eddie.woo committed
2997
            List<EnterpriseAccountSetOrg> enAccountSetOrgList = enterpriseAccountSetOrgMapper.selectByExample(tmpExample);
2998
            if (CollectionUtils.isNotEmpty(enAccountSetOrgList)) {
2999
                List<String> orgIdList = enAccountSetOrgList.stream().map(EnterpriseAccountSetOrg::getOrganizationId)
eddie.woo's avatar
eddie.woo committed
3000 3001
                        .collect(toList());
                OrganizationExample.Criteria orgCriteria = orgExample.createCriteria();
3002
                orgCriteria.andIdIn(orgIdList);
eddie.woo's avatar
eddie.woo committed
3003
                orgList = organizationMapper.selectByExample(orgExample);
3004
            } else {
eddie.woo's avatar
eddie.woo committed
3005 3006 3007 3008 3009 3010 3011
                orgList = Lists.newArrayList();
            }
        }
        if (CollectionUtils.isNotEmpty(orgList)) {
            //find rootOrg
            List<Organization> rootOrgList;
            if (useType == 1) {
gary's avatar
gary committed
3012
                rootOrgList = orgList.stream().filter(x -> StringUtils.isEmpty(x.getParentId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
3013
            } else {
gary's avatar
gary committed
3014
                rootOrgList = orgList.stream().filter(x -> StringUtils.isEmpty(x.getParentId()) && x.getIsActive())
eddie.woo's avatar
eddie.woo committed
3015 3016 3017 3018
                        .collect(toList());
            }
            List<ServiceType> serviceList = Lists.newArrayList();

3019
            for (Organization org : rootOrgList) {
eddie.woo's avatar
eddie.woo committed
3020 3021 3022 3023
                IvhTreeDto root = new IvhTreeDto();
                root.setChildren(Lists.newArrayList());
                root.setLabel(org.getName());
                root.setValue(org);
3024
                orgDtoList.add(generateIvhTreeDto(org, orgList, serviceList, useType));
eddie.woo's avatar
eddie.woo committed
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
            }

        }
        return orgDtoList.stream().map(this::devTreeDtoMapper).collect(toList());
    }

    private DevTreeDto devTreeDtoMapper(IvhTreeDto ivhTreeDto) {
        DevTreeDto dto = new DevTreeDto();
        dto.setText(ivhTreeDto.getLabel());
        List<IvhTreeDto> childList = ivhTreeDto.getChildren();
        if (CollectionUtils.isNotEmpty(childList)) {
            dto.setItems(Lists.newArrayList());
            for (IvhTreeDto ivh : childList) {
                dto.getItems().add(devTreeDtoMapper(ivh));
            }
        }
        dto.setId(ivhTreeDto.getId());
        dto.setData(ivhTreeDto);
        return dto;
    }

    private IvhTreeDto generateIvhTreeDto(Organization parentOrg, List<Organization> orgList,
                                          List<ServiceType> serviceList, int useType) {
        IvhTreeDto result = new IvhTreeDto();
        OrganizationDto parentOrgDto = new OrganizationDto();
        CommonUtils.copyProperties(parentOrg, parentOrgDto);
3051 3052
        if (null != parentOrg && StringUtils.isNotBlank(parentOrg.getId())) {
            parentOrgDto.setParentName(orgList.stream().filter(x -> StringUtils.equals(x.getId(), parentOrg.getParentId()))
eddie.woo's avatar
eddie.woo committed
3053 3054 3055 3056 3057
                    .findFirst().map(x -> x.getName()).orElse(StringUtils.EMPTY));
        }

        List<Organization> subOrgList;
        if (useType == 1) {
3058
            subOrgList = orgList.stream().filter(x -> StringUtils.equals(x.getParentId(), parentOrg.getId())).collect(toList());
eddie.woo's avatar
eddie.woo committed
3059
        } else {
3060
            subOrgList = orgList.stream().filter(x -> StringUtils.equals(x.getParentId(), parentOrg.getId()) && x.getIsActive())
eddie.woo's avatar
eddie.woo committed
3061 3062 3063 3064 3065 3066 3067 3068 3069
                    .collect(toList());
        }
        parentOrgDto.setSubOrgs(Lists.newArrayList());
        List<IvhTreeDto> children = Lists.newArrayList();

        //create and add subtrees to the current node
        for (Organization subOrg : subOrgList) {
            children.add(generateIvhTreeDto(subOrg, orgList, serviceList, useType));
        }
frank.xa.zhang's avatar
frank.xa.zhang committed
3070
        result.setId(parentOrg.getId());
eddie.woo's avatar
eddie.woo committed
3071 3072 3073 3074 3075 3076 3077
        result.setLabel(parentOrgDto.getName());
        result.setValue(parentOrgDto);
        result.setChildren(children);

        return result;
    }

3078
    private OrgGeneralInfoDto getOrgGeneralInfo(String orgId) {
eddie.woo's avatar
eddie.woo committed
3079
        List<OrgGeneralInfoMiddleDto> query = organizationMapper.selectJoinToOrgGeneralInfo();
3080
        List<OrgGeneralInfoMiddleDto> filter = query.stream().filter(x -> Strings.equals(x.getId(), orgId))
eddie.woo's avatar
eddie.woo committed
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095
                .collect(Collectors.toList());
        if (filter.isEmpty()) {
            return null;
        }

        List<String> serviceList = filter.stream().map(OrgGeneralInfoMiddleDto::getServiceName).distinct()
                .collect(Collectors.toList());
        List<String> accountSetList = filter.stream().map(OrgGeneralInfoMiddleDto::getAccountSetName).distinct()
                .collect(Collectors.toList());
        OrgGeneralInfoMiddleDto row = filter.get(0);

        String areaName = "";
        String businessUnitName = "";

        if (row.getAreaName() == null) {
3096
            areaName = getAreaNameById(row.getAreaId());
eddie.woo's avatar
eddie.woo committed
3097 3098 3099
        }

        if (row.getBusinessUnitName() == null) {
3100
            businessUnitName = getBusinessUnitNameById(row.getBusinessUnitId());
eddie.woo's avatar
eddie.woo committed
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
        }
        OrgGeneralInfoDto ret = new OrgGeneralInfoDto();
        ret.setOrgName(row.getOrgName());
        ret.setTaxPayerNumber(row.getTaxPayerNumber());
        ret.setAccountSetName(
                String.join(",", (accountSetList == null || accountSetList.isEmpty()) ? null : accountSetList));
        ret.setServiceName(String.join(",", (serviceList == null || serviceList.isEmpty()) ? null : serviceList));
        ret.setBusinessUnitName(row.getBusinessUnitName() == null ? businessUnitName : row.getBusinessUnitName());
        ret.setIndustryName(row.getIndustryName());
        ret.setAreaName(row.getAreaName() == null ? areaName : row.getAreaName());
        ret.setUserList(new ArrayList<>());
        return ret;
    }

3115
    private String getBusinessUnitNameById(String businessUnitId) {
eddie.woo's avatar
eddie.woo committed
3116

3117
        BusinessUnit businessUnit = businessUnitMapper.selectByPrimaryKey(businessUnitId);
eddie.woo's avatar
eddie.woo committed
3118 3119 3120
        return businessUnit != null ? businessUnit.getName() : null;
    }

3121 3122
    private String getAreaNameById(String areaId) {
        Area area = areaMapper.selectByPrimaryKey(areaId);
eddie.woo's avatar
eddie.woo committed
3123 3124 3125
        return area != null ? area.getName() : null;
    }

gary's avatar
gary committed
3126
    public int getDownloadFilePath(JsonExportDto exportData, OutputStream os) {
gary's avatar
gary committed
3127
        List<OrgInfoDto> orgInfoDtos = JSON.parseArray(exportData.getJsonData(), OrgInfoDto.class);
gary's avatar
gary committed
3128
        try{
gary's avatar
gary committed
3129
            if (orgInfoDtos.size() == 0) {
gary's avatar
gary committed
3130 3131
                return 0;
            }
gary's avatar
gary committed
3132 3133 3134 3135 3136
            Map<String, String> header = generalHeader();
            List<pwc.taxtech.atms.dto.organization.OrgInfoDto> cellList = new ArrayList<>();
            orgInfoDtos.stream().forEach(x -> {
                pwc.taxtech.atms.dto.organization.OrgInfoDto d =
                        new pwc.taxtech.atms.dto.organization.OrgInfoDto();
gary's avatar
gary committed
3137 3138 3139 3140 3141 3142 3143
                d = beanUtil.copyProperties(x,d);
                cellList.add(d);
            });
            ExcelUtil.exportExcel(header, cellList, os);
        }catch (Exception e){
            logger.error("机构列表导出转换Excel异常: %s",e.getMessage());
        }
gary's avatar
gary committed
3144 3145
        return orgInfoDtos.size();
    }
gary's avatar
gary committed
3146

gary's avatar
gary committed
3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157
    private Map<String, String> generalHeader() {
        Map<String, String> header = new LinkedHashMap<>();
        header.put("Name","机构名称");
        header.put("Code","机构代码");
        header.put("TaxPayerNumber","纳税人识别号");
        header.put("StructureName","机构层级");
        header.put("RegionName","地区");
        header.put("BusinessUnitName","事业部");
        header.put("AreaName","区域");
        header.put("IndustryName","行业");
        header.put("IsActive","启用状态");
gary's avatar
gary committed
3158 3159 3160 3161 3162 3163 3164
        header.put("EnglishName","机构名称(英文)");

        header.put("Abbreviation","机构缩写");
        header.put("FoundationDate","成立日期");
        header.put("RegistrationLocation","注册地");
        header.put("RegistrationLocationEn","注册地(英文)");
        header.put("LegalPersonName","法人名称");
gary's avatar
gary committed
3165
        header.put("BusinessScope","经营范围");
gary's avatar
gary committed
3166
        header.put("RegStatus","工商登记状态");
gary's avatar
gary committed
3167
        header.put("ArchitectureType","架构类型");
gary's avatar
gary committed
3168 3169 3170 3171
        header.put("NationalEconomicIndustry","所属国民经济行业");
        header.put("EngageNationalProhibitIndustry","从事国家限制或禁止行业");

        header.put("RegistrationCapital","注册资本(万元)");
gary's avatar
gary committed
3172
        header.put("PaidInCapital","实缴资本(万元)");
gary's avatar
gary committed
3173
        header.put("NumOfBranches","分公司数量");
gary's avatar
gary committed
3174 3175
        header.put("UnifiedSocialCreditCode","统一社会信用代码");
        header.put("RegFinancialAccountingType","注册登记财务核算方式");
gary's avatar
gary committed
3176 3177 3178
        header.put("TaxRegStatus","财务核算方法");
        header.put("TaxCreditRating","纳税信用评级");
        header.put("ApplicableAccountingRule","适用会计制度");
gary's avatar
gary committed
3179
        header.put("LowValueConsumablesAmortizationMethod","低值易耗品摊销方法");
gary's avatar
gary committed
3180 3181
        header.put("DepreciationMethod","折旧方式");

gary's avatar
gary committed
3182
        header.put("AccountingSoftware","会计核算软件");
gary's avatar
gary committed
3183
        header.put("CompleteRecordTotalInstitutions","是否完成总分机构备案");
gary's avatar
gary committed
3184 3185
        header.put("TaxClientPersonName","办税人姓名");
        header.put("TaxClientPersonPhone","办税人电话");
gary's avatar
gary committed
3186
        header.put("TaxClientPersonIdNum","办税人身份证号");
gary's avatar
gary committed
3187 3188
        header.put("TicketHolderName","购票人姓名");
        header.put("TicketHolderPhoneNum","购票人电话");
gary's avatar
gary committed
3189 3190 3191 3192 3193 3194 3195 3196 3197
        header.put("NationalTaxHallAddress","主管国税大厅地址");
        header.put("NationalTaxAdministratorName","主管国税税局名称");
        header.put("NationalTaxAdministratorPhoneNum","主管国税税局电话");

        header.put("LocalTaxHallAddress","主管地税大厅地址");
        header.put("LocalTaxAdministratorName","主管地税税局名称");
        header.put("LocalTaxAdministratorPhoneNum","主管地税税局电话");
        header.put("EtaWebsite","电子税务网站");
        header.put("SignTripartiteAgreement","三方协议是否签订");
gary's avatar
gary committed
3198 3199 3200 3201 3202
        header.put("ReportingCurrency","记账本位币");
        header.put("ConsolidationTime","并表期间");
        header.put("TaxAgent","税务代理");
        header.put("TaxAgentContact","税务代理联系方式");
        header.put("TaxReturnBusinessType","纳税申报企业类型");
gary's avatar
gary committed
3203 3204 3205

        header.put("SmallMeagerProfit","小型微利企业");
        header.put("ListedCompany","上市公司");
gary's avatar
gary committed
3206
        header.put("ApplicableAccountingStandardsOrAccountingSystems","适用会计准则或会计制度");
gary's avatar
gary committed
3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227
        header.put("TaxPayerNumberVat","增值税纳税人识别号");
        header.put("TaxPayerNumberCit","企业所得税纳税人识别号");
        header.put("TaxClientPersonEmailAddress","办税人邮箱地址");
        header.put("BankAccountName","三方协议开户银行名称");
        header.put("BankAccountNumber","三方协议开户银行账户");
        header.put("LegalPersonPhoneNumber","法定代表人/负责人手机");
        header.put("LegalPersonLandlineNum","法定代表人/负责人座机");

        header.put("LegalPersonEmailAddress","法定代表人/负责人邮箱");
        header.put("RegFinancialOfficerName","注册登记财务负责人姓名");
        header.put("RegFinancialOfficerPhoneNum","注册登记财务负责人电话");
        header.put("RegFinancialOfficerLandlineNum","注册登记财务负责人座机");
        header.put("RegFinancialOfficerEmailAddress","注册登记财务负责人邮箱");
        header.put("ActualBusinessAddress","实际经营地址");
        header.put("SecondaryApprovalAmount","二级审批金额");
        header.put("FiscalYearDeadline","财年截止日");
        header.put("BusinessRegistrationNumber","Business registration number");
        header.put("ParValue","Par Value");
        header.put("IssuedShares","Issued shares");
        header.put("Directors","Directors");
        header.put("OtherFacts","其他情况说明");
3228
        header.put("LogoutTime","注销时间");
gary's avatar
gary committed
3229
        header.put("TaxRuleIntroduction","税制简介");
gary's avatar
gary committed
3230
        header.put("Country","国家");
gary's avatar
gary committed
3231
        return header;
gary's avatar
gary committed
3232
    }
eddie.woo's avatar
eddie.woo committed
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247

    /**
     * 获取当前用户可查看机构信息
     *
     * @return List<OrgSelectDto>
     */
    public List<OrgSelectDto> getMyOrgList() {
        String uid = authUserHelper.getCurrentUserId();
        User user = userMapper.selectByPrimaryKey(uid);
        if (user.getIsSuperAdmin()) {
            return organizationMapper.getAllOrgSelectList();
        } else {
            return organizationMapper.getMyOrgSelectList(uid);
        }
    }
chase's avatar
chase committed
3248

eddie.woo's avatar
eddie.woo committed
3249 3250 3251 3252 3253 3254 3255 3256 3257
    public List<OrgCodeIdDto> getMyOrgCodeList() {
        String uid = authUserHelper.getCurrentUserId();
        User user = userMapper.selectByPrimaryKey(uid);
        if (user.getIsSuperAdmin()) {
            return organizationMapper.getAllOrgCodeList();
        } else {
            return organizationMapper.getMyOrgCodeList(uid);
        }
    }
3258

chase's avatar
chase committed
3259 3260 3261
    public String queryBusinessByCompanyId(String companyId) {
        return organizationMapper.queryBusinessByCompanyId(companyId);
    }
eddie.woo's avatar
eddie.woo committed
3262
}