/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-06-05
 * 描述            ：资材备件归集表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.BaseItemCmpMapper;
import market.Cm.mapper.BaseOrgCmpMapper;
import market.Cm.mapper.CostAcmMatMapper;
import market.Cm.service.CostAcmMatService;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.BaseItemCmp;
import market.Cm.vo.BaseOrgCmp;
import market.Cm.vo.CostAcmMat;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Equipment.mapper.YdmEquipmentOutlistMapper;
import market.Lms.Equipment.vo.YdmEquipmentOutlist;

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="CostAcmMatService")
public class CostAcmMatServiceImpl extends BaseServiceImpl<CostAcmMat,Object> implements CostAcmMatService {

	/**
	 * 资材备件归集查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCostAcmMat(CommonPage<CostAcmMat> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CostAcmMat cam = cp.getObject();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		int pageIndex=cp.getPageIndex();
		int pageSize=cp.getPageSize();
		PageModel<CostAcmMat> pm = new PageModel<CostAcmMat>(pageIndex,pageSize);
		try {
			String swhere = "";			
			if (cam.getMat_name()!=null && !"".equals(cam.getMat_name())) {
				swhere+=" and mat_name like '%"+cam.getMat_name()+"%'";//产品名称
			}
			if (cam.getSrot_name()!=null && !"".equals(cam.getSrot_name())) {
				swhere+=" and srot_name like '%"+cam.getSrot_name()+"%'";//产品分类名称
			}
			if (cam.getOrg_name()!=null && !"".equals(cam.getOrg_name())) {
				swhere+=" and org_name like '%"+cam.getOrg_name()+"%'";//成本组织
			}
			if (cam.getOrg_code()!=null && !"".equals(cam.getOrg_code())) {
				swhere+=" and org_code = '"+cam.getOrg_code()+"'";//成本组织
			}
			if (cam.getPrd_num()!=null && !"".equals(cam.getPrd_num())) {
				swhere+=" and prd_num like '%"+cam.getPrd_num()+"%'";//成本期间
			}
			if (startTime!=null && !"".equals(startTime)) {
				swhere += " and to_char(out_date, 'yyyy-mm-dd hh24:mi:ss') >='"
						+ startTime +" 00:00:00"+ "'";//出库时间起
			}
			if (endTime!=null && !"".equals(endTime)) {
				swhere += " and to_char(out_date, 'yyyy-mm-dd hh24:mi:ss') <='"
						+ endTime +" 23:59:59"+ "'";//出库时间止
			}			
			if (cam.getValid_flg()!=null && !"".equals(cam.getValid_flg())) {
				swhere+=" and valid_flg = '"+cam.getValid_flg()+"'"; //是否有效
			}
			if (cam.getAudit_flg()!=null && !"".equals(cam.getAudit_flg())) {
				swhere+=" and audit_flg = '"+cam.getAudit_flg()+"'"; //是否审核
			}
			pm.setRows(this.getMapper(CostAcmMatMapper.class).findWithCondition(null, swhere, "out_bill_no desc", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(CostAcmMatMapper.class).countWithCondition(null, swhere));
			rm.setData(pm);
			rm.setState("200");
			rm.setMsgInfo("查询成功");
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 资材备件归集：审核及反审
	 * @param cp object[out_bill_no出库单号]  memo1【0反审  1审核】
	 * @return
	 * @throws Exception
	 */
	public ResultModel doChangeCostAcmMatAuditFlg(CommonPage<CostAcmMat> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();
		CostAcmMat cam = cp.getObject();
		
		//通过成本期间和成本组织进行【审核】和【反审】
		CostAcmMat CAM = new CostAcmMat();
		CAM.setPrd_num(cam.getPrd_num());
		CAM.setAudit_flg("1".equals(opr)?"1":"0");//
		int count = this.getMapper(CostAcmMatMapper.class).count(CAM);
		if (count > 0) {
			throw new Exception("成本期间【"+cam.getPrd_num()+"】中存在"+("1".equals(opr)?"已审核":"未审核")+"的数据");
		}
		cam.setAudit_flg(opr);
		if ("1".equals(opr)) {//审核操作，传递审核人和审核时间			
			cam.setAudit_man(userName);
			cam.setAudit_time(now);
		}
		this.getMapper(CostAcmMatMapper.class).doChangeCostAcmMatAuditFlg(cam);	
		rm.setMsgInfo("成本期间【"+cam.getPrd_num()+"】"+("0".equals(cp.getMemo1())?"反审":"审核") + "操作成功");
		rm.setState("200");		
		return rm;
	}
	
	/**
	 * 资材备件归集
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertCostAcmMat(CommonPage<BaseFiscalPeriodD> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		BaseFiscalPeriodD bfpd = cp.getObject();
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(bfpd.getPrd_num());
		if (b==null) {
			throw new Exception("请传入成本会计期间");
		}
		
		Date now = new Date();
		SimpleDateFormat df0 = new SimpleDateFormat("yyyy-MM-dd");
		String startTime = df0.format(b.getStr_date());
		String endTime = df0.format(b.getEnd_date());
		//判断成本期间内是否已经进行了归集
		CostAcmMat CAM = new CostAcmMat();
		CAM.setPrd_num(bfpd.getPrd_num());//成本期间
		List<CostAcmMat> CAMList = this.getMapper(CostAcmMatMapper.class).find(CAM, 0, 0);
		if (CAMList!=null && CAMList.size()>0) {
			throw new Exception("当前成本期间【"+bfpd.getPrd_num()+"】已经进行资材备件归集");
		}
		
		//查找归集期间的资材备件的出库数据(YTDG的不需要进行归集，为二次入库)
		String condition = " and out_date >= '"+startTime+"' and out_date <= '"+endTime+"' and supplier_name <> 'YTGD'";
		List<YdmEquipmentOutlist> yeoList = this.getMapper(YdmEquipmentOutlistMapper.class).findWithCondition(null, condition, "out_bill_no desc", 0, 0);
		if (yeoList==null || yeoList.size()<=0) {
			throw new Exception("未找到资材备件库出库数据，无法进行归集");
		}
		
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		for (YdmEquipmentOutlist yeo : yeoList) {
			CostAcmMat cam = new CostAcmMat();
			cam.setOut_bill_no(yeo.getOut_bill_no());
			cam.setMat_code(yeo.getMat_code());			//产品编码
			cam.setMat_name(yeo.getMat_name());
			cam.setSrot_code(yeo.getSrot_code());		//产品分类
			cam.setSrot_name(yeo.getSrot_name());
			cam.setSpec(yeo.getSpec());					//规格
			cam.setMachine_code(yeo.getMachine_code());	//机台代码
			cam.setMachine_name(yeo.getMachine_name());
			cam.setQuantity_value(yeo.getQuantity());			//数量
			cam.setPrice_value(yeo.getPrice());				//单价
			cam.setAmount_value(yeo.getQuantity() * yeo.getPrice());//金额
			cam.setMsr_unit(yeo.getUnit());					//单位
			cam.setStorage_code(yeo.getStorage_code());	//仓库编码
			cam.setArea(yeo.getArea());					//区域
			cam.setOut_type(yeo.getOut_type());			//出库类型
			cam.setApply_dept(yeo.getApply_dept());		//申请单位
			//设置成本项目
			BaseItemCmp bic = new BaseItemCmp();
			bic.setCmp_code(cam.getMat_code());//项目匹配代码
			bic.setCmp_name(cam.getMat_name());//项目匹配名称
			List<BaseItemCmp> bciList = this.getMapper(BaseItemCmpMapper.class).find(bic, 0, 0);
			if (bciList!=null && bciList.size()>0) {
				bic = bciList.get(0);
				cam.setItem_code(bic.getItem_code());
				cam.setItem_name(bic.getItem_name());				
			}
			//设置成本组织
			BaseOrgCmp boc = new BaseOrgCmp();
			boc.setCmp_code(cam.getMachine_code());//组织对照编码
			//boc.setCmp_name(cam.getMachine_name());//组织对照名称
			List<BaseOrgCmp> bocList = this.getMapper(BaseOrgCmpMapper.class).find(boc, 0, 0);
			if (bocList!=null && bocList.size()>0) {
				cam.setOrg_code(bocList.get(0).getOrg_code());//成本组织代码
				cam.setOrg_name(bocList.get(0).getOrg_name());//成本组织名称				
			}
			cam.setPrd_num(bfpd.getPrd_num());
			cam.setOut_date(df.parse(yeo.getOut_date()));
			cam.setMemo(null);
			cam.setValid_flg("1");//有效
			cam.setAudit_flg("0");//未审核
			cam.setCreate_man(userName);
			cam.setCreate_time(now);
			this.getMapper(CostAcmMatMapper.class).insert(cam);
		}		
		rm.setState("200");
		rm.setMsgInfo("资材备件归集成功");
		return rm;
	}
	
	/**
	 * 删除期间内的资材备件归集
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCostAcmMat(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();//成本期间
		CostAcmMat CAM = new CostAcmMat();
		CAM.setPrd_num(prd_num);	//成本期间
		CAM.setAudit_flg("1");		//已经审核
		List<CostAcmMat> CAMList = this.getMapper(CostAcmMatMapper.class).find(CAM, 0, 0);
		if (CAMList!=null && CAMList.size()>0) {
			throw new Exception("当前成本期间【"+prd_num+"】已经存在已经审核归集信息,无法删除");
		}
		//删除成本期间内的信息
		this.getMapper(CostAcmMatMapper.class).deleteCostAcmMatByPrdnum(prd_num);		
		
		rm.setState("200");
		rm.setMsgInfo("资材备件归集信息删除成功");
		return rm;		
	}
	
}
