
package com.ningdatech.pmapi.ding.task;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.ningdatech.basic.model.GenericResult;
import com.ningdatech.pmapi.ding.model.DingOrgInfoTreeDTO;
import com.ningdatech.pmapi.organization.model.entity.DingOrganization;
import com.ningdatech.pmapi.organization.service.IDingOrganizationService;
import com.ningdatech.zwdd.client.ZwddClient;
import com.ningdatech.zwdd.model.dto.DingOrgInfoDTO;
import com.ningdatech.zwdd.model.dto.DingScopesV2DTO;
import com.ningdatech.zwdd.model.dto.PageSubOrganizationCodeDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author liuxinxin
 * @date 2023/2/7 上午10:15
 */

@Slf4j
@Component
public class OrganizationBatchGetTask {

    @Autowired
    private ZwddClient zwddClient;

    private static final Integer GROUP_SIZE = 100;

    @Autowired
    private IDingOrganizationService iDingOrganizationService;

    /**
     * 获取浙政钉组织架构
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchGetOrganizationTask() {
//        List<DingOrganization> allList = iDingOrganizationService.list();
//        List<String> currentAllOrganizationCodeList = allList.stream().map(DingOrganization::getOrganizationCode).collect(Collectors.toList());
        // 全量删除
        // iDingOrganizationService.remove(Wrappers.lambdaQuery(DingOrganization.class).isNotNull(DingOrganization::getId));
        // 获取顶级组织code
        GenericResult<DingScopesV2DTO> scopesV2Result = zwddClient.getScopesV2();
        DingScopesV2DTO scopesV2 = scopesV2Result.getData();

        if (Objects.nonNull(scopesV2)) {
            // 顶级组织code
            List<String> deptVisibleScopes = scopesV2.getDeptVisibleScopes();
            log.info("顶级组织code: size = " + deptVisibleScopes.size() + "列表：" + JSONObject.toJSONString(deptVisibleScopes));
            // 获取顶级节点信息
            GenericResult<List<DingOrgInfoDTO>> listGenericResult = zwddClient.listOrganizationsByCodes(deptVisibleScopes);
            List<DingOrgInfoDTO> dingOrgInfoDtos = listGenericResult.getData();
            for (String orgCode : deptVisibleScopes) {
//                if (currentAllOrganizationCodeList.contains(orgCode)) {
//                    log.info("已存在组织架构---{}", orgCode);
//                    continue;
//                }
                List<DingOrgInfoTreeDTO> treeDTOList = new ArrayList<>();

                DingOrgInfoTreeDTO childDingOrgInfoTreeDTO = new DingOrgInfoTreeDTO();
                //设置节点详情
                if (dingOrgInfoDtos != null && !dingOrgInfoDtos.isEmpty()) {
                    for (DingOrgInfoDTO orgInfo : dingOrgInfoDtos) {
                        if (orgInfo.getOrganizationCode().equals(orgCode)) {
                            childDingOrgInfoTreeDTO.setDingOrgInfoDTO(orgInfo);
                        }
                    }
                }
                childDingOrgInfoTreeDTO.setCode(orgCode);
                childDingOrgInfoTreeDTO.setChildCodes(new ArrayList<>());
                getDingOrgChild(childDingOrgInfoTreeDTO);
                treeDTOList.add(childDingOrgInfoTreeDTO);
                if (CollectionUtils.isNotEmpty(treeDTOList)) {
                    List<DingOrganization> saveRecordList = new ArrayList<>();
                    buildSaveRecordList(treeDTOList, saveRecordList);
                    // 批量保存
                    if (saveRecordList.size() <= GROUP_SIZE) {
                        iDingOrganizationService.saveBatch(saveRecordList);
                    } else {
                        List<List<DingOrganization>> split = Lists.partition(saveRecordList, GROUP_SIZE);
                        for (List<DingOrganization> segment : split) {
                            iDingOrganizationService.saveBatch(segment);
                        }
                    }
                }
                log.info("----拉取浙政钉组织结构结束---,顶级code：" + orgCode);
            }
        }
    }

    private void buildSaveRecordList(List<DingOrgInfoTreeDTO> treeDTOList, List<DingOrganization> saveRecordList) {
        if (CollectionUtils.isEmpty(treeDTOList)) {
            return;
        }
        for (DingOrgInfoTreeDTO dingOrgInfoTreeDTO : treeDTOList) {
            DingOrganization saveRecord = new DingOrganization();
            DingOrgInfoDTO dingOrgInfoDTO = dingOrgInfoTreeDTO.getDingOrgInfoDTO();
            List<DingOrgInfoTreeDTO> childCodes = dingOrgInfoTreeDTO.getChildCodes();
            saveRecord.setDisplayOrder(dingOrgInfoDTO.getDisplayOrder());
//            saveRecord.setEnabled("1");
            saveRecord.setParentCode(dingOrgInfoDTO.getParentCode());
            saveRecord.setOrganizationCode(dingOrgInfoDTO.getOrganizationCode());
//            saveRecord.setSubCount((long) dingOrgInfoTreeDTO.getChildCodes().size());
            saveRecord.setOrganizationName(dingOrgInfoDTO.getOrganizationName());
            saveRecordList.add(saveRecord);
            if (CollectionUtils.isNotEmpty(childCodes)) {
                buildSaveRecordList(childCodes, saveRecordList);
            }
        }
    }

    private void getDingOrgChild(DingOrgInfoTreeDTO parentDingOrgInfoTreeDTO) {
        String parentOrgCode = parentDingOrgInfoTreeDTO.getCode();
        DingOrgInfoDTO orgInfoDTO = parentDingOrgInfoTreeDTO.getDingOrgInfoDTO();
        boolean leaf = orgInfoDTO.getLeaf();
        if (!leaf) {
            int currentPage = 1;
            int pageSize = 100;
            GenericResult<PageSubOrganizationCodeDTO> pageSubOrganizationCodeDTOGenericResult = zwddClient.pageSubOrganizationCodes(currentPage++, pageSize, parentOrgCode);
            PageSubOrganizationCodeDTO pageSubOrganizationCodeDTO = pageSubOrganizationCodeDTOGenericResult.getData();

            if (CollUtil.isNotEmpty(pageSubOrganizationCodeDTO.getSubOrganizationCodeList())) {
                List<String> subOrganizationCodeList = new ArrayList<>(pageSubOrganizationCodeDTO.getSubOrganizationCodeList());
                Long totalSize = pageSubOrganizationCodeDTO.getTotalSize();

                while (totalSize > (long) currentPage * pageSize) {
                    GenericResult<PageSubOrganizationCodeDTO> subPageSubOrganizationCodeDTOGenericResult = zwddClient
                            .pageSubOrganizationCodes(currentPage++, pageSize, parentOrgCode);
                    PageSubOrganizationCodeDTO subOrganizationCodeDTO = subPageSubOrganizationCodeDTOGenericResult.getData();
                    if (CollectionUtils.isNotEmpty(subOrganizationCodeDTO.getSubOrganizationCodeList())) {
                        subOrganizationCodeList.addAll(subOrganizationCodeDTO.getSubOrganizationCodeList());
                    }
                }

                if (CollectionUtils.isNotEmpty(subOrganizationCodeList)) {
                    GenericResult<List<DingOrgInfoDTO>> listGenericResult = zwddClient
                            .listOrganizationsByCodes(subOrganizationCodeList);
                    List<DingOrgInfoDTO> dingOrgInfoDtos = listGenericResult.getData();
                    List<DingOrgInfoTreeDTO> dingOrgInfoTreeDTOList = dingOrgInfoDtos.stream().map(r -> {
                        DingOrgInfoTreeDTO dingOrgInfoTreeDTO = new DingOrgInfoTreeDTO();
                        dingOrgInfoTreeDTO.setCode(r.getOrganizationCode());
                        dingOrgInfoTreeDTO.setDingOrgInfoDTO(r);
                        dingOrgInfoTreeDTO.setChildCodes(new ArrayList<>());
                        getDingOrgChild(dingOrgInfoTreeDTO);
                        return dingOrgInfoTreeDTO;
                    }).collect(Collectors.toList());
                    parentDingOrgInfoTreeDTO.setChildCodes(dingOrgInfoTreeDTOList);
                }
            }
        }
    }

}


