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.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.stereotype.Component;


@Component
@Slf4j
@ConditionalOnExpression("'${platform.type:standalone}'=='standalone'")
public class SiteStartedService implements IApplicationStartedService {

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


    @Override
    public void start() {
        log.info("开始服务..[初始化用户站点树]");
        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;
    }

}
