package org.dromara.monitoring.service.impl;


import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.monitoring.config.SnowFlakeUtil;
import org.dromara.monitoring.config.YsDto;
import org.dromara.monitoring.domain.MonEquipmentHistroy;
import org.dromara.monitoring.domain.MonEquipmentList;
import org.dromara.monitoring.domain.dto.DelYzd;
import org.dromara.monitoring.domain.dto.MonitoringListDto;
import org.dromara.monitoring.domain.vo.MonList;
import org.dromara.monitoring.domain.vo.MonYsVo;
import org.dromara.monitoring.mapper.MonitoringYsMapper;
import org.dromara.monitoring.monEnum.ListConstant;
import org.dromara.monitoring.monEnum.QualityEnum;
import org.dromara.monitoring.monEnum.YsPort;
import org.dromara.monitoring.service.MonitoringYsService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class MonitoringYsServiceImpl implements MonitoringYsService {


    private final YsDto ysDto;

    private final MonitoringYsMapper monitoringYsMapper;

    private final String GETDEVICELISTURL = "https://open.ys7.com/api/lapp/device/list";



    @Override
    @Cacheable(cacheNames = "opsMonToken#432000s")
    public String getYsTokenService() {

        String jsonStr = HttpRequest.post(YsPort.GETTOKENURLBYPOST.getSite()).
            form("appKey", ysDto.getAppKey())
            .form("appSecret", ysDto.getAppSecret())
            .execute().body();


        JSONObject jsonObject = JSONUtil.parseObj(jsonStr.trim());
        String accessToken = jsonObject.getJSONObject("data").getStr("accessToken");
        return accessToken;
    }

    @Override
    public MonList getMonitoringList(MonitoringListDto dto) {

        MonList monList = new MonList();

        if (StringUtils.isEmpty(dto.getPageSize().toString())){
            dto.setPageSize(ListConstant.pageSize.getConstant());
            dto.setPageStart(ListConstant.PAGESTART.getConstant());
        }

//        分页查询
        String jsonStr = HttpRequest
            .post(YsPort.GETDEVICELISTURL.getSite()).
            form("accessToken",getYsTokenService())
            .form("pageStart",dto.getPageStart() - 1)
            .form("pageSize",dto.getPageSize())
            .execute().body();

        JSONObject jsonObject = JSONUtil.parseObj(jsonStr.trim());
        List<MonEquipmentList> data = (List<MonEquipmentList>)jsonObject.get("data");


        Map page1 = JSONUtil.parseObj(jsonObject.get("page")).toBean(Map.class);
        monList.setSum(Integer.parseInt(page1.get("total").toString()));


        if(dto.getPageSize() != ListConstant.pageSize.getConstant()&& dto.getIsflow()) {

            List<MonEquipmentHistroy> monEquipmentHistroys = new ArrayList<MonEquipmentHistroy>();
            data = JSONUtil.toList(data.toString(), MonEquipmentList.class);

            data.stream().forEach(item -> {
                MonEquipmentHistroy monEquipmentHistroy = new MonEquipmentHistroy();
                monEquipmentHistroy.setId(SnowFlakeUtil.getID());
                monEquipmentHistroy.setDeviceSerial(item.getDeviceSerial());
                monEquipmentHistroy.setDeviceName(item.getDeviceName());
                monEquipmentHistroy.setDeviceType(item.getDeviceType());
                monEquipmentHistroy.setUserId(LoginHelper.getUserId());
                monEquipmentHistroy.setDeptId(LoginHelper.getDeptId());
                monEquipmentHistroy.setProjectId(dto.getProjectId());
                monEquipmentHistroy.setCreateTime(LocalDateTime.now());
                monEquipmentHistroys.add(monEquipmentHistroy);
            });

//        将返回的数据列为点击数据
            if (monEquipmentHistroys.size() > 0) {
                monitoringYsMapper.insertHistroy(monEquipmentHistroys);
            }
        }
              monList.setObject(data);

//        查询所有并将数据存入数据库 :先判断数据库里是否有数据
      Integer sum =   monitoringYsMapper.setSunList();




        if(sum != Integer.parseInt(page1.get("total").toString())){
            monitoringYsMapper.delList();
            insertMonitoring(Integer.parseInt(page1.get("total").toString()),1);
        }
        return monList;
    }

    @Override
    public MonYsVo getMonitoringDp() {
       List<MonEquipmentList> list = monitoringYsMapper.selDpList();
        MonYsVo monYsVo = new MonYsVo();
        if (list.size() > 0){
            monYsVo.setSumMon(list.size());
            long count = list.stream().filter(item -> item.getStatus() == 1).count();
            monYsVo.setSumOnLine(count);
            monYsVo.setSumOffLine(list.size() - count);
        }

        return monYsVo;
    }

    @Override
    public String capturePho(DelYzd dto) {
        String temp = HttpRequest
            .post(YsPort.CAPTUREDEVICEURLBYPOST.getSite()).
            form("accessToken",getYsTokenService())
            .form("deviceSerial",dto.getDeviceSerial())
            .form("channelNo",dto.getChannelNo())
            .form("quality", QualityEnum.HIGHDEFINITION.getValue())
            .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(temp.trim());
        Map bean = JSONUtil.parseObj(jsonObject.get("data")).toBean(Map.class);
        /**Todo 后期照片需要对接ai识别 */
        return bean.get("picUrl").toString();
    }

    @Override
    public Void test() {
//        查询所有的设备
        List<MonEquipmentList> monEquipmentList = monitoringYsMapper.selDpList();

        monEquipmentList.forEach(item -> {
            serialNumber(item);
        });
        return null;
    }


    //格式化存储
    public void serialNumber(MonEquipmentList equipmentList){

        ArrayList<String> temp = selSTORAGEMEDIUMSTATUS(equipmentList.getDeviceSerial());
        if (temp.size() == 0)return;

        temp.forEach(s -> {
            HttpRequest
                .put(YsPort.DEVICESTORAGEMEDIUM.getSite())
                .header("accessToken",getYsTokenService())
                .form("deviceSerial",equipmentList.getDeviceSerial())
                .form("diskIndex",s)
                .execute().body();
        });

    }

    /**
     * 查询存储状态
     * @param deviceSerial
     * @return
     */
    public ArrayList<String> selSTORAGEMEDIUMSTATUS(String deviceSerial){

        ArrayList<String> res = new ArrayList<>();
        String body = HttpRequest
            .get(YsPort.STORAGEMEDIUMSTATUS.getSite())
            .header("accessToken", getYsTokenService())
            .form("deviceSerial", deviceSerial)
            .execute().body();

        JSONObject jsonObject = JSONUtil.parseObj(body.trim());




        Map bean = JSONUtil.parseObj(jsonObject.get("data")).toBean(Map.class);

        if (bean.get("storageStatus") == null){return res;}

        JSONArray objects = JSONUtil.parseArray( bean.get("storageStatus").toString());

        if (objects != null && objects.size() > 0){
            objects.stream().forEach(temp ->{
                Map temoMap = JSONUtil.parseObj(temp.toString()).toBean(Map.class);
                res.add(temoMap.get("index").toString());
            });
        }

        return res;

    }



    public void insertMonitoring(Integer sum,Integer start){
        if (sum > 50){
            String temp = HttpRequest
                .post(YsPort.GETDEVICELISTURL.getSite()).
                form("accessToken",getYsTokenService())
                .form("pageStart",start - 1)
                .form("pageSize",50)
                .execute().body();

            JSONObject jsonTemp = JSONUtil.parseObj(temp.trim());
            List<MonEquipmentList> tempList = (List<MonEquipmentList>)jsonTemp.get("data");
            tempList = JSONUtil.toList(tempList.toString(), MonEquipmentList.class);
            List<MonEquipmentList> collect = tempList.stream().map(monEquipmentList -> {

                monEquipmentList.setId(SnowFlakeUtil.getID());
                return monEquipmentList;
            }).collect(Collectors.toList());

            monitoringYsMapper.insettList(collect);
            start++;
            sum = sum - 50;
            insertMonitoring(sum,start);
        }else {
            String temp = HttpRequest
                .post(YsPort.GETDEVICELISTURL.getSite()).
                form("accessToken",getYsTokenService())
                .form("pageStart",start - 1)
                .form("pageSize",sum)
                .execute().body();

            JSONObject jsonTemp = JSONUtil.parseObj(temp.trim());
            List<MonEquipmentList> tempList = (List<MonEquipmentList>)jsonTemp.get("data");
            tempList = JSONUtil.toList(tempList.toString(), MonEquipmentList.class);
            List<MonEquipmentList> collect = tempList.stream().map(monEquipmentList -> {

                monEquipmentList.setId(SnowFlakeUtil.getID());
                return monEquipmentList;
            }).collect(Collectors.toList());

            monitoringYsMapper.insettList(collect);
        }
    }


}
