package com.huimv.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huimv.admin.common.utils.DataUill;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.entity.FeedArea;
import com.huimv.admin.entity.FeedPig;
import com.huimv.admin.entity.FeedingData;
import com.huimv.admin.entity.FeedingEnv;
import com.huimv.admin.mapper.FeedAreaMapper;
import com.huimv.admin.mapper.FeedPigMapper;
import com.huimv.admin.mapper.FeedingDataMapper;
import com.huimv.admin.mapper.FeedingEnvMapper;
import com.huimv.admin.service.IFeedAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-09-22
 */
@Service
public class FeedAreaServiceImpl extends ServiceImpl<FeedAreaMapper, FeedArea> implements IFeedAreaService {

    @Autowired
    private FeedingEnvMapper envMapper;
    @Autowired
    private FeedPigMapper pigMapper;
    @Autowired
    private FeedAreaMapper areaMapper;
    @Autowired
    private FeedingDataMapper dataMapper;

    @Override
    public Result feedType(Map<String, String> paramsMap) {
        return new Result(ResultCode.SUCCESS, pigMapper.selectList(null));
    }

    @Override
    public Result feedList(Map<String, String> paramsMap) {
        String earTag = paramsMap.get("eatTag");
        if ("".equals(earTag) || null == earTag) {
            earTag = "b17005701668064";
        }
        String url = "http://znsw.zxkj2006.com/feed/api/api/v1/pig/list/" + earTag;
        Map<String, String> heads = new HashMap<>();
        heads.put("Authorizationf", getToken());
        String body = HttpRequest.get(url).addHeaders(heads).execute().body();
        System.out.println(body);
        JSONObject jsonObject1 = JSONObject.parseObject(body);
        List<JSONObject> data = (List<JSONObject>) jsonObject1.get("data");
        System.out.println(data);
        JSONObject jsonObject = data.get(0);
        jsonObject.get("planFeedingCapacity");//计划喂料
        jsonObject.get("actualFeedingCapacity");//实际喂料
        jsonObject.get("actualWaterCapacity");//实际喂水
        JSONObject object = new JSONObject();
        object.put("planFeed", jsonObject.get("planFeedingCapacity"));
        object.put("actualWater", jsonObject.get("actualWaterCapacity"));
        object.put("actualFeed", jsonObject.get("actualFeedingCapacity"));
        return new Result(ResultCode.SUCCESS, object);

    }

    @Override
    public Result feedNumber(Map<String, String> paramsMap) {
//        String url = "http://znsw.zxkj2006.com/feed/api/api/v1/area/load/3b2a454b1e706856169dee136c17c974";
//        Map<String, String> heads = new HashMap<>();
//        heads.put("Authorizationf", getToken());
//        String body = HttpRequest.get(url).addHeaders(heads).execute().body();
//        System.out.println(body);
//        JSONObject jsonObject1 = JSONObject.parseObject(body);
//        JSONObject jsonObject = (JSONObject) jsonObject1.get("data");
//        JSONObject feedType = (JSONObject) jsonObject.get("feedType");
//        JSONObject jsonObject2 = new JSONObject();
//        jsonObject2.put("type", feedType.get("description"));
//        jsonObject2.put("value", feedType.get("newMealsMaterial"));
        List<FeedPig> pigs = pigMapper.selectList(null);
        JSONArray jsonArray = new JSONArray();
        for (FeedPig pig : pigs) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", pig.getType());
            jsonObject.put("number", pig.getMealNum());
            jsonArray.add(jsonObject);
        }
        return new Result(ResultCode.SUCCESS, jsonArray);
    }

    @Override
    public Result feedStatus(Map<String, String> paramsMap) {
        HashMap<String, String> paramMap = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("page", "10");
        jsonObject.put("currentPage", "1");
        jsonObject.put("farmId", "d5165406946f6d42398df89481dbc30e");
        jsonObject.put("customerId", null);
        jsonObject.put("lsId", null);
        jsonObject.put("unitId", null);
        paramMap.put("Content-Type", "application/json;charset=utf-8");
        paramMap.put("AuthorizationF", getToken());
        String post = HttpRequest.post("http://znsw.zxkj2006.com/feed/api/home/equipmentStatistics")
                .headerMap(paramMap, false).body(jsonObject.toJSONString()).timeout(30 * 1000).execute().body();
        JSONObject jsonObject1 = JSONObject.parseObject(post);
        JSONObject jsonObject2 = (JSONObject) jsonObject1.get("data");
        JSONObject object = new JSONObject();
        object.put("alarms", jsonObject2.get("alarms"));
        object.put("offlines", jsonObject2.get("offlines"));
        object.put("online", jsonObject2.get("online"));
        return new Result(ResultCode.SUCCESS, object);
    }

    @Override
    public Result reminderPig(Map<String, String> paramsMap) {
        HashMap<String, String> paramMap = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("page", "10");
        jsonObject.put("currentPage", "1");
        jsonObject.put("farmId", "d5165406946f6d42398df89481dbc30e");
        jsonObject.put("customerId", null);
        jsonObject.put("lsId", "e024a4eb306f6e0cbb880e01efe869a4");
        jsonObject.put("unitId", null);
        paramMap.put("Content-Type", "application/json;charset=utf-8");
        paramMap.put("AuthorizationF", getToken());
        String post = HttpRequest.post("http://znsw.zxkj2006.com/feed/api/home/reminderPig?pageNum=1&pageSize=10")
                .headerMap(paramMap, false).body(jsonObject.toJSONString()).timeout(30 * 1000).execute().body();
        JSONObject jsonObject1 = JSONObject.parseObject(post);
        JSONObject jsonObject2 = (JSONObject) jsonObject1.get("data");
        List<JSONObject> result = (List<JSONObject>) jsonObject2.get("records");
        return new Result(ResultCode.SUCCESS, result);
    }

    @Override
    public Result listCount(Map<String, String> paramsMap) {
        List<JSONObject> data=(List<JSONObject>) reminderPig(paramsMap).getData();
        Object total = data.size();//报警数量

        Date timesmorning = DataUill.getTimesmorning();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = sdf.format(timesmorning);
        String endDate = sdf.format(timesmorning);
        HashMap<String, String> paramMap = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("startDate", startDate);
        jsonObject.put("endDate", endDate);
        jsonObject.put("areaId", "3b2a454b1e706856169dee136c17c974");
        jsonObject.put("earTagr", "");
        jsonObject.put("lsId", "e024a4eb306f6e0cbb880e01efe869a4");
        jsonObject.put("flag", 0);
        paramMap.put("Content-Type", "application/json;charset=utf-8");
        paramMap.put("AuthorizationF", getToken());
        String post = HttpRequest.post("http://znsw.zxkj2006.com/feed/api/api/v1/data/queryEchartsData")
                .headerMap(paramMap, false).body(jsonObject.toJSONString()).timeout(30 * 1000).execute().body();

        System.out.println(post);
        JSONObject jsonObject1 = JSONObject.parseObject(post);
        JSONObject jsonObject2 = (JSONObject) jsonObject1.get("data");
        String s = "";
        String s1 = "";
        List<JSONObject> objects = (List<JSONObject>) jsonObject2.get("seriesDatas");
        if (objects.size() > 0) {
            JSONObject jsonObject3 = objects.get(0);
            List<String> data1 = (List<String>) jsonObject3.get("data");
             s = data1.get(2);//总饲喂量
            JSONObject jsonObject4 = objects.get(1);
            List<String> data2 = (List<String>) jsonObject4.get("data");
             s1 = data1.get(2);//总饮水量
        } else {
            s = "0";
            s1 = "0";
        }


        List<FeedingEnv> envs = envMapper.selectList(new QueryWrapper<FeedingEnv>().eq("online_status",0));//在线数量
        List<FeedingEnv> envs1 = envMapper.selectList(null);//饲养器数量
        Integer online = envs.size();
        Integer count = envs1.size();
        String format = "";
        if (count > 0) {
            double rank = Double.valueOf(online) / Double.valueOf(count)*100;
            DecimalFormat def = new DecimalFormat("0.00");
             format = def.format(rank);
        } else {
            format = "0.00";
        }

        JSONObject result = new JSONObject();
        result.put("alarm", total);
        result.put("envCount", envs1.size());
        result.put("onRank", format);
        result.put("feed", s);
        result.put("water", s1);
        return new Result(ResultCode.SUCCESS, result);
    }

    @Override
    public Result listEnvStatus(Map<String, String> paramsMap) {
        return new Result(ResultCode.SUCCESS, envMapper.selectList(null));
    }

    @Override
    public Result feedEnvCount(Map<String, String> paramsMap) {
        List<FeedArea> areas = areaMapper.selectList(null);//网关数量
        List<FeedingEnv> feedingEnvs = envMapper.selectList(null);
        Integer online = 0;
        Integer offline = 0;
        for (FeedingEnv feedingEnv : feedingEnvs) {
            if (feedingEnv.getOnlineStatus() == 0) {
                online = online + 1;
            } else {
                offline = offline + 1;
            }
        }
        String format = "";
        if (feedingEnvs.size() > 0) {
            Double rank = Double.valueOf(online) / Double.valueOf(feedingEnvs.size()) * 100;
            DecimalFormat def = new DecimalFormat("0.00");
            format = def.format(rank);//设备在线率
        } else {
            format = "0.00";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("gateway", areas.size());
        jsonObject.put("feedEnv", feedingEnvs.size());
        jsonObject.put("online", online);
        jsonObject.put("rank", format);
        return new Result(ResultCode.SUCCESS, jsonObject);
    }

    @Override
    public Result feedEnvList(Map<String, String> paramsMap) {
        String deviceCode = paramsMap.get("deviceCode");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        if ("".equals(pageNum) || null == pageNum) {
            pageNum = "1";
        }
        if ("".equals(pageSize) || null == pageSize) {
            pageSize = "10";
        }
        QueryWrapper<FeedingEnv> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(deviceCode), "device_code", deviceCode);
        Page<FeedingEnv> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        return new Result(ResultCode.SUCCESS, envMapper.selectPage(page,queryWrapper));
    }

    @Override
    public Result feedingList(Map<String, String> paramsMap) {
        String deviceCode = paramsMap.get("deviceCode");
        String pageNum = paramsMap.get("pageNum");
        String pageSize = paramsMap.get("pageSize");
        String type = paramsMap.get("type");
        if ("".equals(type) || null == type) {
            type = "0";
        }
        if ("".equals(pageNum) || null == pageNum) {
            pageNum = "1";
        }
        if ("".equals(pageSize) || null == pageSize) {
            pageSize = "10";
        }
        QueryWrapper<FeedingData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(deviceCode), "device_code", deviceCode).eq("device_type", type);
        Page<FeedingData> page = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        return new Result(ResultCode.SUCCESS, dataMapper.selectPage(page, queryWrapper));
    }

    @Override
    public Result feedingTypeCount(Map<String, String> paramsMap) {
        String type = paramsMap.get("type");//查询类型 0 育肥  1配怀 2保育 3分娩
        QueryWrapper<FeedPig> queryWrapper = new QueryWrapper<>();
        if ("0".equals(type)) {
            queryWrapper.eq("type", "育肥");
        } else if ("1".equals(type)) {
            queryWrapper.eq("type", "配怀");
        } else if ("2".equals(type)) {
            queryWrapper.eq("type", "保育");
        } else {
            queryWrapper.eq("type", "分娩");
        }
        FeedPig pig = pigMapper.selectOne(queryWrapper);//猪群数量
        List<FeedingEnv> envs = envMapper.selectList(new QueryWrapper<FeedingEnv>().eq("device_type", type));//饲养器数量
        Integer online = 0;
        for (FeedingEnv env : envs) {
            if (env.getDeviceStatus() == 0) {
                online = online + 1;
            }
        }
        String format = "";
        if (envs.size() > 0) {
            Double rank = Double.valueOf(online) / Double.valueOf(envs.size()) * 100;
            DecimalFormat def = new DecimalFormat("0.00");
             format = def.format(rank);//设备在线率
        } else {
            format = "0.00";
        }
        JSONObject jsonObject = new JSONObject();
        if (ObjectUtil.isNotEmpty(pig)) {
            jsonObject.put("pigNum", pig.getNumber());
        } else {
            jsonObject.put("pigNum", 0);
        }

        jsonObject.put("feedEnv", envs.size());
        jsonObject.put("online", online);
        jsonObject.put("rank", format);
        return new Result(ResultCode.SUCCESS, jsonObject);
    }

    @Override
    public Result feedingDetail(Map<String, String> paramsMap) {
        String eartag = paramsMap.get("eartag");
        QueryWrapper<FeedingData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("eartag", eartag);
        return new Result(ResultCode.SUCCESS, dataMapper.selectList(queryWrapper));
    }


    public String getToken() {
        HashMap<String, String> paramMap = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "ruanzong");
        jsonObject.put("password", "123456");
        paramMap.put("Content-Type", "application/json;charset=utf-8");
        String post = HttpRequest.post("http://znsw.zxkj2006.com/feed/api/admin/appLogin").headerMap(paramMap, false).body(jsonObject.toJSONString()).timeout(30 * 1000).execute().body();
        JSONObject jsonObject1 = JSONObject.parseObject(post);
        Map map = (Map) jsonObject1.get("data");
        String s = map.get("tokenHead") + " " + map.get("token");
        return s;
    }

}
