package com.gyee.frame.service.report;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gyee.frame.common.dataSources.DataSource;
import com.gyee.frame.common.dataSources.DataSourceType;
import com.gyee.frame.mapper.auto.MisdailydataMapper;
import com.gyee.frame.mapper.auto.NoscaledataMapper;
import com.gyee.frame.mapper.auto.WfpfdataMapper;
import com.gyee.frame.model.auto.*;
import com.gyee.frame.util.SnowflakeIdWorker;
import com.gyee.frame.util.StringUtils;
import com.gyee.frame.util.excel.MisDailyData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MisDailyDateService {

    @Resource
    private MisdailydataMapper misdailydataMapper;
    @Resource
    private NoscaledataMapper noscaledataMapper;
    @Resource
    private WfpfdataMapper wfpfdataMapper;

    List<Noscwfdata> gll = null;

    /**
     * 保存数据
     *
     * @param list
     */
    @Transactional
    public void insert(List<MisDailyData> list) {
        if (list == null || list.size() == 0)
            return;

        list.stream().forEach(a -> {
            String str = JSONObject.toJSONString(a);
            Misdailydata data = JSON.parseObject(str, Misdailydata.class);
            data.setId(SnowflakeIdWorker.getUUID());
            boolean flag = selectItem(data);
            if (!flag)
                misdailydataMapper.insert(data);
        });
    }

    /**
     * 保存数据
     *
     * @param list
     */
    @Transactional
    public void insertgz(List<Misdailydata> list) {
        if (list == null || list.size() == 0)
            return;

        list.forEach(data -> {
            data.setId(SnowflakeIdWorker.getUUID());
            boolean flage = selectItemgz(data);
            if (!flage) {
                misdailydataMapper.insert(data);
            }
        });
    }

    /**
     * 查询功率预测数据
     *
     * @return
     */
    @DataSource(value = DataSourceType.PREDICT)
    public List<Noscwfdata> query() {
        return wfpfdataMapper.slectGlyc();
    }
    //处理字段名
    @DataSource(value = DataSourceType.PREDICT)
    public void gl (){
        List<Noscwfdata> list = wfpfdataMapper.slectGlyc();
//        list.forEach(ss->
//                ss.setWindplantNo(projectMap().get(ss.getWindplantNo()))
//        );
        gll = list;
    }

    /**
     * 写入功率预测数据
     *
     * @return
     */
    @DataSource(value = DataSourceType.MASTER)
    public List<Noscwfdata> write() {
        Misdailydata misdailydata = new Misdailydata();
        gll.forEach(data -> {
            java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String date = formatter.format(data.getData_Time());
//
//            java.text.SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//            Date date1=null;
//            try {
//                date1 = dateFormat.parse(date);
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }

            if(projectMap().get(data.getWindplant_No())==null){
                System.out.println();
            }
            List<Misdailydata> list1 = misdailydataMapper.selectByExamplegl(date,projectMap().get(data.getWindplant_No()));
            if(list1.size()>0){
                misdailydataMapper.updategl(data.getAccuracy_Rate(),list1.get(0).getId());
            }else {

                misdailydata.setId(SnowflakeIdWorker.getUUID());
                misdailydata.setName(projectMap().get(data.getWindplant_No()));
                misdailydata.setImportdate(data.getData_Time());
                misdailydata.setDqglyczql(data.getAccuracy_Rate());
                misdailydataMapper.insert(misdailydata);
            }
        });

        return  gll;

    }


    /**
     * 字段对应
     *
     * @return
     */
    private Map<Short, String> projectMap() {
        Map<Short, String> map = new HashMap<>();
        map.put((short) 1, "牛首山风电场");
        map.put((short) 2, "青山风电场");
        map.put((short) 3, "石板泉风电场");
        map.put((short) 4, "香山风电场");
        map.put((short) 5, "麻黄山风电场");
        map.put((short) 6, "麻六");
        map.put((short) 7, "宋六");
        map.put((short) 8, "星六");
        map.put((short) 9, "牛五");
        return map;
    }

    /**
     * 查询是否存在
     *
     * @param data
     * @return
     */
    public boolean selectItem(Misdailydata data) {
        MisdailydataExample example = new MisdailydataExample();
        example.createCriteria()
                .andImportdateEqualTo(data.getImportdate())
                .andUnitNoEqualTo(data.getUnitNo());

        List<Misdailydata> list = misdailydataMapper.selectByExample(example);
        if (list.size() > 0)
            return true;
        else
            return false;
    }

    /**
     * 查询是否存在故障数据
     *
     * @param data
     * @return
     */
    public boolean selectItemgz(Misdailydata data) {
        MisdailydataExample example = new MisdailydataExample();
        example.createCriteria()
                .andImportdateEqualTo(data.getImportdate())
                .andProjectidEqualTo(data.getProjectid())
                .andUnitNoIsNull();

        java.text.SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String date = formatter.format(new Date());

        List<Misdailydata> list = misdailydataMapper.selectByExamplegz(date, data.getProjectid());
        if (list.size() > 0)
            return true;
        else
            return false;
    }

    /**
     * 更新或删除短期功率预测数据和故障次数
     *
     * @param data
     * @return
     */
    public boolean insertOrUpdate(Misdailydata data) {
        int i = 0;

        if (StringUtils.isEmpty(data.getId())) {
            data.setId(SnowflakeIdWorker.getUUID());
            i = misdailydataMapper.insert(data);
        } else {
            i = misdailydataMapper.updateByPrimaryKey(data);
        }

        return i > 0 ? true : false;
    }

    /**
     * 查询短期功率数据及故障次数
     *
     * @param date
     * @return
     */
    public Misdailydata selectItemByDate(Date date) {
        MisdailydataExample example = new MisdailydataExample();
        example.createCriteria().andImportdateEqualTo(date)
                .andUnitNoIsNull();

        List<Misdailydata> list = misdailydataMapper.selectByExample(example);

        Misdailydata obj = list.size() > 0 ? list.get(0) : new Misdailydata();

        return obj;
    }


    /**
     * 计算数据   风速、同期电量等
     *
     * @param st
     * @param et
     */
    public List<Object> getCalData(Date st, Date et) {
        //当前数据
        MisdailydataExample example = new MisdailydataExample();
        example.createCriteria().andImportdateBetween(st, et)
//                .andProjectidIsNotNull()
                .andUnitNoIsNotNull();
        example.setOrderByClause(" IMPORTDATE ASC");
        List<Misdailydata> listC = misdailydataMapper.selectByExample(example);

        //同期数据
        Calendar cal = Calendar.getInstance();
        cal.setTime(st);
        cal.add(Calendar.YEAR, -1);
        Date sDate = cal.getTime();
        cal.clear();
        cal.setTime(et);
        cal.add(Calendar.YEAR, -1);
        Date eDate = cal.getTime();

        MisdailydataExample example2 = new MisdailydataExample();
        example2.createCriteria().andImportdateBetween(sDate, eDate)
                .andUnitNoIsNotNull();

        example2.setOrderByClause(" IMPORTDATE ASC");
        List<Misdailydata> listT = misdailydataMapper.selectByExample(example2);
        Map<String, List<Misdailydata>> collect2 = listT.stream().filter(a -> !a.getProjectid().equals("HJ"))
                .collect(Collectors.groupingBy(Misdailydata::getName, Collectors.toList()));

        //计算数据
        List<Object> list = new ArrayList<>();
        if (listC.size() > 0) {
            Map<String, List<Misdailydata>> collect = listC.stream().filter(a -> !a.getProjectid().equals("HJ"))
                    .collect(Collectors.groupingBy(Misdailydata::getName, Collectors.toList()));
            collect.forEach((k, v) -> {
                Map<String, Object> mp = new HashMap<>();
                double pjfs = v.stream().mapToDouble(Misdailydata::getPjfsJzR).average().getAsDouble();
                double fdl = v.stream().mapToDouble(Misdailydata::getFdlJzR).sum();
                double yfdl = v.stream().max(Comparator.comparing(Misdailydata::getImportdate)).get().getYfdlJzR();
                double fdlscada = v.stream().mapToDouble(Misdailydata::getFdlJzRScada).sum();
                double swdl = v.stream().mapToDouble(Misdailydata::getSwdlJzRT).sum();
                double zhcydl = v.stream().mapToDouble(Misdailydata::getZhcydlJzR).sum();
                double zhcydlscada = v.stream().mapToDouble(Misdailydata::getZhcydlJzRScada).sum();
                mp.put("name", k);
                mp.put("fs1", pjfs);
                mp.put("fdl1", fdl);
                mp.put("ylj1", yfdl);
                mp.put("fdlscada1", fdlscada);
                mp.put("swdl1", swdl);
                mp.put("zhcydl1", zhcydl);
                mp.put("zhcydlscada1", zhcydlscada);

                List<Misdailydata> ls = collect2.get(k);
                double pjfs2 = ls.stream().mapToDouble(Misdailydata::getPjfsJzR).average().getAsDouble();
                double fdl2 = ls.stream().mapToDouble(Misdailydata::getFdlJzR).sum();
                double yfdl2 = ls.stream().max(Comparator.comparing(Misdailydata::getImportdate)).get().getYfdlJzR();
                double fdlscada2 = ls.stream().mapToDouble(Misdailydata::getFdlJzRScada).sum();
                double swdl2 = ls.stream().mapToDouble(Misdailydata::getSwdlJzRT).sum();
                double zhcydl2 = ls.stream().mapToDouble(Misdailydata::getZhcydlJzR).sum();
                double zhcydlscada2 = ls.stream().mapToDouble(Misdailydata::getZhcydlJzRScada).sum();
                mp.put("fs2", pjfs2);
                mp.put("fdl2", fdl2);
                mp.put("ylj2", yfdl2);
                mp.put("fdlscada2", fdlscada2);
                mp.put("swdl2", swdl2);
                mp.put("zhcydl2", zhcydl2);
                mp.put("zhcydlscada2", zhcydlscada2);

                list.add(mp);
            });
        }

        return list;
    }

    public static void main(String[] args) {
    }
}
