/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-07-07
 * 描述            ：免检产品配置表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Qms.qcm.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Qms.common.DataHelper;
import market.Qms.metallurgy.vo.ComMscStdPhy;
import market.Qms.qcm.mapper.ComMscExemptionMapper;
import market.Qms.qcm.mapper.ComMscExemptionRCtMapper;
import market.Qms.qcm.mapper.ComMscExemptionRDsMapper;
import market.Qms.qcm.mapper.ComMscExemptionRRgMapper;
import market.Qms.qcm.service.ComMscExemptionService;
import market.Qms.qcm.vo.ComMscExemption;
import market.Qms.qcm.vo.ComMscExemptionRCt;
import market.Qms.qcm.vo.ComMscExemptionRDs;
import market.Qms.qcm.vo.ComMscExemptionRRg;
import market.Qms.slmord.mapper.SlmOrdDesignMscMapper;
import market.Qms.slmord.vo.SlmOrdDesignMsc;
import market.Slm.ContractManagement.impl.SlmContractIdenOrgServiceImpl;
import market.Slm.ContractManagement.vo.SlmContractIdenOrg;
import market.Slm.OrderManagement.vo.SlmContractProcessPlan;

import org.springframework.transaction.annotation.Transactional;

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

@RemoteService(path="ComMscExemptionService")
public class ComMscExemptionServiceImpl extends BaseServiceImpl<ComMscExemption,Object> implements ComMscExemptionService {
	/**
	 * 查询免检信息
	 * 
	 * @return
	 */
	public ResultModel getExemptedInfo(CommonPage<ComMscExemption> sum) {
		ResultModel rm = new ResultModel();
		ComMscExemption cme = sum.getObject();
		List<ComMscExemption> listmsc = new ArrayList<>();
		System.out.println(cme.getSteel_name());
		System.out.println(cme.getValidflag());
		try {
			listmsc = this.getMapper(ComMscExemptionMapper.class).getExemptedInfo(cme.getSteel_name(),
					cme.getValidflag());
			rm.setData(listmsc);
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setMsgInfo("查询免检信息失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 新增免检信息
	 * 
	 * @param sum
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel insertExemptedInfo(ComMscExemption cme, List<ComMscExemptionRCt> rct,
			List<ComMscExemptionRDs> rds, List<ComMscExemptionRRg> rrg) {
		ResultModel rm = new ResultModel();
		try {
			if (cme.getProd_name() == null && cme.getProd_name().equals("")) {
				rm.setState("500");
				rm.setMsgInfo("产品规范描述不能为空，请选择产品规范描述后再进行操作！");
				return rm;
			}
			ComMscExemption psc_id = this.getMapper(ComMscExemptionMapper.class).findById(cme.getPsc());
			if (psc_id != null && !psc_id.equals("")) {
				rm.setState("500");
				rm.setMsgInfo("产品名称【" + cme.getProd_name() + "】已存在，不能重复创建免检信息，请确认！");
				return rm;
			}

			String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			// 将传入的值插入com_msc_exemption

			cme.setCreate_name(username);
			cme.setCreate_time(new Date());
			this.getMapper(ComMscExemptionMapper.class).insert(cme);
			// 插入COM_MSC_EXEMPTION_R_CT表
			for (ComMscExemptionRCt r : rct) {
				ComMscExemptionRCt c = new ComMscExemptionRCt();
				c.setPsc(cme.getPsc());
				c.setCustomer_code(r.getCustomer_code());
				c.setCustomer_name(r.getCustomer_name());
				this.getMapper(ComMscExemptionRCtMapper.class).insert(c);
			}
			// 插入COM_MSC_EXEMPTION_R_DS表
			for (ComMscExemptionRDs r : rds) {
				ComMscExemptionRDs d = new ComMscExemptionRDs();
				d.setPsc(cme.getPsc());
				d.setDelivery_state_code(r.getDelivery_state_code());
				d.setDelivery_state_desc(r.getDelivery_state_desc());
				this.getMapper(ComMscExemptionRDsMapper.class).insert(d);
			}
			// 插入COM_MSC_EXEMPTION_R_DS表
			for (ComMscExemptionRRg r : rrg) {
				ComMscExemptionRRg g = new ComMscExemptionRRg();
				g.setPsc(cme.getPsc());
				g.setOrg_code(r.getOrg_code());
				g.setOrg_name(r.getOrg_name());
				this.getMapper(ComMscExemptionRRgMapper.class).insert(g);
			}
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setMsgInfo("新增信息失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 修改免检信息
	 * 
	 * @param sum
	 * @param rct
	 * @param rds
	 * @param rrg
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel updateExemptedInfo(ComMscExemption cme, List<ComMscExemptionRCt> rct,
			List<ComMscExemptionRDs> rds, List<ComMscExemptionRRg> rrg) {
		ResultModel rm = new ResultModel();
		int a1 = 0;
		int a2 = 0;
		int a3 = 0;
		try {
			if (cme.getValidflag().equals("0")) {
				rm.setState("500");
				rm.setMsgInfo("当前选中记录状态为无效，请置为有效后再进行修改操作！");
				return rm;
			}

			String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			// 将传入的值插入com_msc_exemption
			cme.setUpdate_name(username);
			cme.setUpdate_time(new Date());
			if (cme.getThick_min()==null) {
				 this.getMapper(ComMscExemptionMapper.class).upda1(cme.getPsc());
			}
			if (cme.getThick_max()==null) {
				 this.getMapper(ComMscExemptionMapper.class).upda2(cme.getPsc());
			}
			if (cme.getWidth_min()==null) {
				 this.getMapper(ComMscExemptionMapper.class).upda3(cme.getPsc());
			}
			if (cme.getWidth_max()==null) {
				 this.getMapper(ComMscExemptionMapper.class).upda4(cme.getPsc());
			}
			if (cme.getLenth_max()==null) {
				 this.getMapper(ComMscExemptionMapper.class).upda5(cme.getPsc());
			}
			if (cme.getLenth_min()==null) {
				String conn="lenth_min=''";
				 this.getMapper(ComMscExemptionMapper.class).upda6(cme.getPsc());
			}
			this.getMapper(ComMscExemptionMapper.class).update(cme);
			// 更新COM_MSC_EXEMPTION_R_CT表
			for (ComMscExemptionRCt r : rct) {
				// 先把psc对应的适用客户信息删除然后再新增
				if (a1 == 0) {
					this.getMapper(ComMscExemptionRCtMapper.class).deleteRct(cme.getPsc());
					a1++;
				}
				ComMscExemptionRCt c = new ComMscExemptionRCt();
				c.setPsc(cme.getPsc());
				c.setCustomer_code(r.getCustomer_code());
				c.setCustomer_name(r.getCustomer_name());
				this.getMapper(ComMscExemptionRCtMapper.class).insert(c);
			}
			// 插入COM_MSC_EXEMPTION_R_DS表
			for (ComMscExemptionRDs r : rds) {
				if (a2 == 0) {
					this.getMapper(ComMscExemptionRDsMapper.class).deleteRds(cme.getPsc());
					a2++;
				}
				ComMscExemptionRDs d = new ComMscExemptionRDs();
				d.setPsc(cme.getPsc());
				d.setDelivery_state_code(r.getDelivery_state_code());
				d.setDelivery_state_desc(r.getDelivery_state_desc());
				this.getMapper(ComMscExemptionRDsMapper.class).insert(d);
			}
			// 插入COM_MSC_EXEMPTION_R_DS表
			for (ComMscExemptionRRg r : rrg) {
				if (a3 == 0) {
					this.getMapper(ComMscExemptionRRgMapper.class).deleteRrg(cme.getPsc());
					a3++;
				}
				ComMscExemptionRRg g = new ComMscExemptionRRg();
				g.setPsc(cme.getPsc());
				g.setOrg_code(r.getOrg_code());
				g.setOrg_name(r.getOrg_name());
				this.getMapper(ComMscExemptionRRgMapper.class).insert(g);
			}
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setMsgInfo("修改信息失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}

	/**
	 * 作废免检信息
	 * 
	 * @param sum
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel deleteExemptedInfo(CommonPage<ComMscExemption> sum) {
		ResultModel rm = new ResultModel();
		List<ComMscExemption> listcme = sum.getObjectList();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try {
			for (ComMscExemption c : listcme) {
				ComMscExemption cme = new ComMscExemption();
				cme.setDelete_name(username);
				cme.setDelete_time(new Date());
				cme.setPsc(c.getPsc());
				cme.setValidflag("0");
				this.getMapper(ComMscExemptionMapper.class).update(cme);
			}
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setMsgInfo("作废信息失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}

	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel recoveryExemptedInfo(CommonPage<ComMscExemption> sum) {
		ResultModel rm = new ResultModel();
		List<ComMscExemption> listcme = sum.getObjectList();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		try {
			for (ComMscExemption c : listcme) {
				ComMscExemption cme = new ComMscExemption();
				cme.setPsc(c.getPsc());
				this.getMapper(ComMscExemptionMapper.class).recoveryExemptedInfo(c.getPsc());
			}
			rm.setState("200");
		} catch (Exception e) {
			// TODO: handle exception
			rm.setState("500");
			rm.setMsgInfo("恢复信息失败");
			rm.setErrorInfo(e.getMessage());
		}
		return rm;
	}
	
	
	
	/**
	 * 判断免检功能
	 */
	public ResultModel judgeExemptedInfo(CommonPage<SlmContractProcessPlan> slm) {

		ResultModel rm = new ResultModel();

		SlmContractProcessPlan plan = slm.getObject();
		try {

			if (plan == null) {
				rm.setState("500");
				rm.setData(null);
				rm.setMsgInfo("订单不存在");
				return rm;

			}

			if (plan.getPsc() == null) {
				rm.setState("500");
				rm.setData(null);
				rm.setMsgInfo("订单" + plan.getContract_line_no() + "产品规范码不存在");
				return rm;
			}

			// 查询免检信息配置表
			ComMscExemption cp = this.getMapper(ComMscExemptionMapper.class).findById(plan.getPsc());

			if (cp == null) {
				rm.setState("500");
				rm.setData(null);
				rm.setMsgInfo("订单" + plan.getContract_line_no() + "不属于免检产品");
				return rm;

			}

			// 验证免检产品适用客户信息配置表是否存在当前用户

			List<ComMscExemptionRCt> users = this.getMapper(ComMscExemptionRCtMapper.class).findWithCondition(null,
					"PSC='" + plan.getPsc() + "'", null, 0, 0);

			if (users.size() > 0) {
				
				
				
				for (int i = 0; i <users.size(); i++) {
					
					if (!users.get(i).getCustomer_code().equals(plan.getUser_no())) {
						users.remove(i);
						i--;
					}
					
				}

				
				if (users.size() < 1) {
					rm.setState("500");
					rm.setData(null);
					rm.setMsgInfo("订单" + plan.getContract_line_no() + "客户为" + plan.getUser_name() + "不能免检");
					return rm;

				}

			}

			// 验证认证机构

			// 获取订单对应的认证机构
			SlmContractIdenOrg orgs = new SlmContractIdenOrg();
			orgs.setContract_line_no(plan.getContract_line_no());
			orgs.setPsc(plan.getPsc());
			ResultModel rl = this.getBean(SlmContractIdenOrgServiceImpl.class).doQueryIdenOrg(orgs);
			List<SlmContractIdenOrg> ordList = (List<SlmContractIdenOrg>) rl.getData();

			List<ComMscExemptionRRg> org = this.getMapper(ComMscExemptionRRgMapper.class).findWithCondition(null,
					"PSC='" + plan.getPsc() + "'", null, 0, 0);

			if (org.size() > 0) {

				for (SlmContractIdenOrg planOrg : ordList) {

					for (int i = 0; i < org.size(); i++) {

						if (planOrg.getOrg_code().equals(org.get(i).getOrg_code())) {

							break;

						}

						if (i == org.size() - 1) {
							rm.setState("500");
							rm.setData(null);
							rm.setMsgInfo(
									"订单" + plan.getContract_line_no() + "存在认证机构" + planOrg.getOrg_name() + "不能免检");

						}

					}
				}

			}

			// 过滤规格
			boolean pass = FilterExemp(cp, plan);
			if (!pass) {
				rm.setState("500");
				rm.setData(null);
				rm.setMsgInfo("订单" + plan.getContract_line_no() + "的规格不符合免检要求");
				return rm;

			}

			rm.setData(cp);
			rm.setState("200");

		} catch (Exception e) {
			rm.setState("500");
			rm.setData(null);
			rm.setMsgInfo("订单" + plan.getContract_line_no() + "的验证是否免检失败");
			return rm;
		}

		return rm;
	}
	
	
	
	/**
	 * 过滤规格
	 * 
	 * @param cp
	 * @param orderLine
	 * @return
	 */

	public boolean FilterExemp(ComMscExemption cp, SlmContractProcessPlan orderLine) {
		List<ComMscStdPhy> _listChem = new ArrayList<>();

		if (cp.getThick_min() != null) {
			boolean pass = DataHelper.checkSignAndValue(cp.getThick_min_sign(), cp.getThick_min(),
					orderLine.getThick().toString());
			if (!pass) {
				return false;
			}
		}

		if (cp.getThick_max() != null) {
			boolean pass = DataHelper.checkSignAndValue(cp.getThick_max_sign(), cp.getThick_max(),
					orderLine.getThick().toString());
			if (!pass) {
				return false;
			}

		}

		if (cp.getWidth_min() != null) {
			boolean pass = DataHelper.checkSignAndValue(cp.getWidth_min_sign(), cp.getWidth_min(),
					orderLine.getWidth().toString());
			if (!pass) {
				return false;
			}
		}

		if (cp.getWidth_max() != null) {
			boolean pass = DataHelper.checkSignAndValue(cp.getWidth_max_sign(), cp.getWidth_max(),
					orderLine.getWidth().toString());
			if (!pass) {
				return false;
			}
		}

		if (cp.getLenth_min() != null) {
			boolean pass = DataHelper.checkSignAndValue(cp.getLenth_min_sign(), cp.getLenth_min(),
					DataHelper.getDoubleString(orderLine.getLength()));
			if (!pass) {
				return false;
			}

		}

		if (cp.getLenth_max() != null) {
			boolean pass = DataHelper.checkSignAndValue(cp.getLenth_max_sign(), cp.getLenth_max(),
					DataHelper.getDoubleString(orderLine.getLength()));
			if (!pass) {
				return false;
			}

		}

		return true;
	}
	
	/**
	 * 根据design_key获取是否免检
	 * 
	 * 
	 */
	public ResultModel judgeExemptedByDk(String design_key) {
		ResultModel rm = new ResultModel();
		try {

			SlmOrdDesignMsc msc = this.getMapper(SlmOrdDesignMscMapper.class).findById(design_key);
			if (msc != null) {
				SlmContractProcessPlan plan = new SlmContractProcessPlan();
				plan.setContract_line_no(msc.getContract_line_no());
				plan.setPsc(msc.getPsc());
				plan.setThick(msc.getThick());
				plan.setLength(msc.getLength());
				plan.setWidth(msc.getWidth());
				plan.setUser_no(msc.getFinal_user_code());
				plan.setUser_name(msc.getFinal_user_desc());
				CommonPage<SlmContractProcessPlan> slm = new CommonPage<SlmContractProcessPlan>();
				slm.setObject(plan);
				ResultModel mianJian = judgeExemptedInfo(slm);
				ComMscExemption cp = (ComMscExemption) mianJian.getData();
				rm.setData(cp);

			}

			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询是否免检失败");
			return rm;
		}

		return rm;
	}
	

}
