package com.foreverwin.mesnac.listener.listener;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.foreverwin.mesnac.listener.model.SysUser;
import com.foreverwin.mesnac.listener.service.SysUserService;
import com.foreverwin.mesnac.listener.util.ConstantsUtil;
import com.sap.security.api.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.UUID;

@Component
public class StartListener implements ApplicationListener<ApplicationReadyEvent> {

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

    @Autowired
    SysUserService sysUserService;
    @Autowired
    NwaUserListener nwaUserListener;
    @Autowired
    NwaPrincipalListener nwaPrincipalListener;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        try {
            IUserFactory userFactory = UMFactory.getUserFactory();
            IPrincipalFactory principalFactory = UMFactory.getPrincipalFactory();
            //---------------------------------------------------------------------------------------------------------------------------
            userFactory.registerListener(nwaUserListener, UserListener.INFORM_ON_USER_ADDED);// 注册新增用户监听
            userFactory.registerListener(nwaUserListener, UserListener.INFORM_ON_USER_REMOVED);// 注册删除用户监听
            //---------------------------------------------------------------------------------------------------------------------------
            principalFactory.registerListener(nwaPrincipalListener, NwaPrincipalListener.INFORM_ON_OBJECT_ADDED);
            principalFactory.registerListener(nwaPrincipalListener, NwaPrincipalListener.INFORM_ON_OBJECT_ASSIGNED);
            principalFactory.registerListener(nwaPrincipalListener, NwaPrincipalListener.INFORM_ON_OBJECT_EDITED);
            principalFactory.registerListener(nwaPrincipalListener, NwaPrincipalListener.INFORM_ON_OBJECT_REMOVED);
            principalFactory.registerListener(nwaPrincipalListener, NwaPrincipalListener.INFORM_ON_OBJECT_UNASSIGNED);
            //---------------------------------------------------------------------------------------------------------------------------
            initUser();
        } catch (Exception e) {
            logger.error("", e.getMessage());
        }
    }

    private void initUser() {
        new Thread(() -> {
            try {
                LocalDateTime now = LocalDateTime.now();
                IUserFactory userFactory = UMFactory.getUserFactory();
                ISearchResult searchResult = userFactory.searchUsers(userFactory.getUserSearchFilter());
                if (searchResult == null) return;
                //---------------------------------------------------------------------------------------------------------------------------
                while (searchResult.hasNext()) {
                    String userId = (String)searchResult.next();
                    IUser user = userFactory.getUser(userId);
                    IUserAccount userAccount = UMFactory.getUserAccountFactory().getUserAccount(ConstantsUtil.NWA_USER_ACCOUNT_ID_PREFIX + user.getName());
                    if (StringUtils.isEmpty(user.getFirstName()) && StringUtils.isEmpty(user.getLastName())) continue;
                    String fullName = user.getLastName();
                    if (!StringUtils.isEmpty(user.getFirstName())) fullName = fullName + user.getFirstName();
                    //---------------------------------------------------------------------------------------------------------------------------
                    String upperUserName = user.getName().toUpperCase();
                    String departmentInfo = user.getDepartment();
                    String department = null;
                    String departmentDescription = null;
                    if(departmentInfo != null){
                        department = departmentInfo.split("/").length > 0 ? departmentInfo.split("/")[0] : "";
                        departmentDescription = departmentInfo.split("/").length > 1 ? departmentInfo.split("/")[1] : "";
                    }
                    String[] sites = user.getAttribute("SAPME", "DEFAULT SITE");
                    String site = sites != null && sites.length > 0 ? sites[0] : null;
                    SysUser entity = sysUserService.selectOne(upperUserName);
                    if (entity == null) {
                        entity = new SysUser();
                        entity.setHandle(UUID.randomUUID().toString());
                        entity.setUserName(upperUserName);
                        entity.setCreateTime(now);
                        entity.setDelFlag(ConstantsUtil.N);
                    }//if
                    //---------------------------------------------------------------------------------------------------------------------------
                    entity.setSite(site);
                    entity.setFirstName(user.getFirstName());
                    entity.setLastName(user.getLastName());
                    entity.setFullName(fullName);
                    entity.setPhone(user.getCellPhone());
                    entity.setDeptId(department);
                    entity.setDeptDesc(departmentDescription);
                    entity.setJobTitle(user.getJobTitle());
                    entity.setEmail(user.getEmail());
                    if(userAccount.getValidFromDate() != null){
                        entity.setValidFrom(DateUtil.toLocalDateTime(userAccount.getValidFromDate()).toLocalDate());
                    }
                    if(userAccount.getValidToDate() != null){
                        entity.setValidTo(DateUtil.toLocalDateTime(userAccount.getValidToDate()).toLocalDate());
                    }
                    entity.setUpdateTime(now);
                    entity.setLockFlag(userAccount.isUserAccountLocked() ? ConstantsUtil.Y : ConstantsUtil.N);
                    //---------------------------------------------------------------------------------------------------------------------------
                    sysUserService.saveOrUpdate(entity);
                }//while
                //---------------------------------------------------------------------------------------------------------------------------
                // 删除NWA没有的数据
                //sysUserService.remove(Wrappers.<SysUser>lambdaQuery().lt(SysUser::getUpdateTime, now));
            } catch (Exception e) {
                logger.error("", e.getMessage());
            }
        }).start();
    }
}
