package com.mortals.xhx.module.sitestat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.xhx.common.code.DeviceStatusEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.common.utils.MemoryPagination;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.feign.user.IUserFeign;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.module.sitestat.model.SitestatQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.sitestat.dao.SitestatDao;
import com.mortals.xhx.module.sitestat.model.SitestatEntity;
import com.mortals.xhx.module.sitestat.service.SitestatService;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * SitestatService
 * 站点统计 service实现
 *
 * @author zxfei
 * @date 2022-06-27
 */
@Service("sitestatService")
@Slf4j
public class SitestatServiceImpl extends AbstractCRUDServiceImpl<SitestatDao, SitestatEntity, Long> implements SitestatService {

    @Autowired
    private ISiteFeign siteFeign;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private IUserFeign userFeign;
    @Autowired
    private IAuthTokenService authTokenService;

    /**
     * 重写带分页的方法
     *
     * @param entity
     * @param pageInfo
     * @param context
     * @return
     * @throws AppException
     */
    @Override
    public Result<SitestatEntity> find(SitestatEntity entity, PageInfo pageInfo, Context context) throws AppException {
        Result<SitestatEntity> res = new Result<>();
        //根据站点查询所以站点子集列表

        if (!ObjectUtils.isEmpty(entity.getSiteIdList())) {
            // TODO: 2022/7/1 站点为多站点时候合并
            List<SitestatEntity> collect = entity.getSiteIdList().stream().flatMap(siteId -> {
                SitePdu sitePdu = new SitePdu();
                sitePdu.setId(siteId);
                Rest<List<SitePdu>> result = siteFeign.getFlatSitesBySiteId(sitePdu);
                if (result.getCode() == YesNoEnum.YES.getValue()) {
                    //根据返回的id 筛选列表
                    Map<Long, SitestatEntity> collectMap = this.find(new SitestatEntity()).stream().collect(Collectors.toMap(x -> x.getSiteId(), y -> y, (o, n) -> n));
                    List<SitestatEntity> list = result.getData().stream().filter(f -> collectMap.containsKey(f.getId())).map(m -> collectMap.get(m.getId())).collect(Collectors.toList());
                    return list.stream();
                }
                return new ArrayList<SitestatEntity>().stream();
            }).collect(Collectors.toList());

            //列表去重
            collect = collect.stream().filter(MemoryPagination.distinctByKey(SitestatEntity::getId)).collect(Collectors.toList());

            if (!ObjectUtils.isEmpty(entity.getSiteName())) {
                collect = MemoryPagination.search(entity.getSiteName(), collect);
            }
            pageInfo.setTotalResult(collect.size());
            List<SitestatEntity> siteStatList = MemoryPagination.pagination(collect, pageInfo.getCurrPage(), pageInfo.getPrePageResult());
            res.setList(siteStatList);
            res.setPageInfo(pageInfo);
            return res;
        }

        if (ObjectUtils.isEmpty(entity.getSiteId())) {
            return res;
            //throw new AppException("当前站点ID不能为空！");
        }
        SitePdu sitePdu = new SitePdu();
        sitePdu.setId(entity.getSiteId());
        Rest<List<SitePdu>> result = siteFeign.getFlatSitesBySiteId(sitePdu);
        if (result.getCode() == YesNoEnum.YES.getValue()) {
            //根据返回的id 筛选列表
            Map<Long, SitestatEntity> collectMap = this.find(new SitestatEntity()).stream().collect(Collectors.toMap(x -> x.getSiteId(), y -> y, (o, n) -> n));
            List<SitestatEntity> list = result.getData().stream().filter(f -> collectMap.containsKey(f.getId())).map(m -> collectMap.get(m.getId())).collect(Collectors.toList());

            if (!ObjectUtils.isEmpty(entity.getSiteName())) {
                list = MemoryPagination.search(entity.getSiteName(), list);
            }
            pageInfo.setTotalResult(list.size());
            List<SitestatEntity> siteStatList = MemoryPagination.pagination(list, pageInfo.getCurrPage(), pageInfo.getPrePageResult());
            res.setList(siteStatList);
            res.setPageInfo(pageInfo);
        } else {
            log.info("error resp:{}", JSON.toJSONString(result));
        }
        return res;
    }

    @Override
    public String getSiteTree(Context context) {
//
        UserPdu userPdu = new UserPdu();
        userPdu.setLoginName("admin");
        userPdu.setPassword("admin");
        userPdu.setSecurityCode("8888");
        String loginResp = userFeign.portalLogin(userPdu);
        JSONObject loginRespJson = JSON.parseObject(loginResp);
        String token = loginRespJson.getJSONObject("data").getString("token");

      //  String token = context.getUser().getToken();
        String resp = siteFeign.siteTree(token);
        //log.info("treeResp:"+resp);
        return resp;
    }

    @Override
    public void updateSiteStat(SitestatEntity entity, Context context) {
        //更新统计信息，触发
        List<DeviceEntity> deviceList = deviceService.find(new DeviceQuery().siteId(entity.getSiteId()));
        //分别统计数据
        entity.setDeviceTotal(deviceList.size());

        Long onlineCount = deviceList.stream().filter(f -> f.getDeviceStatus() == DeviceStatusEnum.在线.getValue()).count();
        Long offlineCount = deviceList.stream().filter(f -> f.getDeviceStatus() == DeviceStatusEnum.离线.getValue()).count();
        Long unActiveCount = deviceList.stream().filter(f -> f.getDeviceStatus() == DeviceStatusEnum.未激活.getValue()).count();
        Long stopCount = deviceList.stream().filter(f -> f.getEnabled() == YesNoEnum.YES.getValue()).count();

        entity.setOnlineCount(onlineCount.intValue());
        entity.setOfflineCount(offlineCount.intValue());
        entity.setStopCount(stopCount.intValue());
        entity.setUnActiveCount(unActiveCount.intValue());

        //查询站点统计记录是否存在，如果存在则修改，否则新增
        SitestatEntity sitestatEntity = this.selectOne(new SitestatQuery().siteId(entity.getSiteId()));
        if (ObjectUtils.isEmpty(sitestatEntity)) {
            //新增
            entity.setCreateUserId(getContextUserId(context));
            entity.setCreateTime(new Date());
            this.save(entity, context);
        } else {
            //修改
            entity.setId(sitestatEntity.getId());
            entity.setUpdateUserId(getContextUserId(context));
            entity.setUpdateTime(new Date());
            this.update(entity, context);
        }

    }
}