package com.mortals.xhx.daemon.applicationservice;

import com.mortals.framework.model.Context;
import com.mortals.framework.springcloud.service.IApplicationStartedService;
import com.mortals.framework.util.ThreadPool;
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.utils.SyncTreeSiteThread;
import com.mortals.xhx.module.site.service.SiteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 应用级服务，在应用启动后、停止过程中调用
 * 应用已经完成启动完成，才调用该服务
 * 应用场景：
 * 1、应用任务，应用启动后定时或间隔执行的任务
 * 2、Socket服务端
 */
@Component
@Slf4j
public class SiteStartedService implements IApplicationStartedService {

    @Autowired
    private SiteService siteService;
    @Autowired
    private UserService userService;


    @Override
    public void start() {
        log.info("开始服务..[初始化用户站点树]");
        ThreadPool.getInstance().init(20);
        UserEntity userEntity = new UserEntity();
        userEntity.initAttrValue();
        userEntity.setId(0L);
        Context contextTemp = new Context();
        contextTemp.setUser(userEntity);
        SyncTreeSiteThread syncTreeSiteThread = new SyncTreeSiteThread(siteService, contextTemp);
        ThreadPool.getInstance().execute(syncTreeSiteThread);

        userService.find(new UserQuery()).forEach(user -> {
            Context context = new Context();
            context.setUser(user);
            ThreadPool.getInstance().execute(new SyncTreeSiteThread(siteService, context));
        });

    }

    @Override
    public void stop() {
        log.info("停止服务..");
        ThreadPool.getInstance().close();
    }

    @Override
    public int getOrder() {
        return 10;
    }

}
