package com.nantian.cloud.jljc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nantian.cloud.jljc.entity.TDualcontrolParam;
import com.nantian.cloud.jljc.mapper.TDualcontrolParamMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jljc.service.TDualcontrolParamService;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import org.springframework.stereotype.Service;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * 能耗双控-参数设置 服务实现类
 */
@Service("tDualcontrolParamService")
public class TDualcontrolParamServiceImpl extends ServiceImpl<TDualcontrolParamMapper, TDualcontrolParam> implements TDualcontrolParamService {

    @Override
    public TDualcontrolParam getGearByComprehensiveWeight(String planYear, long versionId, Double weight) {
        Integer deptId = SecurityUtils.getUser().getDeptId();
        return baseMapper.getGearByComprehensiveWeight(planYear,versionId,weight,deptId);
    }

    @Override
    public List<TDualcontrolParam> initializePreData(String planYear, Long versionId) {
        String deptId = SecurityUtils.getUser().getDeptId().toString();
        String[] tmpYear = planYear.split("-");
        //int num = Integer.parseInt(tmpYear[0]) % 5;
        //Integer preYear = num==0 ? Integer.parseInt(tmpYear[0])-5 : Integer.parseInt(tmpYear[0])-num;
        Integer preYear = Integer.parseInt(tmpYear[0]) - 1;

        //查询当前版本数据
        List<TDualcontrolParam> preData = new ArrayList<>();
        preData = baseMapper.getPreData(deptId,planYear,versionId); //查询上个五年计划最后一年数据
        if(preData==null || preData.size()==0){
            //获取当前分解任务的历史版本信息
            QueryWrapper<TDualcontrolParam> q = new QueryWrapper<>();
            q.eq("del_flag","1");
            q.eq("type","0"); //查询版本信息
            q.eq("dept_id",deptId);
            q.eq("year",planYear);
            q.orderByDesc("update_time");
            List<TDualcontrolParam> version = baseMapper.selectList(q);
            a:for (TDualcontrolParam v : version) {
                preData = baseMapper.getPreData(deptId,planYear,v.getId()); //查询历史版本数据
                if(preData!=null && preData.size()>0){
                    for (TDualcontrolParam param : preData) {
                        param.setId(null);
                        param.setVersionId(null);
                    }
                    break a;
                }
            }
        }
        if(preData==null || preData.size()==0){
            //所有版本都没有数据，初始化上个五年计划最后一年数据
            preData = baseMapper.getInitializePreData(deptId,preYear);
        }

        //计算综合权重
        if (preData != null && preData.size() > 0) {
            DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
            TDualcontrolParam indexrCount = preData.get(0);
            for (TDualcontrolParam index : preData) {
                Double preEnergyUnitGdp = 0d, gdpTotalProportion = 0d, energyTotalProportion = 0d, comprehensiveWeight = 0d;
                if (index.getPreEnergyTotal() != null && index.getPreEnergyTotal() != 0 && index.getPreGdpTotal() != null && index.getPreGdpTotal() != 0) {
                    preEnergyUnitGdp = index.getPreEnergyTotal() / index.getPreGdpTotal();
                }
                if (index.getPreGdpTotal() != null && index.getPreGdpTotal() != 0 && indexrCount.getPreGdpTotal() != null && indexrCount.getPreGdpTotal() != 0) {
                    gdpTotalProportion = 100 * index.getPreGdpTotal() / indexrCount.getPreGdpTotal();
                }
                if (index.getPreEnergyTotal() != null && index.getPreEnergyTotal() != 0 && indexrCount.getPreEnergyTotal() != null && indexrCount.getPreEnergyTotal() != 0) {
                    energyTotalProportion = 100 * index.getPreEnergyTotal() / indexrCount.getPreEnergyTotal();
                }
                comprehensiveWeight = (gdpTotalProportion + energyTotalProportion) / 2;
                index.setPreEnergyUnitGdp(Double.parseDouble(df.format(preEnergyUnitGdp)));
                index.setGdpTotalProportion(Double.parseDouble(df.format(gdpTotalProportion)));
                index.setEnergyTotalProportion(Double.parseDouble(df.format(energyTotalProportion)));
                index.setComprehensiveWeight(Double.parseDouble(df.format(comprehensiveWeight)));
            }

            preData.sort(new Comparator<TDualcontrolParam>() {
                @Override
                public int compare(TDualcontrolParam o1, TDualcontrolParam o2) {
                    return (int)((o2.getComprehensiveWeight()- o1.getComprehensiveWeight())*100); //从大到小
                }
            });
        }
        return preData;
    }

    @Override
    public void saveOrUpdateParamBatch(String str) {
        JSONObject json = JSONObject.parseObject(str);
        TDualcontrolParam version = JSONArray.parseObject(json.getString("version"), TDualcontrolParam.class);
        TDualcontrolParam difference = (TDualcontrolParam) JSONObject.parseObject(json.getString("difference"), TDualcontrolParam.class);
        List<TDualcontrolParam> gear = (List<TDualcontrolParam>) JSONArray.parseArray(json.getString("gear"), TDualcontrolParam.class);
        List<TDualcontrolParam> data = (List<TDualcontrolParam>) JSONArray.parseArray(json.getString("data"), TDualcontrolParam.class);
        ScUser u = SecurityUtils.getUser();
        QueryWrapper<TDualcontrolParam> q = new QueryWrapper<>();
        q.eq("version_id",version.getId()); //只查询该版本数据
        q.eq("dept_id",u.getDeptId()); //只查询本部门参数
        q.eq("del_flag","1");
        q.eq("type","1"); //查询档位参数
        List<TDualcontrolParam> tmps = baseMapper.selectList(q); //历史数据
        for (TDualcontrolParam tmp : tmps) {
            boolean flag = true; //档位已删除
            a:for (TDualcontrolParam g : gear) {
                if(g.getId()!=null && tmp.getId()==g.getId()){
                    flag = false; //档位没有删除
                    break a;
                }
            }
            if(flag){
                tmp.setDelFlag("4"); //原来的档位被删除
                tmp.setUpdateTime(new Date());
                tmp.setUpdateUserid(u.getId());
                tmp.setUpdateUserName(u.getUserRealName());
                baseMapper.updateById(tmp);
            }
        }

        //类型(0版本,1档位,2差额值,3指标分解权重与平均增长率)
        List<TDualcontrolParam> params = new ArrayList<>();
        /*difference.setType("2");
        for (TDualcontrolParam param : gear) {
            param.setType("1");
        }
        for (TDualcontrolParam param : data) {
            param.setType("3");
        }*/
        params.add(difference);
        params.addAll(gear);
        params.addAll(data);
        for (TDualcontrolParam param : params) {
            param.setUpdateTime(new Date());
            param.setUpdateUserid(u.getId());
            if(param.getId()==null){
                param.setDelFlag("1");
                param.setAddTime(new Date());
                param.setAddUserid(u.getId());
                param.setAddUserName(u.getUserRealName());
                param.setDeptId(u.getDeptId());
                param.setYear(version.getYear()); //设置年度
                param.setVersionId(version.getId()); //设置版本id
                baseMapper.insert(param);
            }else{
                baseMapper.updateById(param);
            }
        }
        version.setUpdateTime(new Date());
        version.setUpdateUserid(u.getId());
        baseMapper.updateById(version); //更新版本数据
    }
}
