package com.bocloud.ims.service.resource.fusionsphere;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.monitor.MonitorDriver;
import com.bocloud.cmp.model.fusionsphere.FusionSphereMonitorModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.JSONTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Vdc;
import com.bocloud.ims.interfaces.resource.fusionsphere.FusionSphereMonitorService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.VdcRepository;
import com.bocloud.ims.service.model.ResultTrend;
import com.bocloud.ims.service.model.StatsResult;
import com.bocloud.ims.service.model.TrendData;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FusionSphereMonitorServiceImpl implements FusionSphereMonitorService {

    private static Logger logger = LoggerFactory.getLogger(FusionSphereMonitorServiceImpl.class);
    @Autowired
    private MonitorDriver monitorDriver;
    @Autowired
    private CloudVendorRepository vendorRepository;
    @Autowired
    private VdcRepository vdcRepository;

    @Override
    public BocloudResult metrics(Long id, String params, RequestContext context) {
        try {
            JSONObject object = JSONTools.isJSONObj(params);
            Long vendorId = object.getLong("vendorId");
            Long vdcId = object.getLong("vdcId");
            CloudVendor vendor = vendorRepository.query(vendorId);
            if (ObjectUtils.isEmpty(vendor)) {
                logger.error("get cloudVendor failure");
                return new BocloudResult(false, "平台验证失败");
            }
            // 站点
            Vdc vdc = vdcRepository.query(vdcId);
            if (ObjectUtils.isEmpty(vdc)) {
                logger.error("get vdc failure");
                return new BocloudResult(false, "站点验证失败");
            }

            FusionSphereMonitorModel model = new FusionSphereMonitorModel();
            model.setUrn(object.getString("urn"));
            model.setMetricId(object.getString("metricId"));
            model.setStartTime(object.getString("startTime"));
            model.setEndTime(object.getString("endTime"));
            model.setInterval(object.getString("interval"));

            BocloudResult bocloudResult = monitorDriver.metrics(vendor.getUuid(), model, vdc.getUri());
            String response = (String) bocloudResult.getData();
            JSONObject responseObject = JSONObject.parseObject(response);

            List<String> keys = new ArrayList<>();
            List<String> trendData = Lists.newArrayList();
            List<TrendData> dataList = Lists.newArrayList();

            JSONArray items = responseObject.getJSONArray("items");
            JSONObject item = items.getJSONObject(0);

            String name = item.getString("metricName");
            JSONArray tv = item.getJSONArray("metricValue");

            List<StatsResult> statsResults = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (java.util.Iterator tor = tv.iterator(); tor.hasNext(); ) {
                StatsResult statsResult = new StatsResult();
                JSONObject t = (JSONObject) tor.next();
                String key = t.getString("time") + "000";
                String keyTiem = sdf.format(new Date(Long.valueOf(key)));
                statsResult.setName(keyTiem);
                statsResult.setValue(t.getString("value") == null ? 0 : t.getString("value"));
                statsResults.add(statsResult);
            }
            statsResults.stream().forEach(statsResult -> {
                keys.add(statsResult.getName());
                trendData.add(statsResult.getValue() + "");
            });
            dataList.add(new TrendData(name, trendData));
            ResultTrend resultTrend = new ResultTrend(keys, dataList);
            return new BocloudResult(true, resultTrend, "查询成功");
        } catch (Exception e) {
            logger.error("list metrics error!", e);
            return new BocloudResult(true, "暂无监控指标数据，请稍后查询！");
        }
    }
}
