package com.tofly.spire.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.haiqiu.tools.excel.utils.ExcelUtils;
import com.tofly.spire.entity.SpireBigGrid;
import com.tofly.spire.utils.ResultScada;
import com.tofly.spire.utils.SpireUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.spire.mapper.SpireMinGridMapper;
import com.tofly.spire.entity.SpireMinGrid;
import com.tofly.spire.entity.dto.SpireMinGridDto;
import com.tofly.spire.service.SpireMinGridService;
import org.springframework.stereotype.Service;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.io.Serializable;
import java.util.stream.Collectors;

/**
 * 小表（户表）(SpireMinGrid)表服务实现类
 *
 * @author HaiQiu
 * @since 2022-11-11 11:52:49
 */
@Service("spireMinGridService")
@Slf4j
public class SpireMinGridServiceImpl extends ServiceImpl<SpireMinGridMapper, SpireMinGrid> implements SpireMinGridService {

    @Autowired
    private SpireUtils spireUtils;


    /**
     * 定时获取-小表（户表）数据接口-通过此接口获取表端上传的数据信息以及日志信息
     * @param params
     * @return
     */
    @XxlJob("getMeterData")
    public ReturnT getMeterData(String params){
        String date="";
        ResultScada bulkMeterData = spireUtils.getMeterData(null,date);

        List<SpireMinGrid> data = JSONObject.parseArray(bulkMeterData.getData().toString(), SpireMinGrid.class);
        log.info("获取到接口数据：{}条", data.size());
        Date getReadTime=null;
        if(StringUtils.isEmpty(date)){
            date="2023-01-01";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            getReadTime = sdf.parse(date);
        } catch (ParseException e) {

            throw new RuntimeException(e);
        }
        if(data.size()>0){
            //查找库里面大于查询时间的所有数据
            List<SpireMinGrid>  list_old=super.list(Wrappers.<SpireMinGrid>lambdaQuery()
                    .ge(SpireMinGrid::getReadTime,getReadTime));

            if(list_old.size()>0){
                //取不同的差集，用于新增数据
                List<SpireMinGrid> list_diff=data.stream().filter(x->list_old.stream().noneMatch(e->e.getSn().equals(x.getSn()) && e.getReadTime().equals(x.getReadTime()))).collect(Collectors.toList());
                if(list_diff.size()>0){
                    //添加
                    saveBatch(list_diff);
                }

            }else{
                saveBatch(data);
            }
        }

        return ReturnT.SUCCESS;
    }

    /**
     * 定时获取-小表（户表）数据接口-通过此接口获取表端上传的数据信息以及日志信息
    * @return
     */
   @Override
    public long getMeterData(String sn, String date){
        ResultScada bulkMeterData = spireUtils.getMeterData(date,sn);
        List<SpireMinGrid> data = JSONObject.parseArray(bulkMeterData.getData().toString(), SpireMinGrid.class);
        log.info("获取到接口数据：{}条", data.size());

       Date getReadTime=null;
       if(StringUtils.isEmpty(date)){
           date="2023-01-01";
       }
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
       try {
           getReadTime = sdf.parse(date);
       } catch (ParseException e) {

           throw new RuntimeException(e);
       }
       if(data.size()>0){
       //查找库里面大于查询时间的所有数据
       List<SpireMinGrid>  list_old=super.list(Wrappers.<SpireMinGrid>lambdaQuery()
               .ge(SpireMinGrid::getReadTime,getReadTime));

       if(list_old.size()>0){
           //取不同的差集，用于新增数据
           List<SpireMinGrid> list_diff=data.stream().filter(x->list_old.stream().noneMatch(e->e.getSn().equals(x.getSn()) && e.getReadTime().equals(x.getReadTime()))).collect(Collectors.toList());
           if(list_diff.size()>0){
               //添加
               saveBatch(list_diff);
           }

       }else{
           saveBatch(data);
         }
       }
       return data.size();
}

    /**
     * 根据ID查询
     *
     * @param id id
     * @return 数据
     */
    @Override
    public SpireMinGrid get(Serializable id) {
        return getById(id);
    }

    /**
     * 新增
     *
     * @param spireMinGridDto 实体
     */
    @Override
    public void insert(SpireMinGridDto spireMinGridDto) {
        SpireMinGrid spireMinGrid = convert(spireMinGridDto);
        if (!save(spireMinGrid)) {
            throw new RuntimeException("新增失败");
        }
    }

    /**
     * 修改
     *
     * @param spireMinGridDto 实体
     */
    @Override
    public void edit(SpireMinGridDto spireMinGridDto) {
        SpireMinGrid spireMinGrid = convert(spireMinGridDto);
        if (!updateById(spireMinGrid)) {
            throw new RuntimeException("修改失败");
        }
    }

    /**
     * 实体转换
     *
     * @param spireMinGridDto dto实体
     */
    private SpireMinGrid convert(SpireMinGridDto spireMinGridDto) {
        SpireMinGrid spireMinGrid = new SpireMinGrid();
        BeanUtils.copyProperties(spireMinGridDto, spireMinGrid);
        return spireMinGrid;
    }

    /**
     * 批量删除
     *
     * @param idList 数据ID集合
     */
    @Override
    public void delete(List<Long> idList) {
        if (!removeByIds(idList)) {
            throw new RuntimeException("删除失败");
        }
    }

    /**
     * 生成模板下载
     */
    @Override
    public void template() {
        SpireMinGrid spireMinGrid = new SpireMinGrid();
        ExcelUtils.createTemplate("小表（户表）", "SpireMinGrid小表（户表）",
                "SpireMinGrid小表（户表）", SpireMinGrid.class, Collections.singletonList(spireMinGrid));
    }

    /**
     * 数据导入
     *
     * @param file 文件
     */
    @Override
    public void importData(MultipartFile file) {
        List<SpireMinGrid> datas = ExcelUtils.getExcelToList("小表（户表）", file, SpireMinGrid.class);
        if (!CollectionUtils.isEmpty(datas)) {
            saveBatch(datas);
        }
    }

    /**
     * 分页查询
     *
     * @param page         分页
     * @param spireMinGrid 查询wrapper
     * @return 数据集合
     */
    @Override
    public Page<SpireMinGrid> pageList(Page page, SpireMinGrid spireMinGrid) {
        return page(page, new QueryWrapper<>(spireMinGrid)).addOrder(page.getOrders());
    }

    /**
     * 数据导出
     *
     * @param page         分页
     * @param spireMinGrid 查询模型
     * @param isAll        是否导出全部数据，true是，false否
     */
    @Override
    public void export(Page page, SpireMinGrid spireMinGrid, Boolean isAll) {
        Page<SpireMinGrid> pageData = new Page<>();
        if (isAll == null || !isAll) {
            pageData = page(page, new QueryWrapper<>(spireMinGrid)).addOrder(page.getOrders());
        } else {
            pageData.setRecords(list(new QueryWrapper<>(spireMinGrid)));
        }
        //导出数据
        ExcelUtils.getListToExcel(SpireMinGrid.class, pageData.getRecords(), "小表（户表）");
    }

    /**
     * 查询所有数据
     *
     * @param spireMinGrid 查询条件
     * @return 查询所有数据
     */
    @Override
    public List<SpireMinGrid> allList(SpireMinGrid spireMinGrid) {
        return list(new QueryWrapper<>(spireMinGrid));
    }
}

