package com.steerinfo.ems.emscalpointvalue.service.impl;

import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.emscalpointvalue.model.EmsCalpointValue;
import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.emscalpointvalue.mapper.EmsCalpointValueMapper;
import com.steerinfo.ems.emscalpointvalue.service.IEmsCalpointValueService;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmcalpoint.mapper.TRmCalpointMapper;
import com.steerinfo.ems.trmcalpoint.model.TRmCalpoint;
import com.steerinfo.ems.trmcalpointvalue.mapper.TRmCalpointValueMapper;
import com.steerinfo.ems.trmcalpointvalue.model.TRmCalpointValue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * EmsCalpointValue服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-05-16 09:36
 * 类描述
 * 修订历史：
 * 日期：2020-05-16
 * 作者：generator
 * 参考：
 * 描述：EmsCalpointValue服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "emsCalpointValueService")
public class EmsCalpointValueServiceImpl extends BaseServiceImpl<EmsCalpointValue, HashMap<String, Object>> implements IEmsCalpointValueService {

    @Autowired
    private EmsCalpointValueMapper emsCalpointValueMapper;
    
    @Autowired
    private TRmCalpointValueMapper tRmCalpointValueMapper;
    
    @Autowired
    private TRmCalpointMapper tRmCalpointMapper;
    
    @Autowired
    private IFormulaService formulaService;

    @Override
    protected IBaseMapper<EmsCalpointValue, HashMap<String, Object>> getMapper() {
        return emsCalpointValueMapper;
    }

	@Override
	public void modifyOrInsert(EmsCalpointValue model) {
		HashMap<String, Object> id = new HashMap<String, Object>();
		id.put("clock", model.getClock());
		id.put("itemid", model.getItemid());
		// 
		if(emsCalpointValueMapper.selectByPrimaryKey(id)!=null){
			emsCalpointValueMapper.updateByPrimaryKeySelective(model);
		}else{
			emsCalpointValueMapper.insert(model);
		}
		// 自动新增第二天的数据、或者下月数据
		TRmCalpoint c = tRmCalpointMapper.selectByPrimaryKey(model.getItemid());
		Calendar cal = Calendar.getInstance();
		try {
			if(c.getMintimegranid().equalsIgnoreCase("DAY")){
				cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(model.getClock()));
				cal.add(Calendar.DAY_OF_YEAR, 1);
				id.put("clock", new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
			}else if(c.getMintimegranid().equalsIgnoreCase("MONTH")){
				cal.setTime(new SimpleDateFormat("yyyy-MM").parse(model.getClock()));
				cal.add(Calendar.MONTH, 1);
				id.put("clock", new SimpleDateFormat("yyyy-MM").format(cal.getTime()));
			}
		} catch (ParseException e) {
			e.printStackTrace();
			return;
		}
		EmsCalpointValue nx = emsCalpointValueMapper.selectByPrimaryKey(id);
		if(nx==null){
			nx = new EmsCalpointValue();
			nx.setClock(id.get("clock").toString());
			nx.setItemid(model.getItemid());
			nx.setOperDate(new Date());
			nx.setOperUser(JwtUtil.getUseridByToken());
			nx.setMintvalue(model.getMendvalue());
			emsCalpointValueMapper.insert(nx);
		}else{
			nx.setOperDate(new Date());
			nx.setOperUser(JwtUtil.getUseridByToken());
			nx.setMintvalue(model.getMendvalue());
			emsCalpointValueMapper.updateByPrimaryKeySelective(nx);
		}
		// 数据更新，计算计量点数据
		id.put("clock", model.getClock());
		id.put("timegranid", c.getMintimegranid());
		TRmCalpointValue t = tRmCalpointValueMapper.selectByPrimaryKey(id);
		if(t!=null && model.getApportvalue()!=null){
			t.setApportvalue(model.getApportvalue());
			t.setCorrectvalue(model.getApportvalue().subtract(t.getActualvalue()==null?BigDecimal.ZERO:t.getActualvalue()));
			if(model.getBz()!=null){
				t.setBz(model.getBz());
			}else{
				t.setBz("人工录入，自动修改");
			}
			t.setUpman(JwtUtil.getUseridByToken());
			t.setUptime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			tRmCalpointValueMapper.updateByPrimaryKeySelective(t);
			// 重新计算
			formulaService.reCalculate(t.getItemid(), t.getClock(), t.getTimegranid(), "");
		} else if(t==null){
			// 生成数据
			t = new TRmCalpointValue();
			t.setApportvalue(model.getApportvalue()); // 最终值
			t.setActualvalue(model.getApportvalue()); // 计算值
			t.setCorrectvalue(BigDecimal.ZERO); // 修正值
			t.setClock(model.getClock());
			t.setTimegranid(c.getMintimegranid());
			t.setItemid(model.getItemid());
			t.setItemname(tRmCalpointMapper.selectByPrimaryKey(model.getItemid()).getItemname());
			t.setCrman(JwtUtil.getUseridByToken());
			t.setRecTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			tRmCalpointValueMapper.insert(t);
		}
	}

	@Override
	public PageList<Map<String, Object>> getDateEditForPage(HashMap<String, Object> parmas, Integer pageNum,
			Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		Calendar cal = Calendar.getInstance();
    	cal.add(Calendar.HOUR_OF_DAY, 1);
    	cal.add(Calendar.DAY_OF_YEAR, -1);
    	String clock = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
    	parmas.put("clockt", clock); // 可以修改的clock
    	parmas.put("clocktm", clock.substring(0, 7)); // 可以修改的clock（月）
    	if(parmas.get("itemid")!=null && !parmas.get("itemid").toString().isEmpty()){
			String itemid = parmas.get("itemid").toString();
			itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
			parmas.put("itemid", itemid);
		}
    	List<Map<String, Object>> rows = emsCalpointValueMapper.getDateEdit(parmas);
        PageList<Map<String, Object>> pageInfo = new PageList<Map<String, Object>>(rows);
        return pageInfo;
	}
}
