/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-07-04
 * 描述            ：工模辅具价值表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseCostItemMapper;
import market.Cm.mapper.BaseCostOrgMapper;
import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.CmCostDstGrindMapper;
import market.Cm.mapper.CmReportAssShareMapper;
import market.Cm.service.CmReportAssShareService;
import market.Cm.vo.BaseCostItem;
import market.Cm.vo.BaseCostOrg;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.CmCostDstGrind;
import market.Cm.vo.CmReportAssShare;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;

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="CmReportAssShareService")
public class CmReportAssShareServiceImpl extends BaseServiceImpl<CmReportAssShare,Object> implements CmReportAssShareService {
	
	/**
	 * 工模辅具价值管理查询
	 * object:
	 * prd_num
	 * item_name   （item_name="刀片"/item_name="轧辊"）
	 * audit_flg审核标志
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCostShare(CommonPage<CmReportAssShare> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmReportAssShare cap = cp.getObject();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<CmReportAssShare> pm = new PageModel<CmReportAssShare>(pageIndex,pageSize);
		try {
			String swhere = "";			
			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 ("1".equals(cap.getAudit_flg())) {
				swhere+=" and audit_flg = '1'"; //是否有效
			}
			pm.setRows(this.getMapper(CmReportAssShareMapper.class).findWithCondition(null, swhere, "org_code,prd_num desc", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(CmReportAssShareMapper.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 doInsertCostShare1(CommonPage<BaseFiscalPeriodD> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		BaseFiscalPeriodD bfpd = cp.getObject();
		try {			
			BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
			if (b==null) {
				throw new Exception("请传入成本会计期间");
			}
			//判断当前成本期间是否核算
			CmReportAssShare RPC = new CmReportAssShare();
			RPC.setPrd_num(bfpd.getPrd_num());
			RPC.setItem_name("刀片");
			int count = this.getMapper(CmReportAssShareMapper.class).count(RPC);
			if (count > 0) {
				throw new Exception("成本期间【"+bfpd.getPrd_num()+"】的刀片核算表已经存在数据");
			}
			//根据成本组织,查询【资材备件归集表】
			CmCostDstGrind cam = new CmCostDstGrind();
			cam.setPrd_num(bfpd.getPrd_num());
			cam.setValid_flg("1");
			cam.setAudit_flg("1");		
			cam.setItem_name("刀片");
			List<CmCostDstGrind> bciList = this.getMapper(CmCostDstGrindMapper.class).find(cam,0,0);		
			if (bciList==null || bciList.size()<=0) {
				throw new Exception("未找到成本期间【"+bfpd.getPrd_num()+"】的已审核的刀片归集数据");
			}
			
			
			//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			List<BaseCostOrg> bcoList = this.getMapper(BaseCostOrgMapper.class).findWithCondition(null, "1=1 and org_name like '%纵剪%' ", "org_code", 0, 0);
			for(BaseCostOrg bco:bcoList){
				CmReportAssShare cras=new CmReportAssShare();
				cras.setAudit_flg("0");
				//cras.setAudit_man();
				//cras.setAudit_time();
				cras.setCreate_man(userName);
				cras.setCreate_time(new Date());
				List<BaseCostItem> boiList = this.getMapper(BaseCostItemMapper.class).findWithCondition(null, 
						"item_name='刀片'", null, 0, 0);
				if(boiList==null || boiList.size()<=0){
					throw new Exception("请维护刀片所属的成本项目");
				}
				
				cras.setItem_code(boiList.get(0).getItem_code());//???
				cras.setItem_name(boiList.get(0).getItem_name());
				cras.setMemo("");
				cras.setOrg_code(bco.getOrg_code());
				cras.setOrg_name(bco.getOrg_name());
				cras.setPrd_num(bfpd.getPrd_num());
				
//				cras.setEnd_original_value(end_original_value);//累计原值
//				cras.setEnd_share_value(end_share_value);//累计摊销
//				cras.setEnd_value(end_value);//净值
//				cras.setInput_original_value(input_original_value);//本期原值
//				cras.setInput_share_value(input_share_value);//本期摊销
//				
//				cras.setShare_id(share_id);//摊销ID
//				cras.setStart_original_value(start_original_value);//上期原值
//				cras.setStart_share_value(start_share_value);//上期摊销
				cras.setValid_flg("1");//
				//原值计算：
				//期初原值：
				/*
				 *  1、	原值=上期累计原值+本期领用出库原值								
					2、	上期累计原值=期初原值+自本财年1月份起，各期领用刀片/轧辊原值之和								
					3、	期初原值为上一财年转入的以经领用刀片/轧辊原值之和								
					4、	净值=原值-上期累计摊销金额-本期摊销金额								
					5、	本期累计摊销金额=上期累计摊销金额+本期摊销金额								
				 */
				String year=bfpd.getPrd_num().substring(0, 4);
				Integer year_qinian=Integer.parseInt(year)-1;
				Integer month=Integer.parseInt(bfpd.getPrd_num().substring(4, 6));
				if(month.intValue()!=1){
					month--;
				}
				Double 期初原值=0d;
				期初原值=this.getMapper(CmReportAssShareMapper.class).doSumYuan(year_qinian+"",bco.getOrg_code(),cras.getItem_name());
				Double 上期累计原值=null;
				//上期累计摊销金额
				Double lastTanMoney=null;
				CmReportAssShare crass=new CmReportAssShare();
				crass.setOrg_code(bco.getOrg_code());
				crass.setItem_name(cras.getItem_name());
				crass.setPrd_num(year+lpad(month+"", 2, "0"));
				List<CmReportAssShare> last_monthleo=this.getMapper(CmReportAssShareMapper.class).find(crass, 0, 0);
				if(last_monthleo!=null && last_monthleo.size()>0){
					上期累计原值=last_monthleo.get(0).getEnd_original_value();
					//上期累计摊销金额
					lastTanMoney=last_monthleo.get(0).getEnd_share_value();
				}else{
					上期累计原值=期初原值+this.getMapper(CmReportAssShareMapper.class).doSumTan1(year+"01",year+lpad(month+"", 2, "0"),bco.getOrg_code(),cras.getItem_name());
					//上期累计摊销金额
					lastTanMoney=this.getMapper(CmCostDstGrindMapper.class).doSumTan(year+"01",year+lpad(month+"", 2, "0"),bco.getOrg_code());
				}
				
				Double 原值=null;
				//本期领用出库原值		
				Double 本期领用出库原值=this.getMapper(CmReportAssShareMapper.class).doSumTan1(bfpd.getPrd_num(),bfpd.getPrd_num(),bco.getOrg_code(),cras.getItem_name());
				原值=本期领用出库原值;
				Double 累计原值=null;
				累计原值=上期累计原值+本期领用出库原值;
				
				
				//本期摊销金额
				Double TanMoney=this.getMapper(CmCostDstGrindMapper.class).doSumTan(bfpd.getPrd_num(),bfpd.getPrd_num(),bco.getOrg_code());
				//上期摊销金额
				//Double lastMone=this.getMapper(CmCostDstGrindMapper.class).doSumTan(year+lpad(month+"", 2, "0"),year+lpad(month+"", 2, "0"),bco.getOrg_code());
				
				cras.setEnd_original_value(累计原值);//累计原值
				cras.setEnd_share_value(lastTanMoney+TanMoney);//累计摊销
				cras.setEnd_value(累计原值-lastTanMoney-TanMoney);//净值
				cras.setInput_original_value(原值);//本期原值
				cras.setInput_share_value(TanMoney);//本期摊销
				
				//cras.setShare_id(share_id);//摊销ID
				cras.setStart_original_value(上期累计原值);//上期原值
				cras.setStart_share_value(lastTanMoney);//上期摊销
				
				
				this.getMapper(CmReportAssShareMapper.class).doDelete(cras.getItem_code(),cras.getOrg_code(),cras.getPrd_num());
				this.getMapper(CmReportAssShareMapper.class).insert(cras);
			}
			
		} 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 doInsertCostShare2(CommonPage<BaseFiscalPeriodD> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		BaseFiscalPeriodD bfpd = cp.getObject();
		try {			
			BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
			if (b==null) {
				throw new Exception("请传入成本会计期间");
			}
			//判断当前成本期间是否核算
			CmReportAssShare RPC = new CmReportAssShare();
			RPC.setPrd_num(bfpd.getPrd_num());
			RPC.setItem_name("轧辊");
			int count = this.getMapper(CmReportAssShareMapper.class).count(RPC);
			if (count > 0) {
				throw new Exception("成本期间【"+bfpd.getPrd_num()+"】的轧辊核算表已经存在数据");
			}
			//根据成本组织,查询【资材备件归集表】
			CmCostDstGrind cam = new CmCostDstGrind();
			cam.setPrd_num(bfpd.getPrd_num());
			cam.setValid_flg("1");
			cam.setAudit_flg("1");		
			cam.setItem_name("轧辊");
			List<CmCostDstGrind> bciList = this.getMapper(CmCostDstGrindMapper.class).find(cam,0,0);		
			if (bciList==null || bciList.size()<=0) {
				throw new Exception("未找到成本期间【"+bfpd.getPrd_num()+"】的已审核的轧辊归集数据");
			}
			
			
			
			//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			List<BaseCostOrg> bcoList = this.getMapper(BaseCostOrgMapper.class).findWithCondition(null, "1=1 and (org_name like '%平整%' or org_name like '%轧机%'  ) ", "org_code", 0, 0);
			for(BaseCostOrg bco:bcoList){
				CmReportAssShare cras=new CmReportAssShare();
				cras.setAudit_flg("0");
				//cras.setAudit_man();
				//cras.setAudit_time();
				cras.setCreate_man(userName);
				cras.setCreate_time(new Date());
				List<BaseCostItem> boiList = this.getMapper(BaseCostItemMapper.class).findWithCondition(null, 
						"item_name='轧辊'", null, 0, 0);
				if(boiList==null || boiList.size()<=0){
					throw new Exception("请维护轧辊所属的成本项目");
				}
				
				cras.setItem_code(boiList.get(0).getItem_code());//???
				cras.setItem_name(boiList.get(0).getItem_name());
				cras.setMemo("");
				cras.setOrg_code(bco.getOrg_code());
				cras.setOrg_name(bco.getOrg_name());
				cras.setPrd_num(bfpd.getPrd_num());
				
//				cras.setEnd_original_value(end_original_value);//累计原值
//				cras.setEnd_share_value(end_share_value);//累计摊销
//				cras.setEnd_value(end_value);//净值
//				cras.setInput_original_value(input_original_value);//本期原值
//				cras.setInput_share_value(input_share_value);//本期摊销
//				
//				cras.setShare_id(share_id);//摊销ID
//				cras.setStart_original_value(start_original_value);//上期原值
//				cras.setStart_share_value(start_share_value);//上期摊销
				cras.setValid_flg("1");//
				//原值计算：
				//期初原值：
				/*
				 *  1、	原值=上期累计原值+本期领用出库原值								
					2、	上期累计原值=期初原值+自本财年1月份起，各期领用刀片/轧辊原值之和								
					3、	期初原值为上一财年转入的以经领用刀片/轧辊原值之和								
					4、	净值=原值-上期累计摊销金额-本期摊销金额								
					5、	本期累计摊销金额=上期累计摊销金额+本期摊销金额								
				 */
				String year=bfpd.getPrd_num().substring(0, 4);
				Integer year_qinian=Integer.parseInt(year)-1;
				Integer month=Integer.parseInt(bfpd.getPrd_num().substring(4, 6));
				if(month.intValue()!=1){
					month--;
				}
				Double 期初原值=0d;
				期初原值=this.getMapper(CmReportAssShareMapper.class).doSumYuan(year_qinian+"",bco.getOrg_code(),cras.getItem_name());
				Double 上期累计原值=null;
				//上期累计摊销金额
				Double lastTanMoney=null;
				CmReportAssShare crass=new CmReportAssShare();
				crass.setOrg_code(bco.getOrg_code());
				crass.setItem_name(cras.getItem_name());
				crass.setPrd_num(year+lpad(month+"", 2, "0"));
				List<CmReportAssShare> last_monthleo=this.getMapper(CmReportAssShareMapper.class).find(crass, 0, 0);
				if(last_monthleo!=null && last_monthleo.size()>0){
					上期累计原值=last_monthleo.get(0).getEnd_original_value();
					//上期累计摊销金额
					lastTanMoney=last_monthleo.get(0).getEnd_share_value();
				}else{
					上期累计原值=期初原值+this.getMapper(CmReportAssShareMapper.class).doSumTan1(year+"01",year+lpad(month+"", 2, "0"),bco.getOrg_code(),cras.getItem_name());
					//上期累计摊销金额
					lastTanMoney=this.getMapper(CmCostDstGrindMapper.class).doSumTan(year+"01",year+lpad(month+"", 2, "0"),bco.getOrg_code());
				}
				
				Double 原值=null;
				//本期领用出库原值		
				Double 本期领用出库原值=this.getMapper(CmReportAssShareMapper.class).doSumTan1(bfpd.getPrd_num(),bfpd.getPrd_num(),bco.getOrg_code(),cras.getItem_name());
				原值=本期领用出库原值;
				Double 累计原值=null;
				累计原值=上期累计原值+本期领用出库原值;
				
				
				//本期摊销金额
				Double TanMoney=this.getMapper(CmCostDstGrindMapper.class).doSumTan(bfpd.getPrd_num(),bfpd.getPrd_num(),bco.getOrg_code());
				//上期摊销金额
				//Double lastMone=this.getMapper(CmCostDstGrindMapper.class).doSumTan(year+lpad(month+"", 2, "0"),year+lpad(month+"", 2, "0"),bco.getOrg_code());
				
				cras.setEnd_original_value(累计原值);//累计原值
				cras.setEnd_share_value(lastTanMoney+TanMoney);//累计摊销
				cras.setEnd_value(累计原值-lastTanMoney-TanMoney);//净值
				cras.setInput_original_value(原值);//本期原值
				cras.setInput_share_value(TanMoney);//本期摊销
				
				//cras.setShare_id(share_id);//摊销ID
				cras.setStart_original_value(上期累计原值);//上期原值
				cras.setStart_share_value(lastTanMoney);//上期摊销
				
				
				this.getMapper(CmReportAssShareMapper.class).doDelete(cras.getItem_code(),cras.getOrg_code(),cras.getPrd_num());
				this.getMapper(CmReportAssShareMapper.class).insert(cras);
			}
			
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		rm.setState("200");
		rm.setMsgInfo("轧辊核算成功");
		return rm;
	}
	
	
	/**
	 * 工模辅具：审核及反审
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeCostShareValidFlg(CommonPage<CmReportAssShare> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();
		String reslut = null;
		CmReportAssShare cap = cp.getObject();
//		if (cap.getShare_id()==null || "".equals(cap.getShare_id())) {
//			throw new Exception("请传入ID");
//		}
		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(CmReportAssShareMapper.class).update(cap);
		rm.setState("200");
		rm.setMsgInfo(reslut + "操作成功");
		return rm;
	}
	
	/**
	 * 删除工模辅具信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCmReportAssShare(CommonPage<CmReportAssShare> cp) throws Exception{
		ResultModel rm = new ResultModel();
		CmReportAssShare 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();//成本期间
		CmReportAssShare CAP = new CmReportAssShare();
		CAP.setPrd_num(prd_num);	//成本期间
		CAP.setAudit_flg("1");		//已经审核
		CAP.setItem_name(bfpd.getItem_name());
		List<CmReportAssShare> CAMList = this.getMapper(CmReportAssShareMapper.class).find(CAP, 0, 0);
		if (CAMList!=null && CAMList.size()>0) {
			throw new Exception("当前成本期间【"+prd_num+"】已经存在已经审核核算信息,无法删除");
		}
		//删除成本期间内的信息
		this.getMapper(CmReportAssShareMapper.class).deleteCmReportAssShareByPrdnum(prd_num,bfpd.getItem_name());		
		
		rm.setState("200");
		rm.setMsgInfo("工模辅具信息撤销核算成功");
		return rm;		
	}
	
	// 补零
		public static String lpad(String str, int num, String pad) {
			String n_str = str;
			if (str == null && "".equals(str))
				n_str = " ";
			for (int i = str.length(); i < num; i++) {
				n_str = pad + n_str;
			}
			return n_str;
		}
	
}
