package com.mortals.xhx.daemon.task;

import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.feign.user.IUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 同步门户用户
 */
@Slf4j
@Service("SyncPortalUserTask")
public class SyncPortalUserTaskImpl implements ITaskExcuteService {

    @Autowired
    private IUserFeign userFeign;

    @Autowired
    private UserService userService;


    @Override
    public void excuteTask(ITask task) throws AppException {
        try {
            log.info("同步门户用户");
            syncPersons();
        } catch (Exception e) {
            log.error("同步门户异常", e);
        }
    }

    private void syncPersons() {
        UserPdu userPdu = new UserPdu();
        userPdu.setPage(1);
        userPdu.setSize(-1);
        Rest<RespData<List<UserPdu>>> resp = userFeign.list(userPdu);
        if (resp.getCode() == YesNoEnum.YES.getValue()) {
            List<UserPdu> userPduList = resp.getData().getData();
            log.info("用户总数量：{}", userPduList.size());
            if (!ObjectUtils.isEmpty(userPduList)) {
                List<UserEntity> newUserList = userPduList.stream().map(newUser -> {
                    UserEntity userEntity = new UserEntity();
                    userEntity.initAttrValue();
                    BeanUtils.copyProperties(newUser, userEntity, new String[]{"id", "lastLoginTime", "lastLoginAddress"});
                    return userEntity;
                }).collect(Collectors.toList());

                List<UserEntity> oldUserList = userService.find(new UserQuery());
                log.info(" oldUserList size：{}", oldUserList.size());

                //当前用户map
                Map<String, UserEntity> oldUserMap = oldUserList.parallelStream().collect(Collectors.toMap(x -> x.getLoginName(), y -> y, (o, n) -> n));
                List<UserEntity> saveUserList = newUserList.stream().map(item -> {
                    if (!oldUserMap.containsKey(item.getLoginName())) {
                        item.setCreateUserId(1L);
                        item.setCreateUserName("系统管理员");
                        item.setCreateTime(new Date());
                        return item;
                    }
                    return null;
                }).filter(f -> f != null).collect(Collectors.toList());


                if (!ObjectUtils.isEmpty(saveUserList)) {
                    log.info("用户新增，size:{}", saveUserList.size());
                    saveUserList.stream().forEach(item -> {
                        userService.getUserDao().insert(item);
                    });
                }
            }
        }

    }

    @Override
    public void stopTask(ITask task) throws AppException {

    }
}
