package com.fastbee.waterele.service.impl;

import java.util.*;
import java.util.function.Function;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fastbee.common.core.page.PageDomain;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.core.page.TableSupport;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.waterele.domain.MaGuangaiRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fastbee.waterele.mapper.MaWatereleRecordMapper;
import com.fastbee.waterele.domain.MaWatereleRecord;
import com.fastbee.waterele.service.IMaWatereleRecordService;

/**
 * 水电双计数据记录Service业务层处理
 * 
 * @author kerwincui
 * @date 2024-08-12
 */
@Service
public class MaWatereleRecordServiceImpl implements IMaWatereleRecordService
{
    @Autowired
    private MaWatereleRecordMapper maWatereleRecordMapper;

    /**
     * 查询水电双计数据记录
     * 
     * @param id 水电双计数据记录主键
     * @return 水电双计数据记录
     */
    @Override
    public MaWatereleRecord selectMaWatereleRecordById(Long id)
    {
        return maWatereleRecordMapper.selectMaWatereleRecordById(id);
    }

    /**
     * 查询水电双计数据记录列表
     * 
     * @param maWatereleRecord 水电双计数据记录
     * @return 水电双计数据记录
     */
    @Override
    public TableDataInfo  selectMaWatereleRecordList(MaWatereleRecord maWatereleRecord)
    {
        List<MaWatereleRecord> list = getList(maWatereleRecord);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<MaWatereleRecord> subList = new ArrayList<>();
        if(list.size() > (pageNum-1)*pageSize){
            if(list.size() < pageNum*pageSize){
                subList = list.subList((pageNum-1)*pageSize, list.size());
            }else{
                subList = list.subList((pageNum-1)*pageSize, pageNum*pageSize);
            }
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("获取成功");
        tableDataInfo.setTotal(list.size());
        tableDataInfo.setRows(subList);
        tableDataInfo.setCode(200);
        return tableDataInfo;
    }

    @Override
    public List<MaWatereleRecord> getList(MaWatereleRecord maWatereleRecord){
        Long endTime = 0L;
        Long startTime = 0L;
        if(null == maWatereleRecord.getParams()){
            endTime = new Date().getTime()/1000;
            startTime = endTime - 86400*3;
        }else{
            if(!maWatereleRecord.getParams().containsKey("endCreateTime")){
                endTime = new Date().getTime()/1000;
            }else{
                endTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,
                        maWatereleRecord.getParams().get("endCreateTime").toString()).getTime();
            }
            if(!maWatereleRecord.getParams().containsKey("beginCreateTime")){
                startTime = endTime - 86400*3;
            }else{
                startTime = DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS,
                        maWatereleRecord.getParams().get("beginCreateTime").toString()).getTime();
            }
        }
        Date startDate = new Date();
        startDate.setTime(startTime*1000);
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,startDate);
        Date endDate = new Date();
        endDate.setTime(endTime*1000);
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,endDate);
        String url = "https://zhwly.sdhzwl.cn/api/java/xinjiangup/getShuakaRecord?devSn="
                +maWatereleRecord.getDevSn()+"&startTime="+startDateStr+"&endTime="+endDateStr;
        String result = HttpUtil.get(url);

        JSONObject jsonObject = new JSONObject(result);
        List<MaWatereleRecord> list = new ArrayList<>();
        if(jsonObject != null){
            if(jsonObject.containsKey("code") && Integer.parseInt(jsonObject.get("code").toString()) == 200){
                if(jsonObject.containsKey("data") && jsonObject.get("data") != null){
                    JSONArray dataList = (JSONArray)jsonObject.get("data");
                    for (Object object : dataList) {
                        JSONObject item = (JSONObject)object;
                        MaWatereleRecord record = new MaWatereleRecord();
                        record.setDevSn(item.get("dev_sn").toString());
                        record.setWorkstate(Integer.parseInt(item.get("workState").toString()));
                        record.setUsersumflow(item.get("userSumFlow").toString().equals("null")?"--":item.get("userSumFlow").toString());
                        record.setUsersumele(item.get("userSumEle").toString().equals("null")?"--":item.get("userSumEle").toString());
                        record.setUserbalance(item.get("userBalance").toString().equals("null")?
                                "--":(com.fastbee.common.utils.NumberUtils.formatFloat(
                                        Float.parseFloat(item.get("userBalance").toString())/100)+""));
                        record.setSumflow(item.get("sumFlow").toString().equals("null")?"--":item.get("sumFlow").toString());
                        record.setSumele(item.get("sumEle").toString().equals("null")?"--":item.get("sumEle").toString());
                        record.setMcusn(item.get("mcuSn").toString().equals("null")?"--":item.get("mcuSn").toString());
                        record.setInspower(item.get("insPower").toString().equals("null")?"--":item.get("insPower").toString());
                        record.setInsflow(item.get("insFlow").toString().equals("null")?"--":item.get("insFlow").toString());
                        record.setCurflow(item.get("curFlow").toString().equals("null")?"--":item.get("curFlow").toString());
                        record.setCurele(item.get("curEle").toString().equals("null")?"--":item.get("curEle").toString());
                        record.setMetersum(item.get("meterSum").toString().equals("null")?"--":item.get("meterSum").toString());
                        record.setMeterins(item.get("meterIns").toString().equals("null")?"--":item.get("meterIns").toString());
                        record.setCardid(item.get("cardId").toString().equals("null")?"--":item.get("cardId").toString());
                        record.setAreacode(item.get("areaCode").toString().equals("null")?"--":item.get("areaCode").toString());
                        record.setAction(item.get("action").toString().equals("null")?"--":item.get("action").toString());
                        if(StringUtils.isNotEmpty(item.get("create_time").toString())){
                            if(NumberUtil.isNumber(item.get("create_time").toString())) {
                                Date date = new Date(Long.parseLong(item.get("create_time").toString()) * 1000);
                                record.setCreateTime(date);
                            }
                        }
                        if(StringUtils.isNotEmpty(item.get("update_time").toString())){
                            if(NumberUtil.isNumber(item.get("update_time").toString())) {
                                Date date = new Date(Long.parseLong(item.get("update_time").toString()) * 1000);
                                record.setUpdateTime(date);
                            }
                        }
                        list.add(record);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 新增水电双计数据记录
     * 
     * @param maWatereleRecord 水电双计数据记录
     * @return 结果
     */
    @Override
    public int insertMaWatereleRecord(MaWatereleRecord maWatereleRecord)
    {
        maWatereleRecord.setCreateTime(DateUtils.getNowDate());
        return maWatereleRecordMapper.insertMaWatereleRecord(maWatereleRecord);
    }

    /**
     * 修改水电双计数据记录
     * 
     * @param maWatereleRecord 水电双计数据记录
     * @return 结果
     */
    @Override
    public int updateMaWatereleRecord(MaWatereleRecord maWatereleRecord)
    {
        maWatereleRecord.setUpdateTime(DateUtils.getNowDate());
        return maWatereleRecordMapper.updateMaWatereleRecord(maWatereleRecord);
    }

    /**
     * 批量删除水电双计数据记录
     * 
     * @param ids 需要删除的水电双计数据记录主键
     * @return 结果
     */
    @Override
    public int deleteMaWatereleRecordByIds(Long[] ids)
    {
        return maWatereleRecordMapper.deleteMaWatereleRecordByIds(ids);
    }

    /**
     * 删除水电双计数据记录信息
     * 
     * @param id 水电双计数据记录主键
     * @return 结果
     */
    @Override
    public int deleteMaWatereleRecordById(Long id)
    {
        return maWatereleRecordMapper.deleteMaWatereleRecordById(id);
    }

    @Override
    public ArrayList<Object> chartData(MaWatereleRecord maWatereleRecord) {
        Map<String, Object> map = new HashMap<String, Object>();
        ArrayList<Object> list = new ArrayList<>();
        List<MaWatereleRecord> maWatereleRecords = maWatereleRecordMapper.selectMaWatereleRecordList(maWatereleRecord);
        List<String> time = new ArrayList<>();
        List<String> sumFlow = new ArrayList<>();
        List<String> sumEle = new ArrayList<>();
//        HashMap<String, Object> sumFlowtMap = new HashMap<>();
//        sumFlowtMap.put("name", "累计水量");
//        sumFlowtMap.put("unit", "m³");
        HashMap<String, Object> sumEletMap = new HashMap<>();
        sumEletMap.put("name", "累计电量");
        sumEletMap.put("unit", "度");
        for (MaWatereleRecord record : maWatereleRecords) {
            time.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, record.getCreateTime()));
            sumFlow.add(record.getSumflow());
            sumEle.add(record.getSumele());
        }
//        sumFlowtMap.put("time", time);
//        sumFlowtMap.put("data", sumFlow);
        sumEletMap.put("time", time);
        sumEletMap.put("data", sumEle);
//        list.add(sumFlowtMap);
        list.add(sumEletMap);
//        map.put("time", time);
//        map.put("sumFlow", sumFlow);
//        map.put("sumEle", sumEle);
        return list;
    }
}
