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.SysUser;
import com.my.common.utils.DateUtils;
import com.my.common.utils.spring.SpringUtils;
import com.my.constant.H4ABasicProperty;
import com.my.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户信息同步
 */
@Slf4j
@Component("syncH4AUserTask")
public class SyncH4AUserTask {

    @Autowired
    private BusCache busCache;
    /**
     * 用户同步和机构同步时间需错开，机构同步完成后再同步用户，因为需要处理用户所属部门deptId
     */
    public void syncUser(){

        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[] uc =  helper.getBeanOrganizationChildren(
                    H4ABasicProperty.VIEW_GUID,
                    ViewCategory.ViewCode, rootOrg,
                    OrganizationCategory.ORG_ALL_PATH_NAME,
                    ListObjectCategories.Users,
                    ObjectStatusCategories.Common, 0, "", "", "", 0,
                    "USER_GUID,PARENT_GUID,ALL_PATH_NAME,"
                            + "OBJ_NAME,STATUS,GLOBLA_SORT,RANK_NAME,NOTE,RANK_CODE,RANK_NAME,"
                            + "INNER_SORT,ORG_CLASS,CREATE_TIME,MODIFY_TIME,PERSON_ID,E_MAIL,SIDELINE,SYSCONTENT1");
            if(uc != null && uc.length > 0){
                log.info("人员总数："+uc.length);
                ISysUserService userService = SpringUtils.getBean(ISysUserService.class);
                // 同步前，把所有用户的删除状态设置为删除
                userService.updateDelFlag();
                List<SysUser> list = userService.selectAllUser();
                Map<String, SysUser> userMap = new HashMap<>();
                list.forEach(u -> {
                    userMap.put(u.getUserGuid() + "_" + u.getParentGuid(), u);
                });

                boolean isNew;
                for(OrganizationChildren o : uc){
                    String userGuid = o.getUser_guid();
                    String parentGuid = o.getParent_guid();
                    SysUser u = userMap.get(userGuid + "_" + parentGuid);
                    if(u == null){
                        u = new SysUser();
                        u.setUserCode("$2a$10$h7isN1Li3aoJB9mKGzkF9ONFMFQob9iR538icjQtCgwutrFS5yNbu");
                        isNew = true;
                        u.setUserType("0");
                        u.setLoginFlag("0");
                    } else {
                        isNew = false;
                    }
                    u.setUserGuid(userGuid);
                    buildUser(o, u);
                    if(isNew){
                        userService.insterH4aUser(u);
                    } else {
                        userService.updateH4aUser(u);
                    }
                }
                // 处理用户所属部门 deptId
                userService.updateUserDeptId();
            }

//            //人员兼职对象
            OrganizationChildren[] sild =  helper.getBeanOrganizationChildren(
                    H4ABasicProperty.VIEW_GUID,
                    ViewCategory.ViewCode, rootOrg,
                    OrganizationCategory.ORG_ALL_PATH_NAME,
                    ListObjectCategories.Sideline,
                    ObjectStatusCategories.Common, 0, "", "", "", 0,
                    "USER_GUID,PARENT_GUID,ALL_PATH_NAME,"
                            + "OBJ_NAME,STATUS,GLOBLA_SORT,RANK_NAME,NOTE,RANK_CODE,RANK_NAME,"
                            + "INNER_SORT,ORG_CLASS,CREATE_TIME,MODIFY_TIME,PERSON_ID,E_MAIL,SIDELINE,SYSCONTENT1");
            if(sild != null && sild.length > 0){
                log.info("兼职人员总数："+sild.length);
                ISysUserService userService = SpringUtils.getBean(ISysUserService.class);
                List<SysUser> list = userService.selectAllUser();
                Map<String, SysUser> userMap = new HashMap<>();
                list.forEach(u -> {
                    userMap.put(u.getUserGuid() + "_" + u.getParentGuid(), u);
                });
                for(OrganizationChildren o : sild){
                    String userGuid = o.getUser_guid();
                    String parentGuid = o.getParent_guid();
                    //以主职为主,一个人多个部门
                    SysUser user = userMap.get(userGuid + "_" + parentGuid);
                    if(user == null || !user.getParentGuid().equals(parentGuid)){
                        user = new SysUser();
                        user.setUserGuid(userGuid);
                        user.setUserCode("$2a$10$h7isN1Li3aoJB9mKGzkF9ONFMFQob9iR538icjQtCgwutrFS5yNbu");
                        buildUser(o, user);
                        user.setUserType("0");
                        user.setLoginFlag("0");
                        userService.insterH4aUser(user);
                    } else {
                        buildUser(o, user);
                        userService.updateH4aUser(user);
                    }
                }
                // 处理用户所属部门 deptId
                userService.updateUserDeptId();
            }

            //由于H4A数据重新同步，清除机构和用户缓存
            busCache.clearDeptUser();
        }  catch (IOguReaderGetRootDepartmentCupaaFaultArgsFaultFaultMessage e) {
            e.printStackTrace();
        } catch (IOguReaderGetOrganizationChildrenCupaaFaultArgsFaultFaultMessage e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        log.info("-----------------结束同步H4A机构信息同步完成，共耗时："+(end-start)/1000+"秒------------------");
    }

    private void buildUser(OrganizationChildren o, SysUser u ){
        String parentGuid = o.getParent_guid();
        String allPathName = o.getAll_path_name();
        String status = o.getStatus();
        String objName = o.getObj_name();
        String rankCode = o.getRank_code();
        String rankName = o.getRank_name();
        String note = o.getNote();
        String createTime = o.getCreate_time();
        String modifyTime = o.getModify_time();
        String attributes = o.getAttributes();
        String sideline = o.getSideline();
        String eMail = o.getE_mail();
        String personId = o.getPerson_id();
        String phoneNum = o.getSyscontent1();

        u.setParentGuid(parentGuid);
        u.setAllPathName(allPathName);
//        1、正常使用，3、逻辑删除、5、机构逻辑删除，7、人员逻辑删除
//        if("1".equals(status)){
//            // H4A中1正常使用，其他时删除，本系统中 0 正常，1-停用，
//            u.setStatus("0");
//            u.setDelFlag("0");
//        } else {
//            u.setStatus(status);
//            u.setDelFlag("2");
//        }
        u.setStatus("0");
        u.setDelFlag("0");

        u.setUserName(objName);
        u.setRankCode(rankCode);
        u.setRankName(rankName);
        u.setRemark(note);
        u.setCreateTime(DateUtils.getNowDate());
        u.setModifyTime(modifyTime);
        u.setH4aCreateTime(createTime);

        u.setAttributes(attributes);
        u.setPersonId(personId);
        u.setSideline(sideline);
        u.setEmail(eMail);
        u.setPhonenumber(phoneNum);
    }
}
