/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2017.11.27
 * 描述               :        			生产订单进程表
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
***********************************************************/

package market.Mes.OrderManager.Plan.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import market.Api.Mes.impl.Utils;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Mes.Lengthwise.Plan.mapper.PlnMaterielDetailMapper;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderMapper;
import market.Mes.OrderManager.Plan.mapper.PlnProdorderStatisticMapper;
import market.Mes.OrderManager.Plan.service.PlnProdorderStatisticService;
import market.Mes.OrderManager.Plan.vo.PlnProdorder;
import market.Mes.OrderManager.Plan.vo.PlnProdorderStatistic;

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;

@RemoteService(path = "PlnProdorderStatisticService")
public class PlnProdorderStatisticServiceImpl extends BaseServiceImpl<PlnProdorderStatistic, Object>
		implements PlnProdorderStatisticService {

	/**
	 * 更新生产订单统计量(生产完成量,入库量,发运量,结算量)
	 * 
	 * 必传字段 prod_order_no 生产订单号 
	 * 新增的时候就传正数 撤销的时候传负数 选填量 shipped 发运量 settleed 结算量 producted 生产订单完成量
	 * 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public void update_Pord_Stats(PlnProdorderStatistic pos) {
		if (Utils.isNotEmpty(pos) || Utils.isNotEmpty(pos.getProd_order_no())) {
			this.getMapper(PlnProdorderStatisticMapper.class).update_Pord_Stats(pos);
		}
	}

	/**
	 * 更新生产订单状态 如果统计量满足溢短装量则修改状态
	 * 
	 * 0PAA14 投料 0PAA15 生产中 0PAA20 生产完成 0PAA50 发运完成 0PAA80 结算完成
	 * 
	 * @param prod_order_no
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public void update_Pord_Status(String prod_order_no) {
		// 获取生产订单进程信息
		List<PlnProdorderStatistic> ppos = this.getMapper(PlnProdorderStatisticMapper.class).findWithCondition(null,
				" prod_order_no = '" + prod_order_no + "'", "", 0, 1);
		// 获取生产订单信息
		List<PlnProdorder> pps = this.getMapper(PlnProdorderMapper.class).findWithCondition(null,
				"prod_order_no = '" + prod_order_no + "'", "", 0, 1);
		// 交货重量下限(溢短装)
		Double delivery_error_min = 0d, dsned = 0d;
		delivery_error_min = pps.get(0).getDelivery_error_min();
		// 获取是否已结算
		if (ppos.get(0).getSettleed() != null && ppos.get(0).getSettleed() >= delivery_error_min) {
			pps.get(0).setP_status(pps.get(0).getStatus());
			pps.get(0).setStatus("0PAA80");
			// 是否发运完成
		} else if (ppos.get(0).getShipped() != null && ppos.get(0).getShipped() >= delivery_error_min) {
			pps.get(0).setP_status(pps.get(0).getStatus());
			pps.get(0).setStatus("0PAA50");
			// 是否生产完成
		} else if (ppos.get(0).getProducted() != null && ppos.get(0).getProducted() > 0) {
			pps.get(0).setP_status(pps.get(0).getStatus());
			if (ppos.get(0).getProducted() >= delivery_error_min) {
				pps.get(0).setStatus("0PAA20");
			} else {
				pps.get(0).setStatus("0PAA15");
			}
			
		} else {
		
				
				// 获取已设计量
				dsned = ppos.get(0).getAn_dsn() == null ? ppos.get(0).getLw_dsn() == null
						? ppos.get(0).getRl_dsn() == null ? ppos.get(0).getSr_dsn() == null
								? ppos.get(0).getCl_dsn() == null ? ppos.get(0).getPc_dsn() : ppos.get(0).getCl_dsn()
								: ppos.get(0).getSr_dsn() : ppos.get(0).getRl_dsn()
						: ppos.get(0).getLw_dsn() : ppos.get(0).getAn_dsn();
				// 充当量
			    dsned = dsned == null ? 0 : dsned ;
			    dsned +=ppos.get(0).getReplaced() == null ? 0 : ppos.get(0).getReplaced();
				if (dsned >= 0) {
					pps.get(0).setP_status(pps.get(0).getStatus());
					// 已投料
					pps.get(0).setStatus("0PAA14");
				}
		}
		this.getMapper(PlnProdorderMapper.class).update(pps.get(0));

	}

	/**
	 * 上料修改生产订单状态
	 * 
	 * @param object_no  投料卷号
	 * @param flag       ture 上料 false 取消上料
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public void updateProdSta(String object_no, boolean flag) {
		// 获取库存信息
		YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(object_no);
		if (Utils.isNotEmpty(ypd) && Utils.isNotEmpty(ypd.getProdorderno())) {
			// 获取生产订单信息
			List<PlnProdorder> ppo = this.getMapper(PlnProdorderMapper.class).findWithCondition(null,
					" prod_order_no = '" + ypd.getProdorderno() + "'", "", 0, 1);
			if (Utils.isNotEmpty(ppo)) {
				// 上料
				if (flag) {
					if ("0PAA15".equals(ppo.get(0).getStatus())) {
						return;
					} else {
						ppo.get(0).setP_status(ppo.get(0).getStatus());
						ppo.get(0).setStatus("0PAA15");
						this.getMapper(PlnProdorderMapper.class).update(ppo.get(0));
					}
					// 取消上料
				} else {
					// 如果存在订单对应的虚拟物料信息有实物并且状态like03
					int count = 0;
					count = this.getMapper(PlnMaterielDetailMapper.class).countWithCondition(null, " prod_order_no = '"
							+ ypd.getProdorderno() + "' and object_no is not null and status like '%03'");
					if (count > 0) {
						return;
					} else {
						ppo.get(0).setP_status("0PAA15");
						// 已投料
						ppo.get(0).setStatus("0PAA14");
						this.getMapper(PlnProdorderMapper.class).update(ppo.get(0));
					}
				}
			}
		}
	}
	
	
	/**
	 * 关闭生产订单
	 * 
	 * @param order_no 订单号 = contract_no + order_seq + contract_line_seq
	 * @param flag     true 关闭 flase 取消关闭
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public void Prod_Over(String order_no, Boolean flag) {
		if (Utils.isNotEmpty(order_no)) {
			// 获取订单下的所有生产订单(目前1对1 --2019-07-18)
			List<PlnProdorder> list = this.getMapper(PlnProdorderMapper.class).findWithCondition(null,
					"order_no = '" + order_no + "'", "", 0, 0);
			for (PlnProdorder pln : list) {
				// 修改生产订单状态
				if (flag) {
					pln.setP_status(pln.getStatus());
					pln.setStatus("0PAA99");
				} else {
					pln.setStatus(pln.getP_status());
					pln.setP_status("0PAA99");
				}
				this.getMapper(PlnProdorderMapper.class).update(pln);
			}
		}
	}

	/**
	 * 生产订单统计 统计量并修改生产订单状态
	 * 
	 * @param object_no 物料号成品卷( Y..... )
	 * @param type      操作类型 1 交工 2入库 3 发运 3 结算
	 * @param flag      true 新增 flase 回撤
	 * 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public void prod_Stats(String object_no, int type, boolean flag) {
		// 获取库存信息
		YdmProductDetail ypd = this.getMapper(YdmProductDetailMapper.class).findById(object_no);
		if (Utils.isNotEmpty(ypd) && Utils.isNotEmpty(ypd.getProdorderno())) {
			Double wgt = 0d;
			int cnt = 0;
			if (flag) {
				wgt = ypd.getFactweight();
				cnt = 1;
			} else {
				wgt = -ypd.getFactweight();
				cnt = -1;
			}
			PlnProdorderStatistic pos = new PlnProdorderStatistic();
			pos.setProd_order_no(ypd.getProdorderno());
			switch (type) {
			case 1:
				pos.setProducted(wgt);
				pos.setProducted_cnt(cnt);
				break;
			case 2:
				pos.setStocked(wgt);
				pos.setStocked_cnt(cnt);
				break;
			case 3:
				pos.setShipped(wgt);
				pos.setShipped_cnt(cnt);
				break;
			case 4:
				pos.setSettleed(wgt);
				pos.setSettleed_cnt(cnt);
				break;

			default:
				break;
			}
			update_Pord_Stats(pos);
			if (type != 2) {
				update_Pord_Status(ypd.getProdorderno());
			}
		}
	}

	/**
	 * 生产订单管理报表导出
	 */
	public ResultModel doExportProdorder(CommonPage<PlnProdorder> sum) {
		ResultModel rm = new ResultModel();
		try {
			// 1，创建一个webbook，对应一个Excel文件
			WritableWorkbook workbook;
			// 2,设置用户下载路径
			String path = this.getRequest().getServletContext().getRealPath("/") + "excel" + File.separator; // 临时保存路径
			File dir = new File(path);
			if (!dir.exists()) {
				new File(path).mkdir();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat stdSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String sTime = sum.getStartTime();
			if (sTime != null && sTime.length() > 1) {
				Date sDate = sdf.parse(sTime);
				sTime = sdf.format(sDate);
			}
			String eTime = sum.getEndTime();
			if (eTime != null && eTime.length() > 1) {
				Date eDate = sdf.parse(eTime);
				eTime = sdf.format(eDate);
			}
			String filename = sTime + "至" + eTime + "生产订单管理报表";
			String file = filename + ".xls"; // 文件名
			// 3. 操作EXCEL文件
			workbook = Workbook.createWorkbook(new File(path + file));
			WritableSheet sheet = workbook.createSheet(filename, 0);
			// 去掉整个sheet中的网格线
//            sheet.getSettings().setShowGridLines(false);  
			// 行高
			sheet.getSettings().setDefaultRowHeight(300);
			// 列宽
			sheet.setColumnView(0, 5);
			sheet.setColumnView(1, 18);
			sheet.setColumnView(2, 22);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 18);
			sheet.setColumnView(5, 15);
			sheet.setColumnView(6, 15);
			sheet.setColumnView(7, 15);
			sheet.setColumnView(8, 10);
			sheet.setColumnView(9, 10);
			sheet.setColumnView(10, 10);
			sheet.setColumnView(11, 10);
			sheet.setColumnView(12, 10);
			sheet.setColumnView(13, 15);
			sheet.setColumnView(14, 15);
			sheet.setColumnView(20, 15);
			sheet.setColumnView(23, 15);
			sheet.setColumnView(24, 15);
			sheet.setColumnView(26, 20);
			sheet.setColumnView(27, 20);
			// 字体 参数可自行配置
			WritableFont font1 = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false,
					UnderlineStyle.NO_UNDERLINE);
			WritableCellFormat cellFormat1 = new WritableCellFormat(font1);
			cellFormat1.setAlignment(Alignment.CENTRE);
			cellFormat1.setVerticalAlignment(VerticalAlignment.CENTRE);
			// THICK粗线 thin 细线
//			cellFormat1.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THICK,jxl.format.Colour.BLACK); 
			// 表头
			sheet.addCell(new Label(0, 0, "序号", cellFormat1));
			sheet.addCell(new Label(1, 0, "合同号", cellFormat1));
			sheet.addCell(new Label(2, 0, "订单号", cellFormat1));
			sheet.addCell(new Label(3, 0, "客户名称", cellFormat1));
			sheet.addCell(new Label(4, 0, "订单属性", cellFormat1));
			sheet.addCell(new Label(5, 0, "订单状态", cellFormat1));
			sheet.addCell(new Label(6, 0, "重量", cellFormat1));
			sheet.addCell(new Label(7, 0, "工艺路径", cellFormat1));
			sheet.addCell(new Label(8, 0, "牌号", cellFormat1));
			sheet.addCell(new Label(9, 0, "厚", cellFormat1));
			sheet.addCell(new Label(10, 0, "宽", cellFormat1));
			sheet.addCell(new Label(11, 0, "单重上限", cellFormat1));
			sheet.addCell(new Label(12, 0, "单重下限", cellFormat1));
			sheet.addCell(new Label(13, 0, "交货重量上限", cellFormat1));
			sheet.addCell(new Label(14, 0, "交货重量下限", cellFormat1));
			sheet.addCell(new Label(15, 0, "分条规格", cellFormat1));
			sheet.addCell(new Label(16, 0, "切边方式", cellFormat1));
			sheet.addCell(new Label(17, 0, "横切方式", cellFormat1));
			sheet.addCell(new Label(18, 0, "收货单位", cellFormat1));
			sheet.addCell(new Label(19, 0, "交货日期", cellFormat1));
			sheet.addCell(new Label(20, 0, "创建人", cellFormat1));
			sheet.addCell(new Label(21, 0, "创建时间", cellFormat1));
			sheet.addCell(new Label(22, 0, "产品形态", cellFormat1));
			sheet.addCell(new Label(23, 0, "标准号", cellFormat1));
			sheet.addCell(new Label(24, 0, "交货状态", cellFormat1));
			sheet.addCell(new Label(25, 0, "特殊要求", cellFormat1));
			sheet.addCell(new Label(26, 0, "销售备注", cellFormat1));
			sheet.addCell(new Label(27, 0, "加工计划备注", cellFormat1));

			WritableFont font = new WritableFont(WritableFont.ARIAL, 11, WritableFont.NO_BOLD, false,
					UnderlineStyle.NO_UNDERLINE);
			WritableCellFormat cellFormat = new WritableCellFormat(font);
			cellFormat.setAlignment(Alignment.CENTRE);
			cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
//			cellFormat.setBorder(Border.ALL,BorderLineStyle.THIN,Colour.BLACK);

			// 获取查询结果
			rm = this.getBean(PlnProdorderServiceImpl.class).doQueryWeb(sum);
			if ("500".equals(rm.getState()))
				return rm;
			PageModel<PlnProdorder> pm = (PageModel<PlnProdorder>) rm.getData();
			List<PlnProdorder> list = (List<PlnProdorder>) pm.getRows();
			Double total_weight = 0d;
			for (int v = 0; v < list.size(); v++) {
				PlnProdorder main = list.get(v);
				sheet.addCell(new Label(0, v + 2, "" + (v + 1), cellFormat));
				if (main.getContract_no() != null) {
					sheet.addCell(new Label(1, v + 2, main.getContract_no(), cellFormat));
				}
				if (main.getOrder_no() != null) {
					sheet.addCell(new Label(2, v + 2, main.getOrder_no(), cellFormat));
				}
				if (main.getCustomer_name() != null) {
					sheet.addCell(new Label(3, v + 2, main.getCustomer_name(), cellFormat));
				}
				if (main.getOrder_nature_desc() != null) {
					sheet.addCell(new Label(4, v + 2, main.getOrder_nature_desc(), cellFormat));
				}
				String status_content = "";
				if ("0PAA10".equals(main.getStatus()))
					status_content = "订单已接收";
				if ("0PAA12".equals(main.getStatus()))
					status_content = "订单下发";
				if ("0PAA20".equals(main.getStatus()))
					status_content = "订单完成";
				sheet.addCell(new Label(5, v + 2, status_content, cellFormat));
				if (main.getEstimate_weight() != null) {
					sheet.addCell(new Label(6, v + 2, String.valueOf(main.getEstimate_weight()), cellFormat));
					total_weight += main.getEstimate_weight().doubleValue();

				}
				if (main.getWhole_process_names() != null) {
					sheet.addCell(new Label(7, v + 2, main.getWhole_process_names(), cellFormat));
				}
				if (main.getSteel_name() != null) {
					sheet.addCell(new Label(8, v + 2, main.getSteel_name(), cellFormat));
				}
				if (main.getThick() != null) {
					sheet.addCell(new Label(9, v + 2, main.getThick().toString(), cellFormat));
				}
				if (main.getWidth() != null) {
					sheet.addCell(new Label(10, v + 2, main.getWidth().toString(), cellFormat));
				}
				if (main.getSingle_weight_max() != null) {
					sheet.addCell(new Label(11, v + 2, String.valueOf(main.getSingle_weight_max()), cellFormat));
				}
				if (main.getSingle_weight_min() != null) {
					sheet.addCell(new Label(12, v + 2, String.valueOf(main.getSingle_weight_min()), cellFormat));
				}
				if (main.getDelivery_error_max() != null) {
					sheet.addCell(new Label(13, v + 2, String.valueOf(main.getDelivery_error_max()), cellFormat));
				}
				if (main.getDelivery_error_min() != null) {
					sheet.addCell(new Label(14, v + 2, String.valueOf(main.getDelivery_error_min()), cellFormat));
				}
				if (main.getCut_style() != null) {
					sheet.addCell(new Label(15, v + 2, main.getCut_style(), cellFormat));
				}
				if (main.getCut_edge_type_name() != null) {
					sheet.addCell(new Label(16, v + 2, main.getCut_edge_type_name(), cellFormat));
				}
				if (main.getCrosscut_style() != null) {
					sheet.addCell(new Label(17, v + 2, main.getCrosscut_style(), cellFormat));
				}
				if (main.getReciver_unit_name() != null) {
					sheet.addCell(new Label(18, v + 2, main.getReciver_unit_name(), cellFormat));
				}
				if (main.getDeliver_date() != null) {
					String str = sdf.format(main.getDeliver_date());
					sheet.addCell(new Label(19, v + 2, str, cellFormat));
				}
				if (main.getCreate_man_name() != null) {
					sheet.addCell(new Label(20, v + 2, main.getCreate_man_name(), cellFormat));
				}
				if (main.getCreate_time() != null) {
					String create_time = stdSdf.format(main.getCreate_time());
					sheet.addCell(new Label(21, v + 2, create_time, cellFormat));
				}
				if (main.getProd_cls_name() != null) {
					sheet.addCell(new Label(22, v + 2, main.getProd_cls_name(), cellFormat));
				}
				if (main.getStd_name() != null) {
					sheet.addCell(new Label(23, v + 2, main.getStd_name(), cellFormat));
				}
				if (main.getDelivery_state_desc() != null) {
					sheet.addCell(new Label(24, v + 2, main.getDelivery_state_desc(), cellFormat));
				}
				sheet.addCell(new Label(25, v + 2, "", cellFormat)); // 暂未取值 特殊要求
				if (main.getOrder_memo() != null) {
					sheet.addCell(new Label(26, v + 2, main.getOrder_memo(), cellFormat));
				}
				if (main.getProcessMemo() != null) {
					sheet.addCell(new Label(27, v + 2, main.getProcessMemo(), cellFormat));
				}
			}
			sheet.addCell(new Label(0, list.size() + 2, "合计", cellFormat1));

			sheet.addCell(new Label(14, list.size() + 2, String.valueOf(total_weight), cellFormat));
			sheet.getSettings().setVerticalFreeze(1); // 首行冻结
			sheet.getSettings().setVerticalFreeze(2);

			// 关闭
			workbook.write();
			workbook.close();

			rm.setData("/download?filename=" + file);
			rm.setState("200");
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo(ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}
}
