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.common.code.PlatformTypeEnum;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.module.site.model.SiteQuery;
import com.mortals.xhx.module.site.service.SiteService;
import com.mortals.xhx.module.sitestat.model.SitestatEntity;
import com.mortals.xhx.module.sitestat.service.SitestatService;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 站点统计任务
 *
 * @author: zxfei
 * @date: 2022/3/9 15:19
 */
@Slf4j
@Service("SiteStatTask")
public class SiteStatTaskImpl implements ITaskExcuteService {

    @Autowired
    private SitestatService sitestatService;
    @Autowired
    private ISiteFeign siteFeign;
    @Value("${platform.type:cloud}")
    private String platFormType;//版本，默认云服务版本
    @Autowired
    private SiteService siteService;


    @Override
    public void excuteTask(ITask task) throws AppException {
        if (platFormType.equalsIgnoreCase(PlatformTypeEnum.CLOUD.getValue())) {
            SitePdu sitePdu = new SitePdu();
            sitePdu.setSize(-1);
            Rest<RespData<List<SitePdu>>> resp = siteFeign.list(sitePdu);
            if (resp.getCode() == 1) {
                List<SitePdu> sitePduList = resp.getData().getData();
                sitePduList.stream().forEach(site -> {
                    SitestatEntity sitestatEntity = new SitestatEntity();
                    sitestatEntity.initAttrValue();
                    sitestatEntity.setSiteId(site.getId());
                    sitestatEntity.setSiteName(site.getSiteName());
                    sitestatEntity.setSiteCode(site.getSiteCode());
                    sitestatService.updateSiteStat(sitestatEntity, null);
                });
            }
        } else if (platFormType.equalsIgnoreCase(PlatformTypeEnum.STANDALONE.getValue())) {
            siteService.find(new SiteQuery()).forEach(site -> {
                SitestatEntity sitestatEntity = new SitestatEntity();
                sitestatEntity.initAttrValue();
                sitestatEntity.setSiteId(site.getId());
                sitestatEntity.setSiteName(site.getSiteName());
                sitestatEntity.setSiteCode(site.getSiteCode());
                sitestatService.updateSiteStat(sitestatEntity, null);
            });
        }

    }


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

    }


}
