package com.infoepoch.pms.dispatchassistant.domain.oa.organization;

import com.infoepoch.pms.dispatchassistant.common.component.SnowFlake;
import com.infoepoch.pms.dispatchassistant.common.utils.IntegerTool;
import com.infoepoch.pms.dispatchassistant.common.utils.LambdaTool;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.IOrganizationRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.Organization;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.OrganizationCriteria;
import com.infoepoch.pms.dispatchassistant.domain.basic.organization.OrganizationService;
import com.infoepoch.pms.dispatchassistant.domain.oa.organization.sync.SBMDMMDMPageInquiryOAStandardOrgInfoSrvOutputItem;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrganizationSyncService {

    private final static Logger logger = LoggerFactory.getLogger(OrganizationSyncService.class);

    @Autowired
    private IOrganizationRepository organizationRepository;
    @Autowired
    private OrganizationService organizationService;

    /**
     * 顶级组织编码
     */
    private final static String TOP_ORG_CODE = "00230000000000000000";

    /**
     * 省本部组织编码（OA中不存在）
     */
    private final static String PROVINCE_COMPANY_ORG_CODE = "00230010000000000000";


    /**
     * 从OA同步组织信息
     *
     * @param itemList
     */
    public void syncFromOa(List<SBMDMMDMPageInquiryOAStandardOrgInfoSrvOutputItem> itemList) {
        if (CollectionUtils.isEmpty(itemList)) {
            logger.info("OA同步组织信息为空");
            return;
        }
        List<Organization> organizationList = new ArrayList<>();
        for (SBMDMMDMPageInquiryOAStandardOrgInfoSrvOutputItem item : itemList) {
            Organization organization = new Organization(
                    SnowFlake.instant().nextId().toString(),
                    item.getORGNAME(),
                    getShortName(item.getORGNAME()),
                    judgeStatusDisabled(item.getSTATUS()),
                    null,
                    item.getORGCODE(),
                    null,
                    null,
                    item.getDISPLAYORDER(),
                    item.getPARENTORGID(),
                    IntegerTool.getInteger(item.getORGLEVEL())
            );
            organizationList.add(organization);
        }
        // 将组织列表根据oaOrgCode字段和parentCode字段转换为树形结构，并给pid字段赋值
        fillData(organizationList);
        // 根据组织编码查询已存在的组织记录，用于更新
        List<String> orgCodeList = organizationList.stream().map(Organization::getOaOrgCode).collect(Collectors.toList());
        OrganizationCriteria criteria = new OrganizationCriteria();
        criteria.setOaOrgCodeList(orgCodeList);
        List<Organization> oldList = organizationRepository.selectByCriteria(criteria);
        Map<String, Organization> oldMap = LambdaTool.changeCollectionToHashMap(oldList, Organization::getOaOrgCode);
        List<Organization> addList = new ArrayList<>();
        List<Organization> updateList = new ArrayList<>();
        for (Organization organization : organizationList) {
            Organization old = oldMap.get(organization.getOaOrgCode());
            if (old == null) {
                Organization pOrg = organizationRepository.selectByOaOrgCode(organization.getParentOrgCode());
                if (pOrg != null) {
                    organization.setPId(pOrg.getId());
                }
                addList.add(organization);
            } else {
                old.modify(
                        organization.getName(),
                        organization.getShortName(),
                        organization.getOaOrgCode(),
                        organization.getHrOrgCode(),
                        organization.getDisplayOrder(),
                        organization.isDisabled()
                );
                if (!organization.getParentOrgCode().equals(old.getParentOrgCode())) {
                    Organization pOrg = organizationRepository.selectByOaOrgCode(organization.getParentOrgCode());
                    if (pOrg == null) {
                        old.setPId(organization.getpId());
                    } else {
                        old.setPId(pOrg.getId());
                    }
                    old.setParentOrgCode(organization.getParentOrgCode());
                }
                updateList.add(old);
            }
        }
        if (CollectionUtils.isNotEmpty(addList)) {
            organizationRepository.batchInsert(addList);
        }
        if (CollectionUtils.isNotEmpty(updateList)) {
            organizationRepository.batchUpdate(updateList);
        }
        // 更新省本部下的组织名称
        organizationService.updateProvinceOrganizationName();
        // 刷新redis缓存
        organizationService.freshOrganization();
    }

    /**
     * 获取组织简称
     *
     * @param orgName
     * @return
     */
    private String getShortName(String orgName) {
        if (orgName == null)
            return null;
        if (orgName.lastIndexOf("\\") < 0)
            return orgName;
        else
            return orgName.substring(orgName.lastIndexOf("\\") + 1);
    }


    /**
     * @param organizationList
     */
    public void fillData(List<Organization> organizationList) {
        if (CollectionUtils.isEmpty(organizationList))
            return;
        Map<String, Organization> organizationMap = LambdaTool.changeCollectionToHashMap(organizationList, Organization::getOaOrgCode);
        Organization provinceCompany = organizationRepository.selectByOaOrgCode(PROVINCE_COMPANY_ORG_CODE);
        provinceCompany.setParentOrgCode(TOP_ORG_CODE);
        for (Organization organization : organizationList) {
            if (organization.getParentOrgCode().equals(TOP_ORG_CODE) && !organization.getShortName().contains("分公司")) {
                organization.setParentOrgCode(provinceCompany.getOaOrgCode());
                organization.setPId(provinceCompany.getId());
                organization.setName(replaceProvinceChildName(organization.getName()));
            }
        }
        for(Organization organization : organizationList) {
            if (!organization.getParentOrgCode().equals(TOP_ORG_CODE)) {
                Organization parentOrg = organizationMap.get(organization.getParentOrgCode());
                if (parentOrg == null) {
                    parentOrg = organizationRepository.selectByOaOrgCode(organization.getParentOrgCode());
                }
                if (parentOrg != null) {
                    organization.setName(parentOrg.getName() + "\\" + organization.getShortName());
                    organization.setPId(parentOrg.getId());
                    organization.setLevel(parentOrg.getLevel() + 1);
                }
            }
        }
        organizationList.add(provinceCompany);
    }

    /**
     * 替换省本部下的组织名称
     *
     * @param orgName
     * @return
     */
    private String replaceProvinceChildName(String orgName) {
        if (orgName == null)
            return null;
        if (orgName.startsWith("江苏\\省本部")) {
            return orgName;
        }
        return orgName.replace("江苏", "江苏\\省本部");
    }

    /**
     * 判断组织状态是否禁用
     *
     * @param status
     * @return
     */
    private boolean judgeStatusDisabled(String status) {
        if (status == null)
            return false;
        return status.equals("1");
    }

}
