/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-05-14
 * 描述            ：采购合同表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Pms.Order.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Order.mapper.PurOrderCMapper;
import market.Pms.Order.mapper.PurOrderClauseDMapper;
import market.Pms.Order.mapper.PurOrderClauseMapper;
import market.Pms.Order.mapper.PurOrderMMapper;
import market.Pms.Order.service.PurOrderMService;
import market.Pms.Order.vo.PurOrderC;
import market.Pms.Order.vo.PurOrderClause;
import market.Pms.Order.vo.PurOrderClauseD;
import market.Pms.Order.vo.PurOrderM;

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 = "PurOrderMService")
public class PurOrderMServiceImpl extends BaseServiceImpl<PurOrderM, Object>
		implements PurOrderMService {
	/**
	 * 合同头信息查询
	 * 
	 * @param oci
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<PurOrderM> oci) {
		ResultModel rm = new ResultModel();
		PageModel<PurOrderM> pm = new PageModel<PurOrderM>(oci.getPageIndex(),
				oci.getPageSize());
		PurOrderM queryCls = oci.getObject() == null ? (new PurOrderM()) : oci
				.getObject();
		String startTime = oci.getStartTime();
		String endTime = oci.getEndTime();

		try {
			pm.setTotal(this.getMapper(PurOrderMMapper.class).doQueryCount(
					queryCls, startTime, endTime));
			pm.setRows(this.getMapper(PurOrderMMapper.class).doQuery(queryCls,
					startTime, endTime,
					(oci.getPageIndex() - 1) * oci.getPageSize(),
					oci.getPageIndex() * oci.getPageSize()));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("错误：" + ex.getMessage());
		}
		return rm;
	}
	/**
	 * 结算单编制--合同头信息查询
	 * 
	 * @param oci
	 * @return
	 */
	public ResultModel doSettlementWeb(CommonPage<PurOrderM> oci) {
		ResultModel rm = new ResultModel();
		PurOrderM  pom=oci.getObject();
		String startTime = oci.getStartTime();
		try {
			String swhere="1=1 and VALIDFLAG='20'";
			if(pom.getSupp_name()!=null&&!"".equals(pom.getSupp_name())){
				swhere+=" and  supp_name  like  '%"+pom.getSupp_name()+"%'";
			}//供应商
			if(pom.getSupp_code()!=null&&!"".equals(pom.getSupp_code())){
				swhere+=" and  supp_code  like '%"+pom.getSupp_code()+"%'";
			}
			if(pom.getContract_no()!=null&&!"".equals(pom.getContract_no())){
				swhere+=" and  Contract_no  like '%"+pom.getContract_no()+"%'";
			}//合同号
			if (startTime!=null&&!"".equals(startTime)) {
				swhere+=" and to_char(create_time, 'yyyy-mm-dd hh24:mi:ss') >= '"+startTime+"' ";
			}
			List<PurOrderM>  list=this.getMapper(PurOrderMMapper.class).
					findWithCondition(null, swhere, "create_time desc ", 0, 0);
			rm.setData(list);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("错误：" + ex.getMessage());
		}
		return rm;
	}
	/**
	 * 合同抬头新增
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddWeb(CommonPage<PurOrderM> oci) {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		if (oci.getObjectList() == null || oci.getObjectList().size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("请传入需新增的数据！");
			return rm;
		}
		try {
			for (PurOrderM pom : oci.getObjectList()) {
				PurOrderM pomtest=this.getMapper(PurOrderMMapper.class).findPurByContractNo(pom.getSupp_contract_no());
				if(pomtest!=null&&!"".equals(pomtest)){
					rm.setState("500");
					rm.setMsgInfo("新增失败！当前条款" + pom.getSupp_contract_no()
							+ "已存在该合同！");
					return rm;
				}
				// 主键GUID生成
				pom.setContract_pk(UUID.randomUUID().toString());
				if(pom.getContract_no()==null||"".equals(pom.getContract_no())){
				pom.setContract_no(this.getMapper(PurOrderMMapper.class).getNo(
						"HT"
								+ new SimpleDateFormat("yyyyMM")
										.format(new Date())));
				}
				pom.setValidflag("10");// 默认10草稿
				pom.setStatus("00"); // 默认00代提报
				pom.setBal_year_month(new SimpleDateFormat("yyyyMM")
						.format(new Date()));
				pom.setStart_date(new Date()); // 开始日期
				pom.setCreate_userid(userId);
				pom.setCreate_name(userName);
				pom.setCreate_time(new Date());
				this.getMapper(PurOrderMMapper.class).insert(pom);
				String mode_code = pom.getMode_code();
				List<PurOrderClause> purOrederClauseList = this.getMapper(
						PurOrderClauseMapper.class).FindBYmodeCode(mode_code);
				PurOrderM order = this.getMapper(PurOrderMMapper.class)
						.findById(pom.getContract_pk());
				if (order != null) {
					for (PurOrderClause poc : purOrederClauseList) {
						PurOrderClauseD clause = new PurOrderClauseD();
						clause.setClause_code(poc.getClause_code());
						clause.setContract_pk(pom.getContract_pk());
						List<PurOrderClauseD> clauseList = this.getMapper(
								PurOrderClauseDMapper.class).find(clause, 0, 0);
						if (clauseList.size() > 0) {
							rm.setState("500");
							rm.setMsgInfo("新增失败！当前条款" + poc.getClause_code()
									+ "已存在该合同中！");
							return rm;
						}

						// 新增
						PurOrderClauseD pocd = new PurOrderClauseD();
						pocd.setClause_no(this.getMapper(
								PurOrderClauseDMapper.class).getNo(
								"TK"
										+ new SimpleDateFormat("yyyyMMdd")
												.format(new Date())));// TK+YYYYMMDD+3位流水
						pocd.setContract_pk(order.getContract_pk());
						pocd.setContract_no(order.getContract_no());
						pocd.setClause_code(poc.getClause_code());
						pocd.setClause_name(poc.getClause_name());
						pocd.setClause_desc(poc.getClause_desc());
						pocd.setClause_order_by(poc.getClause_order_by());
						pocd.setCreate_userid(userId);
						pocd.setCreate_name(userName);
						pocd.setCreate_time(new Date());
						this.getMapper(PurOrderClauseDMapper.class)
								.insert(pocd);
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo("新增失败！无效的合同数据");
					return rm;
				}
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("新增失败：" + ex.getMessage());
			return rm;
		}
		rm.setState("200");
		return rm;
	}

	/**
	 * 合同头操作（memo1:1：修改 2：删除 3：提报 4：撤销提报 5：归档）
	 * 
	 * @param oci
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doUpdateOrDeleteWeb(CommonPage<PurOrderM> oci) {
		ResultModel rm = new ResultModel();
		try {
			PurOrderM pom = oci.getObject();
			String memo1 = oci.getMemo1();
			if (pom != null && memo1 != null && !memo1.isEmpty()) {
				String contract_pk = pom.getContract_pk();
				if (contract_pk == null || contract_pk.isEmpty()) {
					rm.setState("500");
					rm.setMsgInfo("操作失败！当前数据无效！");
					return rm;
				}
				PurOrderM m = this.getMapper(PurOrderMMapper.class).findById(
						pom.getContract_pk());
				if (m != null) {
					if ("1".equals(memo1)) {
						// 修改传过来的前端数据
						rm = doUpdate(m, pom);
						return rm;
					} else if ("2".equals(memo1)) {
						rm = doDelete(m);
						return rm;
					} else if ("3".equals(memo1)) {
						rm = doReport(m);
						return rm;
					} else if ("4".equals(memo1)) {
						rm = doDisReport(m);
						return rm;
					} else if ("5".equals(memo1)) {
						rm = doFile(m);
						return rm;
					} else {
						rm.setState("500");
						rm.setMsgInfo("操作失败！无效的操作类型！");
						return rm;
					}
				} else {
					rm.setState("500");
					rm.setMsgInfo("操作失败！当前数据无效！");
					return rm;
				}
			} else {
				rm.setState("500");
				rm.setMsgInfo("操作失败！数据无效！");
				return rm;
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("操作失败：" + ex.getMessage());
			return rm;
		}
	}

	// 编辑
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdate(PurOrderM m, PurOrderM pom) throws Exception {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		if ("10".equals(m.getValidflag())&& ("00".equals(m.getStatus()) || "40".equals(m.getStatus()))) { // 合同状态草稿// 审批状态// 待申报
			try {
				  pom.setUpdate_userid(userId);
				  pom.setUpdate_name(userName);
				  pom.setUpdate_time(new Date());
				  this.getMapper(PurOrderMMapper.class).update(pom);
		        if(!m.getMode_code().equals(pom.getMode_code())){
		        	//根据合同主键 模板代号  同步删除此模板下合同款信息
		        	this.getMapper(PurOrderClauseDMapper.class).deleteOClause(m.getContract_pk(),m.getMode_code());
		        	//再新增 新模板下的  合同款信息
		        	String mode_code = pom.getMode_code();
					List<PurOrderClause> purOrederClauseList = this.getMapper(
							PurOrderClauseMapper.class).FindBYmodeCode(mode_code);
					PurOrderM order = this.getMapper(PurOrderMMapper.class)
							.findById(pom.getContract_pk());
					if (order != null) {
						for (PurOrderClause poc : purOrederClauseList) {
							PurOrderClauseD clause = new PurOrderClauseD();
							clause.setClause_code(poc.getClause_code());
							clause.setContract_pk(pom.getContract_pk());
							List<PurOrderClauseD> clauseList = this.getMapper(
									PurOrderClauseDMapper.class).find(clause, 0, 0);
							if (clauseList.size() > 0) {
								rm.setState("500");
								rm.setMsgInfo("操作失败！当前条款" + poc.getClause_code()
										+ "已存在该合同中！");
								return rm;
							}
							// 新增 合同条款
							PurOrderClauseD pocd = new PurOrderClauseD();
							pocd.setClause_no(this.getMapper(
									PurOrderClauseDMapper.class).getNo(
									"TK"
											+ new SimpleDateFormat("yyyyMMdd")
													.format(new Date())));// TK+YYYYMMDD+3位流水
							pocd.setContract_pk(order.getContract_pk());
							pocd.setContract_no(order.getContract_no());
							pocd.setClause_code(poc.getClause_code());
							pocd.setClause_name(poc.getClause_name());
							pocd.setClause_desc(poc.getClause_desc());
							pocd.setClause_order_by(poc.getClause_order_by());
							pocd.setCreate_userid(userId);
							pocd.setCreate_name(userName);
							pocd.setCreate_time(new Date());
							this.getMapper(PurOrderClauseDMapper.class)
									.insert(pocd);
							}
					}
		        }
			} catch (Exception e) {
				// TODO: handle exception
				rm.setState("500");
				rm.setMsgInfo("操作失败！请联系管理员！"+e.getMessage());
				throw e;
			}
		} else {
			rm.setState("500");
			rm.setMsgInfo("操作失败！当前数据不可编辑！");
			return rm;
		}
		rm.setState("200");
		return rm;
	}

	// 删除
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDelete(PurOrderM m) throws Exception {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		
		if ("10".equals(m.getValidflag())) { // 合同状态 草稿
			try {	
			// 修改主表
			m.setValidflag("00"); // 无效
			m.setDelete_userid(userId);
			m.setDelete_name(userName);
			m.setDelete_time(new Date());
			this.getMapper(PurOrderMMapper.class).update(m);
			// 修改从表
			PurOrderC poc = new PurOrderC();
			poc.setContract_no(m.getContract_no());
			List<PurOrderC> pocList = this.getMapper(PurOrderCMapper.class)
					.find(poc, 0, 0);
			if (pocList.size() > 0) {
				for (PurOrderC order : pocList) {
					order.setValidflag("00");
					order.setDelete_userid(userId);
					order.setDelete_name(userName);
					order.setDelete_time(new Date());
					this.getMapper(PurOrderCMapper.class).update(order);
				}
			}
			this.getMapper(PurOrderClauseDMapper.class).deleteOClause(m.getContract_pk(), null);//根据合同主键 同步删除合同款信息
			} catch (Exception e) {
				// TODO: handle exception
				rm.setState("500");
				rm.setMsgInfo("操作失败！请联系管理员！"+e.getMessage());
				throw e;
			}
		} else {
			rm.setState("500");
			rm.setMsgInfo("操作失败！当前数据不可删除！");
			return rm;
		}
		rm.setState("200");
		return rm;
	}

	// 提报
	public ResultModel doReport(PurOrderM m) throws Exception {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		if ("10".equals(m.getValidflag())
				&& ("00".equals(m.getStatus()) || "40".equals(m.getStatus()))) {
			// 主表
			m.setStatus("10"); // 暂时提报即审批通过并且生效
			m.setValidflag("20"); // 暂时生效
			m.setUpdate_userid(userId);
			m.setUpdate_name(userName);
			m.setUpdate_time(new Date());
			this.getMapper(PurOrderMMapper.class).update(m);
			// 从表
			/*PurOrderC poc = new PurOrderC();
			poc.setContract_no(m.getContract_no());
			List<PurOrderC> pocList = this.getMapper(PurOrderCMapper.class).find(poc, 0, 0);*/
			//无效的合同行不能做"提报"
			String strWhere = " and contract_no = '"+ m.getContract_no() +"' and validflag <> '00' ";
			List<PurOrderC> pocList = this.getMapper(PurOrderCMapper.class).findWithCondition(null, strWhere, null, 0, 0);
			if (pocList.size() > 0) {
				for (PurOrderC order : pocList) {
					order.setStatus("10"); // 暂时提报即审批通过并且生效
					order.setValidflag("20"); // 暂时生效
					order.setUpdate_userid(userId);
					order.setUpdate_name(userName);
					order.setUpdate_time(new Date());
					this.getMapper(PurOrderCMapper.class).update(order);
				}
			}
		} else {
			rm.setState("500");
			rm.setMsgInfo("操作失败！当前数据不可提报！");
			return rm;
		}
		rm.setState("200");
		return rm;
	}

	// 撤销提报
	public ResultModel doDisReport(PurOrderM m) throws Exception {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		if("20".equals(m.getValidflag()) && "10".equals(m.getStatus())){
		// 主表
		m.setStatus("00"); // 待提报
	    m.setValidflag("10");//草稿
		m.setUpdate_userid(userId);
		m.setUpdate_name(userName);
		m.setUpdate_time(new Date());
		this.getMapper(PurOrderMMapper.class).update(m);
		// 从表
		/*PurOrderC poc = new PurOrderC();
		poc.setContract_no(m.getContract_no());
		List<PurOrderC> pocList = this.getMapper(PurOrderCMapper.class).find(poc, 0, 0);*/
		//无效的合同行不能做“撤销提报”
		String strWhere = " and contract_no = '"+ m.getContract_no() +"' and validflag <> '00' ";
		List<PurOrderC> pocList = this.getMapper(PurOrderCMapper.class).findWithCondition(null, strWhere, null, 0, 0);
		if (pocList.size() > 0) {
			for (PurOrderC order : pocList) {
				order.setStatus("00"); // 待提报
				order.setValidflag("10");//草稿
				order.setUpdate_userid(userId);
				order.setUpdate_name(userName);
				order.setUpdate_time(new Date());
				this.getMapper(PurOrderCMapper.class).update(order);
			}
		}
		 }else{
		 rm.setState("500");
		 rm.setMsgInfo("操作失败！当前数据不可撤销提报！");
		 return rm;
		 }
		rm.setState("200");
		return rm;
	}

	// 归档
	public ResultModel doFile(PurOrderM m) throws Exception {
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		if (Integer.parseInt(m.getValidflag()) > 10
				&& m.getArchive_flag().equals("0")) {
			m.setArch_stamp_no(this.getMapper(PurOrderMMapper.class).getArchNo(
					"GD" + new SimpleDateFormat("yyyyMMdd").format(new Date()))); // GD+YYYYYMMDD+3位流水号
			m.setArchive_flag("1"); // 已归档
			m.setArch_date(new SimpleDateFormat("yyyyMM").format(new Date()));
			m.setUpdate_userid(userId);
			m.setUpdate_name(userName);
			m.setUpdate_time(new Date());
			this.getMapper(PurOrderMMapper.class).update(m);
		}
		rm.setState("200");
		return rm;
	}
}
