/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-07-04
 * 描述            ：资材备件库-借出信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
 ***********************************************************/
package market.Lms.Equipment.impl;

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

import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Equipment.mapper.YdmEquipmentDetailMapper;
import market.Lms.Equipment.mapper.YdmEquipmentInlistMapper;
import market.Lms.Equipment.mapper.YdmEquipmentLendlistMapper;
import market.Lms.Equipment.service.YdmEquipmentLendlistService;
import market.Lms.Equipment.vo.YdmEquipmentDetail;
import market.Lms.Equipment.vo.YdmEquipmentInlist;
import market.Lms.Equipment.vo.YdmEquipmentLendlist;

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;
import com.ibm.icu.text.SimpleDateFormat;

@RemoteService(path = "YdmEquipmentLendlistService")
public class YdmEquipmentLendlistServiceImpl extends
		BaseServiceImpl<YdmEquipmentLendlist, Object> implements
		YdmEquipmentLendlistService {
	/**
	 * 查询借出、归还信息表数据 object中state 0借出 1归还
	 */
	public ResultModel doQueryWeb(CommonPage<YdmEquipmentLendlist> cp) {
		ResultModel rm = new ResultModel();
		YdmEquipmentLendlist ye = cp.getObject() == null ? new YdmEquipmentLendlist()
				: cp.getObject();
		String columName = null;
		try {
			String userName = (String) this.getSession().getAttribute(
					HomeService.SESSION_USER_NAME);
			if (userName == null) {
				rm.setState("500");
				rm.setMsgInfo("登录信息过期，请重新登录!");
				return rm;
			}
			String sWhere = " 1=1 ";
			if (ye.getState() != null && !"".equals(ye.getState().trim())) {
				columName = "0".equals(cp.getObject().getState()) ? "lend_time"
						: "return_time";
				if (cp.getStartTime() != null && !"".equals(cp.getStartTime())) {
					sWhere += " and " + columName + ">= to_date(concat('"
							+ cp.getStartTime()
							+ "',' 00:00:00'),'yyyy-MM-dd HH24:mi:ss')";
				}
				if (cp.getEndTime() != null && !"".equals(cp.getEndTime())) {
					sWhere += " and " + columName + "<= to_date(concat('"
							+ cp.getEndTime()
							+ "',' 23:59:59'),'yyyy-MM-dd HH24:mi:ss')";
				}
				sWhere += " and lend_man = '"+userName+"'";
				if(ye.getSrot_code() != null && "".equals(ye.getStorage_code())){
					sWhere += "and storage_code = '"+ye.getStorage_code()+"'";
				}
			} else {
				rm.setState("500");
				rm.setMsgInfo("传入参数错误!");
				return rm;
			}

			List<YdmEquipmentLendlist> lyel = this.getMapper(YdmEquipmentLendlistMapper.class).findWithCondition(ye, sWhere, columName + " desc", 0, 0);
			for (YdmEquipmentLendlist y : lyel) {
				String plan_return_date = y.getPlan_return_date();
				if (plan_return_date == null || "".equals(plan_return_date.trim())) {
					continue;
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date prdDate = sdf.parse(plan_return_date);
				// (1:超过计划归还日期；2:等于；0:未到)
				y.setConpareDate(plan_return_date.equals(sdf.format(new Date())) ? "2" : (prdDate.after(new Date()) ? "0" : "1"));
			}
			rm.setState("200");    
			rm.setData(lyel);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!" + ex.getMessage());
		}
		return rm;
	}

	/**
	 * 归还
	 * 
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddWeb(CommonPage<YdmEquipmentLendlist> cp)
			throws Exception {
		ResultModel rm = new ResultModel();

		if (cp.getObject() == null || cp.getObject().getLend_bill_no() == null
				|| "".equals(cp.getObject().getLend_bill_no())) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据！");
			return rm;
		}
		if (cp.getObject().getReturn_date() == null
				|| "".equals(cp.getObject().getReturn_date())) {
			rm.setState("500");
			rm.setMsgInfo("归还日期不得为空！");
			return rm;
		}
		if (cp.getObject().getArea() == null
				|| "".equals(cp.getObject().getArea())) {
			rm.setState("500");
			rm.setMsgInfo("库存区域不得为空！");
			return rm;
		}
		YdmEquipmentLendlist yelq = this.getMapper(
				YdmEquipmentLendlistMapper.class).findById(
				cp.getObject().getLend_bill_no());
		if (yelq == null || yelq.getLend_bill_no() == null) {
			rm.setState("500");
			rm.setMsgInfo("未找到借出信息!");
			return rm;
		}

		/*
		 * 在入库信息表(YDM_EQUIPMENT_INLIST)中新增一条入库记录 入库编号(IN_BILL_NO)生成规则
		 * IN+'yyyyMMdd'+4位流水 入库类型编码(IN_TYPE)从com_base_info中取(5004)归还入库
		 * 借出单号（LEND_BILL_NO）为选择记录的借出单号
		 */
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		if (userName == null && userId == null) {
			rm.setState("500");
			rm.setMsgInfo("登录信息过期，请重新登录!");
			return rm;
		}
		Date date = new Date();
		Double cpQuantity = cp.getObject().getReturn_quantity() == null ? 0d : cp
				.getObject().getReturn_quantity();

		YdmEquipmentInlist yei = new YdmEquipmentInlist();
		yei.setIn_bill_no(this.getMapper(YdmEquipmentInlistMapper.class)
				.getCode("IN" + new SimpleDateFormat("yyyyMMdd").format(date)));
		yei.setIn_type("500410");
		yei.setLend_bill_no(cp.getObject().getLend_bill_no());
		yei.setOpr_man(userName);
		yei.setIn_grp((String) this.getSession().getAttribute(
				HomeService.SESSION_WORK_GRP));
		yei.setIn_ord((String) this.getSession().getAttribute(
				HomeService.SESSION_WORK_ORD));
		yei.setIn_date(cp.getObject().getReturn_date());
		yei.setOpr_time(date);
		yei.setObject_no(yelq.getObject_no());
		yei.setMat_code(yelq.getMat_code());
		yei.setMat_name(yelq.getMat_name());
		yei.setSrot_code(yelq.getSrot_code());
		yei.setSrot_name(yelq.getSrot_name());
		yei.setSpec(yelq.getSpec());
		yei.setPurc_order_no(yelq.getPurc_order_no());
		yei.setPurc_order_pk(yelq.getPurc_order_pk());
		yei.setSupplier_name(yelq.getSupplier_name());
		yei.setSupplier_no(yelq.getSupplier_no());
		yei.setQuantity(cpQuantity);
		yei.setUnit(yelq.getUnit());
		yei.setPrice(yelq.getPrice());
		yei.setArea(cp.getObject().getArea());
		yei.setDept_code(yelq.getDept_code());
		yei.setStorage_code(yelq.getStorage_code());
		yei.setCreate_man_name(userName);
		yei.setCreate_man_no(userId);
		yei.setCreate_time(date);
		this.getMapper(YdmEquipmentInlistMapper.class).insert(yei);

		// 在借出信息表(YDM_EQUIPMENT_LENDLIST）中修改对应借出编号的记录，设置状态=1归还，设置归还操作时间、归还日期、归还操作人、归还数量
		YdmEquipmentLendlist yel = new YdmEquipmentLendlist();
		yel.setLend_bill_no(cp.getObject().getLend_bill_no());
		yel.setState("1");
		yel.setReturn_date(cp.getObject().getReturn_date());
		yel.setReturn_man(userName);
		yel.setReturn_time(date);
		yel.setReturn_quantity(cpQuantity);
		this.getMapper(YdmEquipmentLendlistMapper.class).update(yel);

		// 修改库存信息表（YDM_EQUIPMENT_DETAIL）对应库存编号&&借出的数据， 设置数量(QUANTITY) -= 数量
		YdmEquipmentDetail yed = new YdmEquipmentDetail();
		yed.setObject_no(yelq.getObject_no());
		yed.setState("1");// 在库状态(0在库、1借出、2维修、5出库)
		List<YdmEquipmentDetail> lyedq = this.getMapper(
				YdmEquipmentDetailMapper.class).find(yed, 0, 0);
		if (lyedq == null || lyedq.size() == 0) {
			throw new Exception("借出数据未找到！");
		}
		// 库存表里借出量
		Double lyedqB = lyedq.get(0).getQuantity() == null ? 0d : lyedq.get(0)
				.getQuantity();
		// 库存编号&&借出的数量(QUANTITY)=0 then
		// 在库存信息表（YDM_EQUIPMENT_DETAIL）中删除库存编号&&借出的数据
		if (lyedqB.equals(cpQuantity)) {
			this.getMapper(YdmEquipmentDetailMapper.class).doDelete(yed);
		} else {
			if (lyedqB.longValue() < cpQuantity
					.longValue()) {
				throw new Exception("要归还的数量大于库存记录的借出量，请核实！");
			}
			yed.setQuantity(lyedqB - cpQuantity);
			this.getMapper(YdmEquipmentDetailMapper.class).doUpdate(yed);
		}
		// if 库存信息表（YDM_EQUIPMENT_DETAIL）存在库存编号&&在库的数据 then
		yed.setQuantity(null);
		yed.setState("0");//
		List<YdmEquipmentDetail> lyedqq = this.getMapper(
				YdmEquipmentDetailMapper.class).find(yed, 0, 0);
		if (lyedqq == null || lyedqq.size() == 0) {
			// 在库存信息表（YDM_EQUIPMENT_DETAIL）新增对应库存编号&&在库的数据
			YdmEquipmentDetail yedi = new YdmEquipmentDetail();
			yedi.setObject_no(yed.getObject_no());
			yedi.setMat_code(yelq.getMat_code());
			yedi.setMat_name(yelq.getMat_name());
			yedi.setSrot_code(yelq.getSrot_code());
			yedi.setSrot_name(yelq.getSrot_name());
			yedi.setSpec(yelq.getSpec());
			yedi.setPurc_order_no(yelq.getPurc_order_no());
			yedi.setPurc_order_pk(yelq.getPurc_order_pk());
			yedi.setSupplier_name(yelq.getSupplier_name());
			yedi.setSupplier_no(yelq.getSupplier_no());
			yedi.setQuantity(cpQuantity);
			yedi.setUnit(yelq.getUnit());
			yedi.setPrice(yelq.getPrice());
			yedi.setIn_date(cp.getObject().getReturn_date());
			yedi.setArea(cp.getObject().getArea());
			yedi.setState("0");
			// ?????????????
			// yedi.setDept_code(yelq.getDept_code());
			// yedi.setStorage_code(yelq.getStorage_code());
			// --------------------
			this.getMapper(YdmEquipmentDetailMapper.class).insert(yedi);
		} else {
			// 修改库存信息表（YDM_EQUIPMENT_DETAIL）对应库存编号&&在库的数据， 设置数量(QUANTITY) += 数量
			YdmEquipmentDetail yedu = new YdmEquipmentDetail();
			yedu.setState("0");
			// 库存表里在库量
			Double lyedqI = lyedqq.get(0).getQuantity() == null ? 0d : lyedqq.get(0).getQuantity();
			yedu.setQuantity(lyedqI + cpQuantity);
			yedu.setObject_no(yed.getObject_no());
			this.getMapper(YdmEquipmentDetailMapper.class).doUpdate(yedu);
		}

		rm.setState("200");
		return rm;
	}

	/**
	 * 撤销
	 * 
	 * @param cp
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doDeleteWeb(CommonPage<YdmEquipmentLendlist> cp) {
		ResultModel rm = new ResultModel();
		if (cp.getObject() == null || cp.getObject().getLend_bill_no() == null
				|| "".equals(cp.getObject().getLend_bill_no())) {
			rm.setState("500");
			rm.setMsgInfo("请选择数据!");
			return rm;
		}
		String userName = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_NAME);
		String userId = (String) this.getSession().getAttribute(
				HomeService.SESSION_USER_ID);
		if (userName == null && userId == null) {
			rm.setState("500");
			rm.setMsgInfo("登录信息过期，请重新登录!");
			return rm;
		}
		// if 库存编号&&在库 的数量 < 撤销数量 then 不允许操作
		YdmEquipmentLendlist yelq = this.getMapper(
				YdmEquipmentLendlistMapper.class).findById(
				cp.getObject().getLend_bill_no());
		if (yelq == null || yelq.getLend_bill_no() == null) {
			rm.setState("500");
			rm.setMsgInfo("未找到归还信息!");
			return rm;
		}
		YdmEquipmentDetail yed = new YdmEquipmentDetail();
		yed.setState("0");// 在库状态(0在库、1借出、2维修、5出库)
		yed.setObject_no(yelq.getObject_no());
		List<YdmEquipmentDetail> lyedqq = this.getMapper(
				YdmEquipmentDetailMapper.class).find(yed, 0, 0);
		if (lyedqq == null || lyedqq.size() == 0) {
			rm.setState("500");
			rm.setMsgInfo("未找到归还信息!");
			return rm;
		}
		yelq.setReturn_quantity(yelq.getReturn_quantity() == null ? 0d : yelq
				.getReturn_quantity());
		// 库存表里在库量
		Double lyedqI = lyedqq.get(0).getQuantity() == null ? 0d : lyedqq.get(0)
				.getQuantity();
		if (lyedqI.longValue() < yelq.getReturn_quantity().longValue()) {
			rm.setState("500");
			rm.setMsgInfo("要撤销的数量大于库存信息的在库数量，请核实!");
			return rm;
		}

		// 在入库信息表(YDM_EQUIPMENT_INLIST)中删除对应借出编号的入库记录
		YdmEquipmentInlist yei = new YdmEquipmentInlist();
		yei.setLend_bill_no(yelq.getLend_bill_no());
		this.getMapper(YdmEquipmentInlistMapper.class).doDeleteEquipment(yei);

		// 在借出信息表(YDM_EQUIPMENT_LENDLIST)中修改对应借出编号的记录，设置状态=0借出，设置归还操作时间、归还日期、归还操作人，归还数量为null
		YdmEquipmentLendlist yel = new YdmEquipmentLendlist();
		yel.setLend_bill_no(cp.getObject().getLend_bill_no());
		this.getMapper(YdmEquipmentLendlistMapper.class).doUpdateNull(yel);

		YdmEquipmentDetail yedu = new YdmEquipmentDetail();
		yedu.setObject_no(yelq.getObject_no());

		// if 库存编号&&在库的数量(QUANTITY)=0 在库存信息表（YDM_EQUIPMENT_DETAIL）中删除库存编号&&在库的数据
		if (lyedqI.longValue() == yelq.getReturn_quantity().longValue()) {
			yedu.setState("0");
			this.getMapper(YdmEquipmentDetailMapper.class).doDelete(yedu);
		} else {
			// 修改库存信息表（YDM_EQUIPMENT_DETAIL）对应库存编号&&在库的数据， 设置数量(QUANTITY) -= 数量
			yedu.setState("0");
			yedu.setQuantity(lyedqI - yelq.getReturn_quantity());
			this.getMapper(YdmEquipmentDetailMapper.class).doUpdate(yedu);
		}

		// if 库存信息表（YDM_EQUIPMENT_DETAIL）存在库存编号&&借出的数据 then
		// 修改库存信息表（YDM_EQUIPMENT_DETAIL）对应库存编号&&借出的数据， 设置数量
		// (QUANTITY) += 数量
		yedu.setState("1");
		yedu.setQuantity(null);
		// 找到库存表里的借出信息
		List<YdmEquipmentDetail> lyed = this.getMapper(
				YdmEquipmentDetailMapper.class).find(yedu, 0, 0);
		if (lyed != null && lyed.size() != 0) {
			// 库存表里的借出数量
			Double lyedqB = lyedqq.get(0).getQuantity() == null ? 0d : lyedqq.get(0).getQuantity();
			yedu.setQuantity(lyedqB + yelq.getReturn_quantity());
			this.getMapper(YdmEquipmentDetailMapper.class).doUpdate(yedu);
		} else {
			// 在库存信息表（YDM_EQUIPMENT_DETAIL）新增对应库存编号&&借出的数据
			YdmEquipmentDetail yedi = new YdmEquipmentDetail();
			yedi.setObject_no(yedu.getObject_no());
			yedi.setMat_code(lyedqq.get(0).getMat_code());
			yedi.setMat_name(lyedqq.get(0).getMat_name());
			yedi.setSrot_code(lyedqq.get(0).getSrot_code());
			yedi.setSrot_name(lyedqq.get(0).getSrot_name());
			yedi.setSpec(lyedqq.get(0).getSpec());
			yedi.setPurc_order_no(lyedqq.get(0).getPurc_order_no());
			yedi.setPurc_order_pk(lyedqq.get(0).getPurc_order_pk());
			yedi.setSupplier_name(lyedqq.get(0).getSupplier_name());
			yedi.setSupplier_no(lyedqq.get(0).getSupplier_no());
			yedi.setQuantity(yelq.getReturn_quantity());
			yedi.setUnit(lyedqq.get(0).getUnit());
			yedi.setPrice(lyedqq.get(0).getPrice());
			// yedi.setIn_date(cp.getObject().getReturn_date());
			yedi.setArea(cp.getObject().getArea());
			yedi.setState("1");
			// ?????????????
			// yedi.setDept_code(lyedqq.get(0).getDept_code());
			// yedi.setStorage_code(lyedqq.get(0).getStorage_code());
			// --------------------
			this.getMapper(YdmEquipmentDetailMapper.class).insert(yedi);
		}
		rm.setState("200");
		return rm;
	}
}
