/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-06-12
 * 描述            ：修磨原值摊销表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl; 
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseCostItemMapper;
import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.BaseOrgCmpMapper;
import market.Cm.mapper.CmCostDstGrindMapper;
import market.Cm.service.CmCostDstGrindService;
import market.Cm.vo.BaseCostItem;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.BaseOrgCmp;
import market.Cm.vo.CmCostDstGrind;
import market.Com.mapper.ComBaseMachineMapper;
import market.Com.vo.ComBaseMachine;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Mes.Dev.mapper.DevBladeGrindingBldMapper;
import market.Mes.Dev.mapper.DevBladeGrpMapper;
import market.Mes.Dev.mapper.DevBladeInfoMapper;
import market.Mes.Dev.mapper.DevRollerInfoMapper;
import market.Mes.Dev.vo.DevBladeGrinding;
import market.Mes.Dev.vo.DevBladeGrindingBld;
import market.Mes.Dev.vo.DevBladeGrp;
import market.Mes.Dev.vo.DevBladeInfo;
import market.Mes.Dev.vo.DevRollerGrinding;
import market.Mes.Dev.vo.DevRollerInfo;

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="CmCostDstGrindService")
public class CmCostDstGrindServiceImpl extends BaseServiceImpl<CmCostDstGrind,Object> implements CmCostDstGrindService {
	
	
	/**
	 * 根据成本序号，查询开始时间，结束时间
	 * memo1:期间序号
	 * @param oci
	 * @return
	 */
	public ResultModel doQueryBaseFiscalPeriod(CommonPage<BaseFiscalPeriodD> oci){
		ResultModel rm=new ResultModel();
		try{			
			BaseFiscalPeriodD bfpd= this.getMapper(BaseFiscalPeriodDMapper.class).findById(oci.getMemo1());
			rm.setData(bfpd);
			rm.setState("200");
		}catch(Exception ex){
			ex.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo("查询失败!"+ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 刀片、轧辊归集查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCostAcmDst(CommonPage<CmCostDstGrind> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmCostDstGrind cap = cp.getObject();
//		String startTime = cp.getStartTime();
//		String endTime = cp.getEndTime();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<CmCostDstGrind> pm = new PageModel<CmCostDstGrind>(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(CmCostDstGrindMapper.class).findWithCondition(null, swhere, "machine_code,prd_num desc", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(CmCostDstGrindMapper.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 doInsertCostAcmDst(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("请传入成本会计期间");
			}
			//判断成本期间内是否已经进行了归集
			CmCostDstGrind CCAP = new CmCostDstGrind();
			CCAP.setPrd_num(bfpd.getPrd_num());//成本期间
			CCAP.setItem_name("刀片");
			int count = this.getMapper(CmCostDstGrindMapper.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());
			List<DevBladeGrinding> dbgList= this.getMapper(CmCostDstGrindMapper.class).doQueryWeb(startTime,endTime);
			for(DevBladeGrinding dbg:dbgList){
				CmCostDstGrind ccdg=new CmCostDstGrind();
				ccdg.setGrp_code(dbg.getGrp_code());
				ccdg.setGrp_name(dbg.getGrp_name());
				List<BaseOrgCmp> bocList = this.getMapper(BaseOrgCmpMapper.class).findWithCondition(null, "cmp_code='"+dbg.getMachine_code()+"'", null, 0, 0);
				if(bocList==null || bocList.size()<=0){
					throw new Exception("请维护刀片所属的成本组织");
				}
				List<BaseCostItem> boiList = this.getMapper(BaseCostItemMapper.class).findWithCondition(null, "item_name='刀片'", null, 0, 0);
				if(boiList==null || boiList.size()<=0){
					throw new Exception("请维护刀片所属的成本项目");
				}
				
				
				ccdg.setItem_code(boiList.get(0).getItem_code());//???
				ccdg.setItem_name(boiList.get(0).getItem_name());
				ccdg.setOrg_code(bocList.get(0).getOrg_code());//??
				ccdg.setOrg_name(bocList.get(0).getOrg_name());//??
				ccdg.setPrd_num(bfpd.getPrd_num());
				ccdg.setMachine_code(dbg.getMachine_code());
				ccdg.setGrd_thick_value(dbg.getGrd_thick());
				ccdg.setDia_outer_aft(dbg.getDia_outer_aft());
				ComBaseMachine cbm=this.getMapper(ComBaseMachineMapper.class).findById(dbg.getMachine_code());
				ccdg.setMachine_name(cbm.getMachine_name());
				
				List<DevBladeGrindingBld> dbgcList = this.getMapper(DevBladeGrindingBldMapper.class).findWithCondition(null, "serial_no='"+dbg.getSerial_no()+"'", "DSP_ORDER desc", 0, 0);
				if(dbgcList!=null && dbgcList.size()>0){
					ccdg.setDia_outer_org(dbgcList.get(0).getDia_outer_org());
					ccdg.setDia_outer_srp(dbgcList.get(0).getDia_outer_srp());
					ccdg.setDia_outer_bfr(dbgcList.get(0).getDia_outer_bfr());
					//ccdg.setDia_outer_aft(dbgcList.get(0).getDia_outer_aft());
					DevBladeInfo dbi = this.getMapper(DevBladeInfoMapper.class).findById(dbgcList.get(0).getBlade_no());
					if(dbi!=null){
						ccdg.setStd_thick_value(dbi.getDia_outer_org()-dbi.getDia_outer_srp());
						ccdg.setGrd_times_value(1l);
					}
					ccdg.setAmount_all_value(dbi.getAmount_money()*dbgcList.size());//分摊总金额？？？
					if(ccdg.getGrd_thick_value()!=null && ccdg.getStd_thick_value()!=null){
						ccdg.setRate_value(ccdg.getGrd_thick_value()/ccdg.getStd_thick_value());
						ccdg.setAmount_value(ccdg.getRate_value()*ccdg.getAmount_all_value());
					}
					
				}
				
				int grd_num = this.getMapper(DevBladeInfoMapper.class).countWithCondition(null, "grp_code='"+dbg.getGrp_code()+"'");
				ccdg.setGrd_num((long)grd_num);//修磨次数？？？
				
				ccdg.setMsr_unit("元");//单位？
				ccdg.setValid_flg("1");//默认有效
				//ccdg.setAudit_man(userName);
				ccdg.setCreate_man(userName);
				ccdg.setCreate_time(new Date());
				List<DevBladeGrp> list222 = this.getMapper(DevBladeGrpMapper.class).findWithCondition(null, "grp_code='"+dbg.getGrp_code()+"'", "", 0, 0);
				if(list222!=null && list222.size()>0){
					if(list222.get(0).getIs_stock()!=null){
						ccdg.setIs_stock(list222.get(0).getIs_stock());
					}else{
						ccdg.setIs_stock("1");
					}
				}else{
					ccdg.setIs_stock("1");
				}
				ccdg.setIs_dst("1");
				ccdg.setAudit_flg("0");//默认未审核
				//this.getMapper(CmCostDstGrindMapper.class).doDelete(ccdg.getOrg_code(),ccdg.getItem_code(),ccdg.getGrp_code(),ccdg.getMachine_code(),ccdg.getPrd_num());
				this.getMapper(CmCostDstGrindMapper.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 doInsertCostAcmRoller(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("请传入成本会计期间");
			}
			
			//判断成本期间内是否已经进行了归集
			CmCostDstGrind CCAP = new CmCostDstGrind();
			CCAP.setPrd_num(bfpd.getPrd_num());//成本期间
			CCAP.setItem_name("轧辊");
			int count = this.getMapper(CmCostDstGrindMapper.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());
			List<DevRollerGrinding> dbgList= this.getMapper(CmCostDstGrindMapper.class).doQueryWeb2(startTime,endTime);
			for(DevRollerGrinding dbg:dbgList){
				CmCostDstGrind ccdg=new CmCostDstGrind();
				ccdg.setGrp_code(dbg.getRoller_no());
				ccdg.setGrp_name(dbg.getRoller_no());
				List<BaseOrgCmp> bocList = this.getMapper(BaseOrgCmpMapper.class).findWithCondition(null, "cmp_code='"+dbg.getMachine_code()+"'", null, 0, 0);
				if(bocList==null || bocList.size()<=0){
					throw new Exception("请维护轧辊所属的成本组织");
				}
				List<BaseCostItem> boiList = this.getMapper(BaseCostItemMapper.class).findWithCondition(null, "item_name='轧辊'", null, 0, 0);
				if(boiList==null || boiList.size()<=0){
					throw new Exception("请维护轧辊所属的成本项目");
				}
				
				
				ccdg.setItem_code(boiList.get(0).getItem_code());//???
				ccdg.setItem_name(boiList.get(0).getItem_name());
				ccdg.setOrg_code(bocList.get(0).getOrg_code());//??
				ccdg.setOrg_name(bocList.get(0).getOrg_name());//??
				ccdg.setPrd_num(bfpd.getPrd_num());
				ccdg.setMachine_code(dbg.getMachine_code());
				ComBaseMachine cbm=this.getMapper(ComBaseMachineMapper.class).findById(dbg.getMachine_code());
				ccdg.setMachine_name(cbm.getMachine_name());
				DevRollerInfo dbi = this.getMapper(DevRollerInfoMapper.class).findById(dbg.getRoller_no());
				ccdg.setDia_outer_org(dbi.getDia_init());
				ccdg.setDia_outer_srp(dbi.getDia_scrap());
				ccdg.setDia_outer_bfr(dbg.getBfr_roller_dia());
				ccdg.setDia_outer_aft(dbg.getAft_roller_dia());
				ccdg.setGrd_thick_value(dbg.getBfr_roller_dia()-dbg.getAft_roller_dia());
				if(dbi!=null){
					ccdg.setStd_thick_value(dbi.getDia_init()-dbi.getDia_scrap());
					ccdg.setGrd_times_value(1l);
				}
				if(ccdg.getGrd_thick_value()!=null && ccdg.getStd_thick_value()!=null){
					ccdg.setRate_value(ccdg.getGrd_thick_value()/ccdg.getStd_thick_value());
					ccdg.setAmount_all_value(dbi.getAmount_money());//分摊总金额？？？
					ccdg.setAmount_value(ccdg.getRate_value()*ccdg.getAmount_all_value());
				}
				int grd_num = this.getMapper(DevRollerInfoMapper.class).countWithCondition(null, "roller_no='"+dbg.getRoller_no()+"'");
				ccdg.setGrd_num((long)grd_num);//修磨次数？？？
				ccdg.setGrd_thick_value(dbg.getGrd_thick());
				ccdg.setMsr_unit("元");//单位？
				ccdg.setValid_flg("1");//默认有效
				//ccdg.setAudit_man(userName);
				ccdg.setCreate_man(userName);
				ccdg.setCreate_time(new Date());
				if(dbi.getIs_stock()!=null){
					ccdg.setIs_stock(dbi.getIs_stock());
				}else{
					ccdg.setIs_stock("1");
				}
				
				ccdg.setIs_dst("1");
				ccdg.setAudit_flg("0");//默认未审核
				//this.getMapper(CmCostDstGrindMapper.class).doDelete(ccdg.getOrg_code(),ccdg.getItem_code(),ccdg.getGrp_code(),ccdg.getMachine_code(),ccdg.getPrd_num());
				this.getMapper(CmCostDstGrindMapper.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 doChangeCostAcmDstValidFlg(CommonPage<CmCostDstGrind> 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<CmCostDstGrind> capst = cp.getObjectList();
		for(CmCostDstGrind cap:capst){
			if (cap.getGrp_code()==null || "".equals(cap.getGrp_code())) {
				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(CmCostDstGrindMapper.class).update(cap);
		}
		
		rm.setState("200");
		rm.setMsgInfo(reslut + "操作成功");
		return rm;
	}
	
	
	/**
	 * 删除刀片轧辊归集信息
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCostAcmMat(CommonPage<CmCostDstGrind> cp) throws Exception{
		ResultModel rm = new ResultModel();
		CmCostDstGrind 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();//成本期间
		CmCostDstGrind CAP = new CmCostDstGrind();
		CAP.setPrd_num(prd_num);	//成本期间
		CAP.setAudit_flg("1");		//已经审核
		CAP.setItem_name(bfpd.getItem_name());
		List<CmCostDstGrind> CAMList = this.getMapper(CmCostDstGrindMapper.class).find(CAP, 0, 0);
		if (CAMList!=null && CAMList.size()>0) {
			throw new Exception("当前成本期间【"+prd_num+"】已经存在已经审核归集信息,无法删除");
		}
		//删除成本期间内的信息
		this.getMapper(CmCostDstGrindMapper.class).deleteCmCostDstGrindByPrdnum(prd_num,bfpd.getItem_name());		
		
		rm.setState("200");
		rm.setMsgInfo("归集信息删除成功");
		return rm;		
	}	
	
	
	
	
	
	
	
	
}
