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.stereotype.Service;

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

@Service
public class NwaPrincipalListener implements PrincipalListener {

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

    @Autowired
    SysUserService sysUserService;

    @Override
    public void objectAdded(String s) throws UMException {
        logger.info("objectAdded: " + s);
        LocalDateTime now = LocalDateTime.now();
        //----------------------------------------------------------------------------------------------------------------------------
        // 创建用户
        if(s.startsWith(ConstantsUtil.NWA_USER_ID_PREFIX)) {
            IUser user = UMFactory.getUserFactory().getUser(s);
            if (StringUtils.isEmpty(user.getFirstName()) && StringUtils.isEmpty(user.getLastName())) return;
            String fullName = user.getLastName();
            if (!StringUtils.isEmpty(user.getFirstName())) fullName = fullName + user.getFirstName();
            //----------------------------------------------------------------------------------------------------------------------------
            //获取默认站点
            String[] sites = user.getAttribute("SAPME", "DEFAULT SITE");
            String site = sites != null && sites.length > 0 ? sites[0] : null;
            //获取部门信息
            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 upperUserName = user.getName().toUpperCase();
            SysUser entity = sysUserService.selectOne(upperUserName);
            if (entity == null) {
                entity = new SysUser();
                entity.setHandle(UUID.randomUUID().toString());
                entity.setUserName(upperUserName);
                entity.setCreateTime(now);
            }//if
            //----------------------------------------------------------------------------------------------------------------------------
            entity.setSite(site);
            entity.setFirstName(user.getFirstName());
            entity.setLastName(user.getLastName());
            entity.setFullName(fullName);
            entity.setPhone(user.getTelephone());
            entity.setDeptId(department);
            entity.setDeptDesc(departmentDescription);
            entity.setJobTitle(user.getJobTitle());
            entity.setEmail(user.getEmail());
            entity.setUpdateTime(now);
            entity.setLockFlag(ConstantsUtil.N);
            entity.setDelFlag(ConstantsUtil.N);
            //----------------------------------------------------------------------------------------------------------------------------
            sysUserService.saveOrUpdate(entity);
            // 创建用户账号，修改锁定状态
        } else if(s.startsWith(ConstantsUtil.NWA_USER_ACCOUNT_ID_PREFIX)) {
            IUserAccount user = UMFactory.getUserAccountFactory().getUserAccount(s);
            SysUser entity = sysUserService.selectOne(user.getLogonUid());
            if (entity != null) {
                entity.setLockFlag(user.isUserAccountLocked() ? ConstantsUtil.Y : ConstantsUtil.N);
                entity.setUpdateTime(now);
                //----------------------------------------------------------------------------------------------------------------------------
                sysUserService.saveOrUpdate(entity);
            }
        }
    }

    @Override
    public void objectRemoved(String s) throws UMException {
        logger.info("objectRemoved: " + s);
    }

    @Override
    public void objectEdited(String s) throws UMException {
        logger.info("objectEdited: " + s);
        LocalDateTime now = LocalDateTime.now();
        //----------------------------------------------------------------------------------------------------------------------------
        if (s.startsWith(ConstantsUtil.NWA_USER_ID_PREFIX)) {
            IUser user = UMFactory.getUserFactory().getUser(s);
            String fullName = user.getLastName();
            if (!StringUtils.isEmpty(user.getFirstName())) fullName = fullName + user.getFirstName();
            //----------------------------------------------------------------------------------------------------------------------------
            //获取默认站点
            String[] sites = user.getAttribute("SAPME", "DEFAULT SITE");
            String site = sites != null && sites.length > 0 ? sites[0] : null;
            //获取部门信息
            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 upperUserName = user.getName().toUpperCase();
            SysUser entity = sysUserService.selectOne(upperUserName);
            if (entity != null) {
                entity.setSite(site);
                entity.setFirstName(user.getFirstName());
                entity.setLastName(user.getLastName());
                entity.setFullName(fullName);
                entity.setPhone(user.getTelephone());
                entity.setDeptId(department);
                entity.setDeptDesc(departmentDescription);
                entity.setJobTitle(user.getJobTitle());
                entity.setEmail(user.getEmail());
                entity.setUpdateTime(now);
                //----------------------------------------------------------------------------------------------------------------------------
                sysUserService.saveOrUpdate(entity);
            }
        } else if (s.startsWith(ConstantsUtil.NWA_USER_ACCOUNT_ID_PREFIX)) {
            IUserAccount userAccount = UMFactory.getUserAccountFactory().getUserAccount(s);
            if (userAccount != null) {
                SysUser entity = sysUserService.selectOne(userAccount.getLogonUid());
                if (entity != null) {
                    if(userAccount.getValidFromDate() != null){
                        entity.setValidFrom(DateUtil.toLocalDateTime(userAccount.getValidFromDate()).toLocalDate());
                    }
                    if(userAccount.getValidToDate() != null){
                        entity.setValidTo(DateUtil.toLocalDateTime(userAccount.getValidToDate()).toLocalDate());
                    }
                    Boolean locked = userAccount.isUserAccountLocked();
                    entity.setLockFlag(locked != null && locked ? ConstantsUtil.Y : ConstantsUtil.N);
                    //----------------------------------------------------------------------------------------------------------------------------
                    sysUserService.saveOrUpdate(entity);
                }
            }
        }
    }

    @Override
    public void objectAssigned(String s, String s1) throws UMException {
        logger.info("objectAssigned: " + s);
    }

    @Override
    public void objectUnAssigned(String s, String s1) throws UMException {
        logger.info("objectUnAssigned: " + s);
    }
}