package market.Qms.com.service.impl;

import java.util.Date;
import java.util.List;

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Qms.com.mapper.BaseStdAlphaMapper;
import market.Qms.com.mapper.BaseStdRCustMapper;
import market.Qms.com.mapper.MscMapper;
import market.Qms.com.service.BaseStdAlphaService;
import market.Qms.com.vo.BaseStdAlpha;
import market.Qms.com.vo.BaseStdRCust;
import market.Qms.com.vo.Msc;
import market.Qms.common.DataHelper;
import market.Qms.common.RequestModel;
import market.Qms.common.ReturnMsg;
import market.Qms.metallurgy.mapper.ComBaseStdMapper;
import market.Qms.metallurgy.mapper.ComMscMapper;
import market.Qms.metallurgy.vo.ComBaseStd;
import market.Qms.metallurgy.vo.ComMsc;

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="BaseStdAlphaService")
public class BaseStdAlphaServiceImpl extends BaseServiceImpl<BaseStdAlpha, String> implements BaseStdAlphaService {

	@Override
	public ReturnMsg<List<BaseStdAlpha>> GetStdAlpha(RequestModel<BaseStdAlpha> alpha) {
		// TODO Auto-generated method stub
		ReturnMsg<List<BaseStdAlpha>> msg=new ReturnMsg<>();
		try{
			BaseStdAlphaMapper mapper=this.getMapper(BaseStdAlphaMapper.class);
			List<BaseStdAlpha> list=mapper.findWithCondition(alpha.getModel(), null, "ALPHA_CODE DESC", alpha.getSkipResults(), alpha.getPageSize());
			int count=mapper.countWithCondition(alpha.getModel(),null);
			msg.setTotal(count);
			msg.setMessage("获取数据成功");
			msg.setSuccess(true);
			msg.setResult(list);
		}catch(Exception ex){
			msg.setSuccess(false);
			msg.setMessage(ex.getMessage());
		}
		return msg;
	}


	@Override
	public ReturnMsg<BaseStdAlpha> SaveStdAlpha(BaseStdAlpha alpha) {
		// TODO Auto-generated method stub
		ReturnMsg<BaseStdAlpha> msg=new ReturnMsg<>();
		msg.setResult(alpha);
		try{
			BaseStdAlphaMapper mapper=this.getMapper(BaseStdAlphaMapper.class);
			if(DataHelper.IsNullOrSpace(alpha.getAlphaCode())){
				String maxCode=mapper.GetMaxCode(alpha.getStdCode());
				String code=DataHelper.InitSerial(maxCode,alpha.getStdCode(), 13);
				alpha.setAlphaCode(code);
				alpha.setCreateTime(new Date());
				mapper.insert(alpha);

			}else{
				alpha.setUpdateTime(new Date());
				mapper.update(alpha);
			}
			msg.setMessage("保存数据成功");
			msg.setSuccess(true);
			msg.setResult(alpha);
		}catch(Exception ex){
			msg.setSuccess(false);
			msg.setMessage(ex.getMessage());
		}
		return msg;
	}

	@Override
	public ReturnMsg DelOrRenew(String deleteName,String alphaCode, Boolean flag) {
		// TODO Auto-generated method stub
		ReturnMsg msg=new ReturnMsg<>();
		try{
			// TODO Auto-generated method stub
			BaseStdAlpha alpha=new BaseStdAlpha();
			alpha.setAlphaCode(alphaCode);
			alpha.setValidflag(flag?"0":"1");
			if(flag){
				alpha.setDeleteName(deleteName);
				alpha.setDeleteTime(new Date());
			}else{
				alpha.setUpdateTime(new Date());
				alpha.setUpdateName(deleteName);
			}
			this.getMapper(BaseStdAlphaMapper.class).update(alpha);
			msg.setMessage(flag?"废除成功":"恢复成功");
			msg.setSuccess(true);
		}catch(Exception ex){
			msg.setMessage(ex.getMessage());
			msg.setSuccess(false);
		}
		return msg;
	}
	
	
	/***
	 * 1月17日修改
	 * 用途码信息维护——标准基础信息查询
	 * 从标准基础表COM_BASE_STD获取STD_TYPE=‘G’（国标）STD_TYPE=‘X’（协议）
	 * @param cp
	 * memo1:标准名称   1：勾选填写
	 * memo2:有效无效   1：勾选无效
	 * @return
	 */
	public ResultModel doQueryStdWeb(CommonPage<ComBaseStd> cp){
		ResultModel rm = new ResultModel();
		int pageIndex = cp.getPageIndex();
		int pageSize = cp.getPageSize();
		ComBaseStd std = cp.getObject();
		String condition = "1=1";
		PageModel<ComBaseStd> pm = new PageModel<ComBaseStd>(pageIndex, pageSize);
		try {
			if ("1".equals(cp.getMemo1())) {
				condition += " and upper(STD_NAME) like '%" + std.getStdName().toUpperCase() + "%'";
			}
			if ("0".equals(cp.getMemo2())) {
				condition += " and VALIDFLAG = '1'";
				std.setValidflag("1");
			}
			condition += "and STD_TYPE in ('G','X')";
			pm.setRows(this.getMapper(ComBaseStdMapper.class).findWithCondition(null, condition, "CREATE_TIME desc",
					(pageIndex - 1) * pageSize, pageSize));
			pm.setTotal(this.getMapper(ComBaseStdMapper.class).countWithCondition(null, condition));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			e.printStackTrace();
		}
		return rm;
	}
	
	/*****
	 * 用途码信息维护——用途码信息查询
	 * 根据标准基础STD_CODE查询标准用途码表
	 * @param cp:传入参数STD_CODE
	 * @return
	 */
	public ResultModel doQueryStdAlpha(CommonPage<BaseStdAlpha> cp){
		ResultModel rm = new ResultModel();
		int pageIndex = cp.getPageIndex();
		int pageSize = cp.getPageSize();
		BaseStdAlpha Alpha = cp.getObject();
		String condition = "1=1";
		PageModel<BaseStdAlpha> pm = new PageModel<BaseStdAlpha>(pageIndex, pageSize);
		try {
			if ("0".equals(cp.getMemo2())) {
				condition += " and VALIDFLAG = '1'";
			}
			condition += " and STD_CODE = '" + Alpha.getStdCode() + "'";
			pm.setRows(this.getMapper(BaseStdAlphaMapper.class).findWithCondition(null, condition, "CREATE_TIME desc",
					(pageIndex - 1) * pageSize, pageSize));
			pm.setTotal(this.getMapper(BaseStdAlphaMapper.class).countWithCondition(null, condition));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			e.printStackTrace();
		}
		return rm;
	}
	
	/******
	 * 用途码信息维护——适用最终用户信息查询
	 * 根据选中的用途码（ALPHA_CODE）查询客户标准与最终用户对应表
	 * @param cp
	 * @return
	 */
	public ResultModel doQueryStdRCust(CommonPage<BaseStdRCust> cp){
		ResultModel rm = new ResultModel();
		int pageIndex = cp.getPageIndex();
		int pageSize = cp.getPageSize();
		BaseStdRCust cust = cp.getObject();
		String condition = "1=1";
		PageModel<BaseStdRCust> pm = new PageModel<BaseStdRCust>(pageIndex, pageSize);
		try {
			if ("0".equals(cp.getMemo2())) {
				condition += " and VALIDFLAG = '1'";
			}
			condition += " and ALPHA_CODE = '" + cust.getAlphaCode() + "'";
			pm.setRows(this.getMapper(BaseStdRCustMapper.class).findWithCondition(null, condition, "CREATE_TIME desc",
					(pageIndex - 1) * pageSize, pageSize));
			pm.setTotal(this.getMapper(BaseStdRCustMapper.class).countWithCondition(null, condition));
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			e.printStackTrace();
		}
		return rm;
	}
	
	/*****
	 * 用途码信息维护——新增
	 * @param cp
	 * @return
	 */
	public ResultModel doInsertWeb(CommonPage<BaseStdAlpha> cp) {
		ResultModel rm = new ResultModel();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		BaseStdAlphaMapper mapper = this.getMapper(BaseStdAlphaMapper.class);
		try {
			//用途码信息新增
			BaseStdAlpha alpha = new BaseStdAlpha();
			alpha = cp.getObject();
			if (alpha.getAlphaName() == null || "".equals(alpha.getAlphaName().trim())) {
				rm.setState("500");
				rm.setMsgInfo("用途描述不能为空！");
				return rm;
			}
			String condition = " and ALPHA_NAME = '" + alpha.getAlphaName() + "'";
			int temp = mapper.countWithCondition(null, condition);
			if (temp > 0) {
				rm.setState("500");
				rm.setMsgInfo("该用途描述已经存在！");
				return rm;
			}
			alpha.setCreateName(username);
			alpha.setCreateTime(new Date());
			alpha.setValidflag("1");
			//生成用途码
			String maxCode=mapper.GetMaxCode(alpha.getStdCode());
			String code=DataHelper.InitSerial(maxCode,alpha.getStdCode(), 13);
			alpha.setAlphaCode(code);
			mapper.insert(alpha);//新增
			
			//适用最终用户信息新增
			List<BaseStdRCust> custs = alpha.getBaseStdRCusts();
			if (custs != null) {
				for (BaseStdRCust baseStdRCust : custs) {
					baseStdRCust.setAlphaCode(code);
					baseStdRCust.setAlphaName(alpha.getAlphaName());
					baseStdRCust.setStdCodeOld(alpha.getAlphaCodeOld());
					baseStdRCust.setCreateTime(new Date());
					baseStdRCust.setCreateName(username);
					baseStdRCust.setValidflag("1");
					int num = this.getMapper(BaseStdRCustMapper.class).count(baseStdRCust);
					if (num > 0) {
						rm.setState("500");
						rm.setMsgInfo("同客户代码/用途码的同一信息已经存在！");
						throw new Exception();
					}else {
						this.getMapper(BaseStdRCustMapper.class).insert(baseStdRCust);
					}
				}
			}
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("新增失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	
	/*****
	 * 用途码信息维护——修改
	 * @param cp
	 * @return
	 */
	public ResultModel doUpdateWeb(CommonPage<BaseStdAlpha> cp) {
		ResultModel rm = new ResultModel();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		BaseStdAlphaMapper mapper = this.getMapper(BaseStdAlphaMapper.class);
		BaseStdAlpha alpha = cp.getObject();
		try {
			//BaseStdAlpha alpha = new BaseStdAlpha();
			//alpha = mapper.findById(bsa.getAlphaCode());
			//修改用途码信息
			//有效性判断
			if (alpha.getAlphaCode() == null || "0".equals(alpha.getValidflag())) {
				rm.setState("500");
				rm.setMsgInfo("选中记录无效或不存在！");
				return rm;
			}
			
			if (alpha.getAlphaName() == null || "".equals(alpha.getAlphaName().trim())) {
				rm.setState("500");
				rm.setMsgInfo("用途描述不能为空！");
				return rm;
			}
			String condition = " and ALPHA_NAME = '" + alpha.getAlphaName() + 
					"' and ALPHA_CODE <> '" + alpha.getAlphaCode() + "'";
			int temp = mapper.countWithCondition(null, condition);
			if (temp > 0) {
				rm.setState("500");
				rm.setMsgInfo("该用途描述已经存在！");
				return rm;
			}
			alpha.setUpdateName(username);
			alpha.setUpdateTime(new Date());
			mapper.update(alpha);
			
			//修改适用最终用户信息
			this.getMapper(BaseStdRCustMapper.class).doDelete(alpha.getAlphaCode());
			List<BaseStdRCust> custs = alpha.getBaseStdRCusts();
			if (custs != null) {
				for (BaseStdRCust baseStdRCust : custs) {
					baseStdRCust.setAlphaCode(alpha.getAlphaCode());
					baseStdRCust.setAlphaName(alpha.getAlphaName());
					baseStdRCust.setStdCodeOld(alpha.getAlphaCodeOld());
					baseStdRCust.setCreateTime(new Date());
					baseStdRCust.setCreateName(username);
					baseStdRCust.setValidflag("1");
					int num = this.getMapper(BaseStdRCustMapper.class).count(baseStdRCust);
					if (num > 0) {
						rm.setState("500");
						rm.setMsgInfo("同客户代码/用途码的同一信息已经存在！");
						throw new Exception();
					}else {
						this.getMapper(BaseStdRCustMapper.class).insert(baseStdRCust);
					}
				}
			}
			
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("修改失败!");
			ex.printStackTrace();
		}
		return rm;
	}

	/*****
	 * 用途码信息维护——作废
	 * @param cp
	 * @return
	 */
	public ResultModel doCancel(CommonPage<BaseStdAlpha> cp) {
		ResultModel rm = new ResultModel();
		String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		BaseStdAlphaMapper mapper1 = this.getMapper(BaseStdAlphaMapper.class);
		BaseStdRCustMapper mapper2 = this.getMapper(BaseStdRCustMapper.class);
		try {
			BaseStdAlpha bsa = cp.getObject();
			BaseStdAlpha alpha = mapper1.findById(bsa.getAlphaCode());
			if ("0".equals(alpha.getValidflag())) {
				rm.setState("500");
				rm.setMsgInfo("作废失败，无效数据无法作废！");
				return rm;
			}
			Msc msc = new Msc();
			msc.setAlphaCode(bsa.getAlphaCode());
			List<Msc> mscs = this.getMapper(MscMapper.class).find(msc, 0, 0);
			if (mscs.size() > 0) {
				rm.setState("500");
				rm.setMsgInfo("作废失败，被引用数据无法作废！");
				return rm;
			}
			alpha.setDeleteName(username);
			alpha.setDeleteTime(new Date());
			alpha.setValidflag("0");
			mapper1.update(alpha);
			mapper2.doCancel(alpha.getAlphaCode());
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("作废失败!");
			e.printStackTrace();
		}
		return rm;
	}
	
	/****
	 * 用途码信息维护——恢复
	 * @param cp
	 * @return
	 */
	public ResultModel doRecover(CommonPage<BaseStdAlpha> cp) {
		ResultModel rm = new ResultModel();
		BaseStdAlphaMapper mapper1 = this.getMapper(BaseStdAlphaMapper.class);
		BaseStdRCustMapper mapper2 = this.getMapper(BaseStdRCustMapper.class);
		try {
			BaseStdAlpha bsa = cp.getObject();
			BaseStdAlpha alpha = mapper1.findById(bsa.getAlphaCode());
			if ("1".equals(alpha.getValidflag())) {
				rm.setState("500");
				rm.setMsgInfo("恢复失败，有效数据无法作废！");
				return rm;
			}
			alpha.setValidflag("1");
			mapper1.doUpdate(alpha.getAlphaCode());
			mapper2.doRecover(alpha.getAlphaCode());
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("恢复失败!");
			e.printStackTrace();
		}
		return rm;
	}
	
	
	/*****
	 * 查询可操作用途码，没被mscn引用
	 * 根据标准基础STD_CODE查询标准用途码表
	 * @param cp:传入参数STD_CODE
	 * @return
	 */
	public ResultModel doQueryAlpha(CommonPage<BaseStdAlpha> cp){
		ResultModel rm = new ResultModel();
		int pageIndex = cp.getPageIndex();
		int pageSize = cp.getPageSize();
		BaseStdAlpha Alpha = cp.getObject();
		String condition = "1=1";
		PageModel<BaseStdAlpha> pm = new PageModel<BaseStdAlpha>(pageIndex, pageSize);
		try {
			if ("0".equals(cp.getMemo2())) {
				condition += " and VALIDFLAG = '1'";
			}
			condition += " and STD_CODE = '" + Alpha.getStdCode() + "'";
			List<BaseStdAlpha> alphys=this.getMapper(BaseStdAlphaMapper.class).findWithCondition(null, condition, "CREATE_TIME desc",
					(pageIndex - 1) * pageSize, pageSize);
			
			for (int i = 0; i < alphys.size(); i++) {
				
				List<ComMsc> mscs=this.getMapper(ComMscMapper.class).findWithCondition(null, "ALPHA_CODE='"+alphys.get(i).getAlphaCode()+"'", null, 0, 0);
				if (mscs.size()>0) {
					
					alphys.remove(alphys.get(i));
					i--;
				}
				
			}
			
			
			pm.setRows(alphys);
			pm.setTotal(alphys.size());
			rm.setData(pm);
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			e.printStackTrace();
		}
		return rm;
	}
	
	
}
