/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-06-17
 * 描述            ：能源介质归集表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.CmCostAcmWeMapper;
import market.Cm.service.CmCostAcmWeService;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.CmCostAcmWe;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Mes.util.DateUtil;
import market.tcp.mapper.TcpEleDstMapper;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="CmCostAcmWeService")
public class CmCostAcmWeServiceImpl extends BaseServiceImpl<CmCostAcmWe,Object> implements CmCostAcmWeService {
	
	
	
	/**
	 * 能源介质调整保存接口
	 * objectList:
	 * item_code
	 * prd_num
	 * org_code
	 * consume_value
	 * amount_value
	 * adjust_value
	 * adjust_reason
	 * 
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdate(CommonPage<CmCostAcmWe> cp) throws Exception{
		ResultModel rm = new ResultModel();
//		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		
		List<CmCostAcmWe> bfpdlist = cp.getObjectList();
		if(bfpdlist==null || bfpdlist.size()<=0){
			throw new Exception("请传入参数");
		}
		for(CmCostAcmWe bfpd:bfpdlist){
			if(bfpd.getAdjust_value()!=null && bfpd.getConsume_value()!=null){
				bfpd.setAmount_value(bfpd.getAdjust_value()+bfpd.getConsume_value());
			}
			try {			
				BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
				if (b==null) {
					throw new Exception("请传入成本会计期间");
				}
				this.getMapper(CmCostAcmWeMapper.class).update(bfpd);
			} catch (Exception e) {
				throw new Exception("能源介质调整失败"+e.getMessage());
			}
		}
		rm.setState("200");
		rm.setMsgInfo("能源介质调整成功");
		return rm;
	} 
	
	
	
	/**
	 * 能源介质归集查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCostAcmWe(CommonPage<CmCostAcmWe> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmCostAcmWe cap = cp.getObject();
//		String startTime = cp.getStartTime();
//		String endTime = cp.getEndTime();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<CmCostAcmWe> pm = new PageModel<CmCostAcmWe>(pageIndex,pageSize);
		try {
			String swhere = "";			
//			if (cap.getOrder_id()!=null && !"".equals(cap.getOrder_id())) {
//				swhere+=" and order_id like '%"+cap.getOrder_id()+"%'";//订单号
//			}
//			if (cap.getMat_coil_no()!=null && !"".equals(cap.getMat_coil_no())) {
//				swhere+=" and mat_coil_no like '%"+cap.getMat_coil_no()+"%'";//原料卷号
//			}
			if (cap.getOrg_name()!=null && !"".equals(cap.getOrg_name())) {
				swhere+=" and org_name like '%"+cap.getOrg_name()+"%'";//成本组织
			}
			if (cap.getItem_name()!=null && !"".equals(cap.getItem_name())) {
				swhere+=" and item_name like '%"+cap.getItem_name()+"%'";//成本组织
			}
			if (cap.getPrd_num()!=null && !"".equals(cap.getPrd_num())) {
				swhere+=" and prd_num like '%"+cap.getPrd_num()+"%'";//成本期间
			}
//			if (startTime!=null && !"".equals(startTime)) {
//				swhere += " and to_char(prod_time, 'yyyy-mm-dd hh24:mi:ss') >='"
//						+ startTime +" 00:00:00"+ "'";//生产时间起
//			}
//			if (endTime!=null && !"".equals(endTime)) {
//				swhere += " and to_char(prod_time, 'yyyy-mm-dd hh24:mi:ss') <='"
//						+ endTime +" 23:59:59"+ "'";//生产时间止
//			}
			if ("1".equals(cap.getAudit_flg())) {
				swhere+=" and audit_flg = '1'"; //是否有效
			}
			pm.setRows(this.getMapper(CmCostAcmWeMapper.class).findWithCondition(null, swhere, "prd_num desc", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(CmCostAcmWeMapper.class).countWithCondition(null, swhere));			
			rm.setState("200");
			rm.setData(pm);
		} catch (Exception e) { 
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	
	/**
	 * 能源介质归集
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertCostAcmWe(CommonPage<BaseFiscalPeriodD> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		BaseFiscalPeriodD bfpd = cp.getObject();
		try {			
			BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
			if (b==null) {
				throw new Exception("请传入成本会计期间");
			}
			//判断成本期间内是否已经进行了归集
			CmCostAcmWe CCAP = new CmCostAcmWe();
			CCAP.setPrd_num(bfpd.getPrd_num());//成本期间
			int count = this.getMapper(CmCostAcmWeMapper.class).count(CCAP);
			if (count > 0) {
				throw new Exception("当前成本期间【"+bfpd.getPrd_num()+"】已经进行能源介质归集");
			}
			
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			String startTime = df.format(b.getStr_date());
			String endTime = df.format(b.getEnd_date());
			String year = bfpd.getPrd_num().substring(0, 4);
			String month= bfpd.getPrd_num().substring(4, 6);
			int monthLastDay = DateUtil.getMonthLastDay(Integer.parseInt(year), Integer.parseInt(month));
			if(monthLastDay==31){
				String str=bfpd.getPrd_num()+"25";
				Calendar calendar = Calendar.getInstance();
				 try{
			             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");   //日期格式化
			             Date date = sdf.parse(str);
			             calendar.setTime(date);
			             //calendar.add(calendar.DAY_OF_YEAR, -1);
			             //Date enddate = calendar.getTime();
			             //System.out.println(enddate.toString());
			             calendar.setTime(date);
			             calendar.add(calendar.MONTH, -1);    //得到当前日期减一个月的时间点
			             //Date begindate = calendar.getTime();
			             int monthLastDaysahng = DateUtil.getMonthLastDay(Integer.parseInt(sdf.format(calendar.getTime()).substring(0, 4)),
			            		 Integer.parseInt(sdf.format(calendar.getTime()).substring(4, 6)));
			             if(monthLastDaysahng==31){
			            	 startTime= df.format(calendar.getTime()).substring(0, 4)+"-"+df.format(calendar.getTime()).substring(5, 7)
			            			 +"-25 09:00:00";
			             }else{
			            	 startTime= df.format(calendar.getTime()).substring(0, 4)+"-"+df.format(calendar.getTime()).substring(5, 7)
			            			 +"-24 09:00:00";
			             }
			             endTime=year+"-"+month+"-25 09:00:00";
			             
			         } catch (Exception e) {
			             throw new Exception("时间出错!");
			        } 
				 
			}else{
				String str=bfpd.getPrd_num()+"24";
				Calendar calendar = Calendar.getInstance();
				 try{
			             SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");   //日期格式化
			             Date date = sdf.parse(str);
			             calendar.setTime(date);
			             //calendar.add(calendar.DAY_OF_YEAR, -1);
			             //Date enddate = calendar.getTime();
			             //System.out.println(enddate.toString());
			             calendar.setTime(date);
			             calendar.add(calendar.MONTH, -1);    //得到当前日期减一个月的时间点
			             //Date begindate = calendar.getTime();
			             int monthLastDaysahng = DateUtil.getMonthLastDay(Integer.parseInt(sdf.format(calendar.getTime()).substring(0, 4)),
			            		 Integer.parseInt(sdf.format(calendar.getTime()).substring(4, 6)));
			             if(monthLastDaysahng==31){
			            	 startTime= df.format(calendar.getTime()).substring(0, 4)+"-"+df.format(calendar.getTime()).substring(5, 7)
			            			 +"-25 09:00:00";
			             }else{
			            	 startTime= df.format(calendar.getTime()).substring(0, 4)+"-"+df.format(calendar.getTime()).substring(5, 7)
			            			 +"-24 09:00:00";
			             }
			             endTime=year+"-"+month+"-24 09:00:00";
			             
			         } catch (Exception e) {
			             throw new Exception("时间出错!");
			        } 
				 
			}
			List<CmCostAcmWe> cawList = this.getMapper(TcpEleDstMapper.class).doQueryEleByMeterno2(startTime, endTime);
			if (CollectionUtils.isNotEmpty(cawList)) {
				for (CmCostAcmWe caw : cawList) {
					CmCostAcmWe ccaw=new CmCostAcmWe();
					ccaw.setItem_code("CT01010301");
					ccaw.setItem_name("电");
					ccaw.setOrg_code(caw.getOrg_code());
					ccaw.setOrg_name(caw.getOrg_name());
					ccaw.setPrd_num(bfpd.getPrd_num());
					ccaw.setConsume_value(caw.getAmount_value());
					ccaw.setAmount_value(caw.getAmount_value());
					ccaw.setMsr_unit("kwh");
					ccaw.setValid_flg("1");
					ccaw.setAudit_flg("0");
					ccaw.setCreate_man(userName);
					ccaw.setCreate_time(now);
					this.getMapper(CmCostAcmWeMapper.class).insert(ccaw);
				}
			}
			//针对平整的特殊处理
			CmCostAcmWe pzCaw = this.getMapper(CmCostAcmWeMapper.class).findById("CT01010301",bfpd.getPrd_num(),"C012");
			CmCostAcmWe CdCaw = this.getMapper(CmCostAcmWeMapper.class).findById("CT01010301",bfpd.getPrd_num(),"C023");
			if (pzCaw!=null && pzCaw.getAmount_value()!=null) {
				if (CdCaw!=null && CdCaw.getAmount_value()!=null) {
					pzCaw.setAmount_value(pzCaw.getAmount_value() - CdCaw.getAmount_value());
					pzCaw.setConsume_value(pzCaw.getAmount_value() - CdCaw.getAmount_value());
					this.getMapper(CmCostAcmWeMapper.class).update(pzCaw);
				}
			}
			
			/*List<TcpElectricitrcollect> tetcList = this.getMapper(TcpElectricitrcollectMapper.class).doQueryWeb5(startTime,endTime);
			for(TcpElectricitrcollect dbg:tetcList){
				if(dbg.getMch_code()==null || (dbg.getMch_code().contains("M") && dbg.getMch_code().length()==6)){
					continue;
				}
				CmCostAcmWe ccdg=new CmCostAcmWe();
				List<CmBaseEnergyOrgCmp> bocList = this.getMapper(CmBaseEnergyOrgCmpMapper.class).findWithCondition(null, "mch_code='"+dbg.getMch_code()+"'", null, 0, 0);
				if(bocList==null || bocList.size()<=0){
					throw new Exception("请维护电耗所属的成本组织");
				}
				List<BaseCostOrg> bocList1 = this.getMapper(BaseCostOrgMapper.class).findWithCondition(null, "org_code='"+bocList.get(0).getOrg_code()+"'", null, 0, 0);
				if(bocList1==null || bocList1.size()<=0){
					throw new Exception("请维护电耗所属的成本组织");
				}
				List<BaseCostItem> boiList2 = this.getMapper(BaseCostItemMapper.class).findWithCondition(null,"item_code='"+bocList.get(0).getItem_code()+"'", null, 0, 0);
				if(boiList2==null || boiList2.size()<=0){
					throw new Exception("请维护电耗所属的成本项目");
				}
				
				ccdg.setItem_code(bocList.get(0).getItem_code());//???
				
				ccdg.setItem_name(boiList2.get(0).getItem_name());
				
				ccdg.setOrg_code(bocList.get(0).getOrg_code());//??
				ccdg.setOrg_name(bocList1.get(0).getOrg_name());//??
				ccdg.setPrd_num(bfpd.getPrd_num());
				ccdg.setConsume_value(Double.valueOf(dbg.getMonth_kvarh_all()));
				ccdg.setAmount_value(Double.valueOf(dbg.getMonth_kvarh_all()));
				ccdg.setAdjust_value(0d);
				ccdg.setMsr_unit("kwh");//单位？
				ccdg.setValid_flg("1");//默认有效
				ccdg.setAdjust_value(0d);
				//ccdg.setAudit_man(userName);
				ccdg.setCreate_man(userName);
				ccdg.setCreate_time(new Date());
				ccdg.setAudit_flg("0");//默认未审核
				this.getMapper(CmCostAcmWeMapper.class).doDelete(ccdg.getItem_code(),ccdg.getOrg_code(),ccdg.getPrd_num());
				this.getMapper(CmCostAcmWeMapper.class).insert(ccdg);
			}*/
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		rm.setState("200");
		rm.setMsgInfo("电耗归集成功");
		return rm;
	} 
	
	/**
	 * 产量归集：审核及反审
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doChangeCmCostAcmWeValidFlg(CommonPage<CmCostAcmWe> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();
		String reslut = null;
		List<CmCostAcmWe> capst = cp.getObjectList();
		for(CmCostAcmWe cap:capst){
			if (cap.getItem_code()==null || "".equals(cap.getItem_code())) {
				throw new Exception("请传入成本项目代码");
			}
			if (cap.getPrd_num()==null || "".equals(cap.getPrd_num())) {
				throw new Exception("请传入成本期间");
			}
			cap.setAudit_man(userName);//审核人
			cap.setAudit_time(new Date());//审核时间
			if ("1".equals(opr)) {//启用
				cap.setAudit_flg("1");
				cap.setAudit_man(userName);//审核人
				cap.setAudit_time(new Date());//审核时间
				reslut = "审核";
			}else if ("0".equals(opr)) { //禁用
				cap.setAudit_flg("0");
				cap.setAudit_man(userName);//审核人
				cap.setAudit_time(new Date());//审核时间
				reslut = "反审";
			}
			this.getMapper(CmCostAcmWeMapper.class).update(cap);
		}
		
		rm.setState("200");
		rm.setMsgInfo(reslut + "操作成功");
		return rm;
	}
	
	/**
	 * 删除能耗归集信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCmCostAcmWe(CommonPage<BaseFiscalPeriodD> cp) throws Exception{
		ResultModel rm = new ResultModel();
		BaseFiscalPeriodD bfpd = cp.getObject();
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
		if (b==null) {
			throw new Exception("请传入成本期间");
		}		
		//判断成本期间内是否已经进行了归集
		String prd_num = bfpd.getPrd_num();//成本期间
		CmCostAcmWe CAP = new CmCostAcmWe();
		CAP.setPrd_num(prd_num);	//成本期间
		CAP.setAudit_flg("1");		//已经审核
		List<CmCostAcmWe> CAMList = this.getMapper(CmCostAcmWeMapper.class).find(CAP, 0, 0);
		if (CAMList!=null && CAMList.size()>0) {
			throw new Exception("当前成本期间【"+prd_num+"】已经存在已经审核归集信息,无法删除");
		}
		//删除成本期间内的信息
		this.getMapper(CmCostAcmWeMapper.class).deleteCmCostAcmWeByPrdnum(prd_num);		
		
		rm.setState("200");
		rm.setMsgInfo("能耗归集信息删除成功");
		return rm;		
	}	
	
	
}
