package com.my.task;

import cn.gov.customs.casp.sdk.h4a.OguBeanReaderHelper;
import cn.gov.customs.casp.sdk.h4a.entity.OrganizationChildren;
import cn.gov.customs.casp.sdk.h4a.entity.RootDepartment;
import cn.gov.customs.casp.sdk.h4a.enumdefines.ListObjectCategories;
import cn.gov.customs.casp.sdk.h4a.enumdefines.ObjectStatusCategories;
import cn.gov.customs.casp.sdk.h4a.enumdefines.ViewCategory;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.IOguReaderGetOrganizationChildrenCupaaFaultArgsFaultFaultMessage;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.IOguReaderGetRootDepartmentCupaaFaultArgsFaultFaultMessage;
import cn.gov.customs.casp.sdk.h4a.ogu.ws.OrganizationCategory;
import com.my.bus.cache.BusCache;
import com.my.common.core.domain.entity.SysDept;
import com.my.common.utils.DateUtils;
import com.my.common.utils.spring.SpringUtils;
import com.my.constant.H4ABasicProperty;
import com.my.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门信息同步
 */
@Slf4j
@Component("syncH4ADeptTask")
public class SyncH4ADeptTask {
    @Autowired
    private  BusCache busCache;
    /**
     *      * 用户同步和机构同步时间需错开，机构同步完成后再同步用户，因为需要处理用户所属部门deptId
     */
    public void syncH4ADeptTask(){
        log.info("-----------------开始同步H4A机构信息-------------------");

        long start = System.currentTimeMillis();
        try {
            String rootOrg = "";
            OguBeanReaderHelper helper = new OguBeanReaderHelper();
            RootDepartment[] rts;
            rts = helper.getBeanRootDepartment(
                    H4ABasicProperty.VIEW_GUID,
                    ViewCategory.ViewCode,
                    "OBJECTCLASS,VIEW_GUID,ORG_GUID,ORIGINAL_SORT,DISPLAY_NAME,CUSTOMS_CODE,ORG_TYPE,"
                            + "INNER_SORT,OBJ_NAME,RANK_CODE,ORG_CLASS,SYSDISTINCT2,SYSDISTINCT1,SYSCONTENT1,"
                            + "CREATE_TIME,MODIFY_TIME,SYSCONTENT2,SYSCONTENT3");
            if (rts.length > 0) {
                for (RootDepartment r : rts) {
                    rootOrg = r.getAll_path_name();
                    log.info("根机构：" + r.getDisplay_name() + ":"
                            + r.getAll_path_name() + ":" + r.getGlobal_sort()
                            + ":" + r.getOriginal_sort());
                }
            }
            rootOrg += "\\"+H4ABasicProperty.ROOT_CUSTOMS;
            OrganizationChildren[] oc = helper.getBeanOrganizationChildren(
                    H4ABasicProperty.VIEW_GUID,
                    ViewCategory.ViewCode, rootOrg,
                    OrganizationCategory.ORG_ALL_PATH_NAME,
                    ListObjectCategories.Organizations,
                    ObjectStatusCategories.Common, 0, "", "", "", 0,
                    "ORG_GUID,PARENT_GUID,ALL_PATH_NAME,ORIGINAL_SORT,"
                            + "CUSTOMS_CODE,DISPLAY_NAME,OBJ_NAME,STATUS,GLOBAL_SORT,NOTE,RANK_CODE,RANK_NAME,"
                            + "INNER_SORT,ORG_CLASS,ORG_TYPE,CREATE_TIME,MODIFY_TIME");

            ISysDeptService service = SpringUtils.getBean(ISysDeptService.class);
            Date nowDate = DateUtils.getNowDate();
            if(oc != null && oc.length > 0){
                log.info("海关机构总数："+oc.length);
                // 同步前，把所有用户的删除状态设置为删除
                service.updateDelFlag();

                List<SysDept> sysDepts = service.selectAllDept();
                Map<String, SysDept> deptMap = sysDepts.stream().collect(Collectors.toMap(SysDept::getOrgGuid, dept -> dept));
                boolean isNew;
                for(OrganizationChildren o : oc){
                    String orgGuid = o.getOrg_guid();
                    String parentGuid = o.getParent_guid();
                    String allPathName = o.getAll_path_name();
                    String originalSort = o.getOriginal_sort();
                    String customsCode = o.getCustoms_code();
                    String status = o.getStatus();
                    String innerSort = o.getInner_sort();
                    String objName = o.getObj_name();
                    String rankCode = o.getRank_code();
                    String rankName = o.getRank_name();
                    String orgClass = o.getOrg_class();
                    String globalSort = o.getGlobal_sort();
                    String note = o.getNote();
                    String createTime = o.getCreate_time();
                    String modifyTime = o.getModify_time();
                    String org_type = o.getOrg_type();

                    SysDept org = deptMap.get(orgGuid);
                    if(org == null){
                        org = new SysDept();
                        isNew = true;
                    } else{
                        isNew = false;
                    }
                    org.setOrgGuid(orgGuid);
                    org.setParentGuid(parentGuid);
                    org.setAllPathName(allPathName);
                    org.setOriginalSort(originalSort);
                    org.setCustomsCode(customsCode);
                    org.setInnerSort(innerSort);
                    org.setDeptName(objName);
                    org.setRankCode(rankCode);
                    org.setRankName(rankName);
                    org.setOrgClass(orgClass);
                    org.setGlobalSort(globalSort);
                    org.setRemark(note);
                    org.setOrgType(org_type);
                    if("1".equals(status)){
                        // H4A中1正常使用，其他时删除，本系统中 0 正常，1-停用，
                        org.setStatus("0");
                        org.setDelFlag("0");
                    } else {
                        org.setStatus(status);
                        org.setDelFlag("2");
                    }
                    org.setH4aCreateTime(createTime);
                    org.setCreateTime(nowDate);
                    org.setModifyTime(modifyTime);

                    if(isNew){
                        // 部分隶属海关名称后会有（筹）
                        String substring = objName.substring(0, objName.indexOf("（"));
                        //  后勤管理中心为银川下属部门，不算做事业单位
                        String[] institutions  = new String[]{"保健中心","技术中心","机关服务中心"};
                        if("银川海关".equals(objName)){
                            org.setOrgCategory("1");
                        } else if(substring.endsWith("海关")){
                            org.setOrgCategory("2"); // 隶属海关
                        } else if("06".equals(rankCode) && "2".equals(orgClass)){
                            org.setOrgCategory("4"); // 缉私局
                        }  else if(Arrays.asList(institutions).contains(substring)){
                            org.setOrgCategory("3"); // 事业单位
                        }else {
                            org.setOrgCategory("9");
                        }
                        service.insertH4aDept(org);
                    } else {
                        service.updateH4aDept(org);
                    }
                }
                //  ,更新父机构id
                service.updateAllDeptId();

                //  更新祖级列表 根据 ORIGINAL_SORT 字段长度一级一级往下添加
                int sortLent = 12;
                int rows = 0;
                do {
                    rows = service.updateAllAncestors(sortLent);
                    sortLent = sortLent+6;
                }while(rows > 0);
            }
            //由于H4A数据重新同步，清除机构和用户缓存
            busCache.clearDeptUser();
        } catch (IOguReaderGetRootDepartmentCupaaFaultArgsFaultFaultMessage e) {
            e.printStackTrace();
        } catch (IOguReaderGetOrganizationChildrenCupaaFaultArgsFaultFaultMessage e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        log.info("-----------------结束同步H4A机构信息同步完成，共耗时："+(end-start)/1000+"秒------------------");
    }
}
