/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2020-01-08
 * 描述            ：新钢销售委托合同信息表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Slm.OrderManagement.impl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import market.Com.mapper.ComBaseInfoMapper;
import market.Com.mapper.ComBaseSteelMapper;
import market.Com.pb.PbMethod;
import market.Com.vo.ComBaseInfo;
import market.Com.vo.ComBaseSteel;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Lms.Warehouse.mapper.YdmProductDetailMapper;
import market.Lms.Warehouse.vo.YdmProductDetail;
import market.Qms.metallurgy.mapper.ComBaseStdMapper;
import market.Qms.metallurgy.vo.ComBaseStd;
import market.Slm.ContractManagement.mapper.SlmContractHeatInfoMapper;
import market.Slm.ContractManagement.mapper.SlmContractLineInfoMapper;
import market.Slm.ContractManagement.vo.SlmContractHeatInfo;
import market.Slm.ContractManagement.vo.SlmContractLineInfo;
import market.Slm.OrderManagement.mapper.IfSlmContractInfoMapper;
import market.Slm.OrderManagement.service.IfSlmContractInfoService;
import market.Slm.OrderManagement.vo.Ctbl02CoilCommD;
import market.Slm.OrderManagement.vo.IfSlmContractInfo;
import market.Slm.OrderManagement.vo.IfTbl02CoilComm;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
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;
import com.ibm.icu.util.Calendar;

@Service("IfSlmContractInfoService")
@RemoteService(path="IfSlmContractInfoService")
public class IfSlmContractInfoServiceImpl extends BaseServiceImpl<IfSlmContractInfo,Object> implements IfSlmContractInfoService {
	
	/**
	 * 销售合同查询中间表
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQuaryIfSlmContractInfo(CommonPage<IfSlmContractInfo> cp) throws Exception {
		ResultModel rm = new ResultModel();
		IfSlmContractInfo isci = cp.getObject();
		int pageSize = cp.getPageSize();
		int pageIndex = cp.getPageIndex();
		PageModel<IfSlmContractInfo> pm = new PageModel<IfSlmContractInfo>(pageIndex, pageSize);
		if (cp.getStartTime()==null || "".equals(cp.getStartTime())) {
			throw new Exception("开始时间不能为空");
		}
		if (cp.getEndTime()==null || "".equals(cp.getEndTime())) {
			throw new Exception("结束时间不能为空");
		}
		
		String condition = "";
		if (isci.getContract_no()!=null && !"".equals(isci.getContract_no())) { //合同号
			condition += " and t.contract_no like '%"+isci.getContract_no()+"%'";
		}
		if (isci.getStatus()!=null && !"".equals(isci.getStatus())) { //状态
			condition += " and t.status = '"+isci.getStatus()+"'";
		}
		if (cp.getStartTime()!=null && !"".equals(cp.getStartTime())) {
			condition += " and t.create_time >= to_date('"+cp.getStartTime()+"','yyyy-MM-dd HH24:mi:ss')";
		}
		if (cp.getEndTime()!=null && !"".equals(cp.getEndTime())) {
			condition += " and t.create_time <= to_date('"+cp.getEndTime()+"','yyyy-MM-dd HH24:mi:ss')";
		}
		List<IfSlmContractInfo> list = this.getMapper(IfSlmContractInfoMapper.class).doQuaryIfSlmContractInfo(condition,(pageIndex - 1) * pageSize,pageIndex * pageSize);
		int count = this.getMapper(IfSlmContractInfoMapper.class).doQuaryIfSlmContractInfoCount(condition);
		pm.setRows(list);
		pm.setTotal(count);
		rm.setState("200");
		rm.setData(pm);
		return  rm;
	}
	
	
	/**
	 * 生成
	 * @param sum
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doAddIfSlmContractInfo(CommonPage<IfSlmContractInfo> cp) throws Exception{
		ResultModel rm=new ResultModel();
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		Date now = new Date();
		List<IfSlmContractInfo> sciList = cp.getObjectList();
		if (sciList==null || sciList.size()<=0) {
			throw new Exception("请传入参数");
		}
		String year = Calendar.getInstance().get(Calendar.YEAR)+"";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date sign_date = sdf.parse(sdf.format(now));					//签订日期		
		Double tax_rate = 0d;											//税率
		ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById("950902");
		if (cbi!=null) {
			tax_rate = Double.parseDouble(cbi.getBase_name());
		}
		
		try{
			for (IfSlmContractInfo sci : sciList) {
				//获取中间表的合同行信息
				IfSlmContractInfo isci = this.getMapper(IfSlmContractInfoMapper.class).doQuaryUniqueIfSlmContractInfo(sci.getContract_no(),sci.getContract_line_no());
				if (isci==null) {
					rm.setState("500");
					rm.setMsgInfo("未找到合同号【"+sci.getContract_no()+"】的中间表数据");
					return rm;
				}
				//判断优特钢的合同表中是否存在当前合同
				SlmContractHeatInfo schi = new SlmContractHeatInfo();
				schi.setContract_no(sci.getContract_no());
				schi.setValid_flag("1");
				int count = this.getMapper(SlmContractHeatInfoMapper.class).count(schi);
				if (count == 0) {
					//不存在
					// ************** 1.新增合同头信息  ********************
					SlmContractHeatInfo sc = new SlmContractHeatInfo();
					String strContractPk=new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
					sc.setContract_pk(strContractPk+PbMethod.RandomCreate(3));//合同PK
					int mNo=this.getMapper(SlmContractHeatInfoMapper.class).countWithCondition(null, " substr(manage_no,0,6)='"+strContractPk.substring(0,6)+"'")+1;
					sc.setManage_no(strContractPk.substring(0,6)+String.format("%04d", mNo));//管理卡号
					sc.setContract_no(isci.getContract_no());
					sc.setContract_type_no("101607");//合同类型
					sc.setContract_type_name("委托加工合同");
					sc.setIs_order_contract("0");//是否为意向合同
					sc.setCustomer_no("1001901000000000926Q");//客户
					sc.setCustomer_name("新余钢铁集团有限公司");
					sc.setCustomer_abr("新钢集团");//客户简称
					sc.setTrade_type_no("100801");//合同贸易类型
					sc.setTrade_type_name("内贸");
					sc.setSupply_unit_no("20180122102823908069");//供货单位
					sc.setSupply_unit_name("新余新钢优特钢带有限公司");
					sc.setBalance_unit_no("1001901000000000926Q");//结算单位
					sc.setBalance_unit_name("新余钢铁集团有限公司");
					sc.setOrder_unit_no("1001901000000000926Q");//订货单位
					sc.setOrder_unit_name("新余钢铁集团有限公司");
					sc.setPrice_type_no("101801");//计价方式
					sc.setPrice_type_name("锁价");
					sc.setTax_total_price(isci.getOrder_price1());//合同含税总价
					sc.setNot_tax_total_price(isci.getOrder_price2());//合同不含税总价
					sc.setIs_tax("1");//是否含税
					sc.setCurrency_no("101901");//币种
					sc.setCurrency_name("人民币");
					sc.setPayment_type_no("102001");//付款方式
					sc.setPayment_type_name("现款和银行承兑");
					sc.setSale_org_no("20171218221814830158");//销售组织
					sc.setSale_org_name("新余新钢优特钢带有限公司");
					sc.setSale_area_no("0004");//销售区域
					sc.setSale_area_name("新余周边");
					sc.setFrist_bill_unit("新余钢铁集团有限公司");//首次受票单位
					sc.setLegal_man("夏文勇");//法人代表
					sc.setBack("工行新钢办");//开户银行
					sc.setAddress("江西省新余市冶金路");//
					sc.setTax_registra_number("913605001583084437");//纳税人识别号
					sc.setTelphone("0790-6294175");//开票电话
					sc.setAccount("1505202109022100106");//账号
					sc.setPhone(null);//联系电话
					sc.setFax(null);//传真
					sc.setZip_code("338000");//邮编
					sc.setContract_year(year);					
					sc.setContract_flag_no("102101");//合同状态编码
					sc.setContract_flag_name("编辑");
					sc.setEffect_man_no(userId);//生效人编码
					sc.setEffect_man_name(userName);
					sc.setMake_price_type_no("102201");//定价方式
					sc.setMake_price_type_name("采购价");
					sc.setIs_control_payment("0");
					sc.setSign_date(sign_date);//签订日期
					sc.setSign_address("江西新余");//签订地点
					sc.setEffec_start_date(sign_date);//有效开始时间
					//sc.setEffec_end_date(effec_end_date);//有效结束时间
					sc.setValid_flag("1");
					sc.setCreate_man_no(userId);
					sc.setCreate_man_name(userName);
					sc.setCreate_time(now);
					sc.setTax_rate(tax_rate);//税率
					sc.setDeliver_date(isci.getDeliver_date());//交货日期
					sc.setSupplier_address("新钢公司创效路");//供货地址
					sc.setHave_control("0");//是否已有资金控制???
					this.getMapper(SlmContractHeatInfoMapper.class).insert(sc);
					
					//2. ********************* 新增合同行信息  **************************
					ResultModel rm1 = doInsertIfSlmContractInfo(isci,sc);	
					if (rm1.getState()==null || !"200".equals(rm1.getState())) {
						rm.setState("500");
						rm.setMsgInfo("新增合同行失败:"+rm1.getMsgInfo());
						return rm;
					}
				}else {
					//存在，则生成合同行信息
					//1.找到合同头信息
					SlmContractHeatInfo sc = new SlmContractHeatInfo();
					sc.setContract_no(isci.getContract_no());
					sc.setValid_flag("1");
					List<SlmContractHeatInfo> scList = this.getMapper(SlmContractHeatInfoMapper.class).find(sc, 0, 0);
					if (scList==null || scList.size()<=0) {
						rm.setState("500");
						rm.setMsgInfo("未找到有效的合同头信息");
						return rm;
					}
					sc = scList.get(0);
					ResultModel rm1 = doInsertIfSlmContractInfo(isci,sc);	
					if (rm1.getState()==null || !"200".equals(rm1.getState())) {
						rm.setState("500");
						rm.setMsgInfo("新增合同行失败:"+rm1.getMsgInfo());
						return rm;
					}
				}				
				//修改中间表的status为3
				sci.setStatus("3");
				this.getMapper(IfSlmContractInfoMapper.class).doUpdateIfSlmContractInfoStatus(sci);
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("");
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}
	
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertIfSlmContractInfo(IfSlmContractInfo isci,SlmContractHeatInfo sc){
		String userId=(String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName=(String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		SlmContractLineInfo scli = new SlmContractLineInfo();
		scli.setContract_line_no(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) );//合同行号
		scli.setContract_line_seq(isci.getContract_line_no());//001 中间表的合同行号
		scli.setContract_pk(sc.getContract_pk());//合同号
		scli.setContract_no(sc.getContract_no());
		/*scli.setPsc(psc);//产品规范
		scli.setPsc_desc(psc_desc);
		scli.setMsc(msc);//冶金规范
		scli.setMsc_desc(msc_desc);
		scli.setMsc_type_no(msc_type_no);//冶金规范类型
		scli.setMsc_type_name(msc_type_name);*/
		scli.setUse_code("STD0000010000");//用途编码
		scli.setUse_desc("/");//   
		scli.setProd_cls_no("405007");//品种分类
		scli.setProd_cls_name("带材");
		//scli.setProd_code(prod_code);
		scli.setProd_name(isci.getProd_name());//品名
		//TODO 根据品名获取品名编码
		scli.setProd_code(isci.getProd_code());
		
		scli.setStd_name(isci.getStd_name());//标准
		ComBaseStd std = new ComBaseStd();
		std.setStdName(isci.getStd_name());
		std.setValidflag("1");
		List<ComBaseStd> stdList = this.getMapper(ComBaseStdMapper.class).find(std, 0, 0);
		if (stdList==null || stdList.size()<=0) {
			rm.setState("500");
			rm.setMsgInfo("未找到优特钢系统中存在合同号【"+sc.getContract_no()+"】对应的标准【"+isci.getStd_name()+"】");
			return rm;
		}
		scli.setStd_code(stdList.get(0).getStdCode());
		
		scli.setSteel_name(isci.getSteel_name());//牌号
		ComBaseSteel cbs = new ComBaseSteel();
		cbs.setSteel_name(isci.getSteel_name());
		cbs.setValidflag("1");
		List<ComBaseSteel> cbsList = this.getMapper(ComBaseSteelMapper.class).find(cbs, 0, 0);
		if (cbsList==null || cbsList.size()<=0) {
			rm.setState("500");
			rm.setMsgInfo("未找到优特钢系统中存在合同号【"+sc.getContract_no()+"】对应的牌号【"+isci.getSteel_name()+"】");
			return rm;
		}
		scli.setSteel_code(cbsList.get(0).getSteel_code());
		
		scli.setProd_figure_no("405007");//产品形态(默认 带材？)
		scli.setProd_figure_name("带材");
		scli.setEstimate_weight(isci.getEstimate_weight());//暂估重量
		//scli.setDelivery_weight_type(delivery_weight_type);//交货量差方式“0“
		scli.setDelivery_error_max(isci.getDelivery_error_max());//交货量误差上线
		scli.setDelivery_error_min(isci.getDelivery_error_min());//交货量误差下线
		scli.setWeight_type_no("102302");//计重方式
		scli.setWeight_type_name("毛重");
		scli.setSingle_weight_max(isci.getSingle_weight_max());//单支上限
		scli.setSingle_weight_min(isci.getSingle_weight_min());//单支下限
		scli.setSingle_weight_unit_no("100306");//计量单位
		scli.setSingle_weight_unit_name("t");
		scli.setOrder_price1(isci.getOrder_price1());//订货价
		scli.setOut_price(0d);//出厂价
		scli.setBalnce_price(0d);//结算价
		scli.setTrade_price(0d);//运费
		scli.setHoist_price(0d);//吊装费
		scli.setMeasure_price(0d);//测算价
		scli.setCut_edge_type_no(isci.getCut_edge_type_no());//切边方式
		scli.setCut_edge_type_name(isci.getCut_edge_type_name());
		scli.setDiameter_inn_unit_no("100304");
		scli.setDiameter_inn_unit_name("mm");
		scli.setDiameter_out_unit_no("100304");
		scli.setDiameter_out_unit_name("mm");
		scli.setThick(isci.getThick());//厚
		scli.setThick_unit_no("100304");
		scli.setThick_unit_name("mm");
		scli.setWidth(isci.getWidth());//宽
		scli.setWidth_unit_no("100304");
		scli.setWidth_unit_name("mm");
		scli.setLine_flag_no("102601");//当前合同行状态
		scli.setLine_flag_name("编辑");
		scli.setIs_lock("0");//锁定状态
		scli.setIs_prod_line(isci.getIs_prod_line());//是否指定产线
		scli.setValid_flag("1");//有效标识
		scli.setCreate_man_no(userId);
		scli.setCreate_man_name(userName);
		scli.setCreate_time(new Date());
		scli.setEstimate_weight_unit_no("100306");
		scli.setEstimate_weight_unit_name("t");
		scli.setDelivery_unit_no("100306");
		scli.setDelivery_unit_name("t");
		scli.setDelivery_state_code(isci.getDelivery_state_code());//交货状态
		scli.setDelivery_state_desc(isci.getDelivery_state_desc());
		scli.setSolutions_no("202001090002");//运输方案
		scli.setSolutions_name("优特到冷轧");
		scli.setIs_tax("1");//是否含税
		scli.setTax_rate(sc.getTax_rate());
		scli.setOrder_price2(isci.getOrder_price2());//订货价：不含税
		scli.setCurrency_no("101901");
		scli.setCurrency_name("人民币");
		scli.setDelivery_error_rate(10d);
		scli.setPrecisicon_type_code(isci.getPrecisicon_type_code());//精度类型 PT.A
		scli.setPrecisicon_type_desc(isci.getPrecisicon_type_desc());
		scli.setPk_ask_code(isci.getPk_ask_code());//包装要求
		scli.setPk_ask_desc(isci.getPk_ask_desc());
		this.getMapper(SlmContractLineInfoMapper.class).insert(scli);
		rm.setState("200");
		rm.setMsgInfo("新增合同行成功");
		return rm;
	}
	
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doRemoveIfSlmContractInfo(CommonPage<IfSlmContractInfo> cp) throws Exception{
		ResultModel rm=new ResultModel();
		List<IfSlmContractInfo> sciList = cp.getObjectList();
		if (sciList==null || sciList.size()<=0) {
			throw new Exception("请传入参数");
		}
		 				
		try{
			for (IfSlmContractInfo sci : sciList) {
				//判断能否操作
				SlmContractLineInfo scli = new SlmContractLineInfo();
				scli.setContract_no(sci.getContract_no());
				scli.setContract_line_seq(sci.getContract_line_no());
				scli.setValid_flag("1");
				List<SlmContractLineInfo> scList = this.getMapper(SlmContractLineInfoMapper.class).find(scli, 0, 0);
				if (scList!=null && scList.size()>0) {
					for (SlmContractLineInfo sc : scList) {
						if (!"102601".equals(sc.getLine_flag_no())) {
							rm.setState("500");
							rm.setMsgInfo("该合同不处于编辑状态，无法取消生成");
							return rm;
						}
					}
				}
				
				//删除
				this.getMapper(IfSlmContractInfoMapper.class).deleteScliByIfSlmContractInfo(sci);
				//修改中间表的status为3
				sci.setStatus("2");
				this.getMapper(IfSlmContractInfoMapper.class).doUpdateIfSlmContractInfoStatus(sci);
			}
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("");
			ex.printStackTrace();
			throw ex;
		}
		return rm;
	}
	
	
	
	
	
	
	/**
	 * 线程获取销售系统的数据
	 */
	@Override
	public void doGetSlmContractInfo() {
		List<IfSlmContractInfo> list = doQaurySlmContractInfo();
		if (list!=null && list.size()>0) {
			for (IfSlmContractInfo isci : list) {
				//执行新增
				this.getMapper(IfSlmContractInfoMapper.class).doInsertIfSlmContractInfo(isci);
				//执行修改
				doUpdateSlmContractInfo(isci.getContract_line_no(), isci.getContract_no());
			}
		}
	}
	
	/**
	 * 建立销售二级的连接
	 * @return
	 */
	public Connection getConnection(){
		Connection conn=null;		  
		try {
//			String url="jdbc:oracle:thin:@10.10.0.8:1521:sqmesdb";
			// 新连接：
			String url="jdbc:oracle:thin:@172.16.0.136:20000:sqmesdb";
			String user="xg3q";
			String password="xg3q123";			  
			Class.forName("oracle.jdbc.driver.OracleDriver");//加载数据驱动
			conn = DriverManager.getConnection(url, user, password);// 连接数据库		  
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("加载数据库驱动失败");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("连接数据库失败");
		}
		return conn;
	}
	
	/**
	 * 关闭连接
	 * @param rs
	 * @param conn
	 * @param stmt
	 */
	public void close(ResultSet rs, Connection conn, Statement stmt) {
		try {
			if (rs != null)
				rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (stmt != null)
				stmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询销售2级新发的数据
	 */
	public List<IfSlmContractInfo> doQaurySlmContractInfo(){		 
		Connection connection = getConnection();
		List<IfSlmContractInfo> list = new ArrayList<IfSlmContractInfo>();
		//准备sql语句
		String sql = "select t.* from if_slm_contract_info t where t.status in ('0','')";
		//创建语句传输对象
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {			
			preparedStatement = connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			while(resultSet.next()) {
				IfSlmContractInfo isci = new IfSlmContractInfo();
				isci.setContract_line_no(resultSet.getString("CONTRACT_LINE_NO"));
				isci.setContract_no(resultSet.getString("CONTRACT_NO"));
				isci.setCustomer_name(resultSet.getString("CUSTOMER_NAME"));
				isci.setTax_total_price(resultSet.getDouble("TAX_TOTAL_PRICE"));
				isci.setNot_tax_total_price(resultSet.getDouble("NOT_TAX_TOTAL_PRICE"));
				String deliverDate = resultSet.getString("DELIVER_DATE");
				if (deliverDate!=null && !"".equals(deliverDate)) {					
					isci.setDeliver_date(sdf.parse(deliverDate));					
				}
				isci.setProd_code(resultSet.getString("PROD_CODE"));
				isci.setProd_name(resultSet.getString("PROD_NAME"));
				isci.setStd_name(resultSet.getString("STD_NAME"));
				isci.setSteel_name(resultSet.getString("STEEL_NAME"));
				isci.setContract_quantity(resultSet.getDouble("CONTRACT_QUANTITY"));
				isci.setEstimate_weight(resultSet.getDouble("ESTIMATE_WEIGHT"));
				isci.setDelivery_error_max(resultSet.getDouble("DELIVERY_ERROR_MAX"));
				isci.setDelivery_error_min(resultSet.getDouble("DELIVERY_ERROR_MIN"));
				isci.setSingle_weight(resultSet.getDouble("SINGLE_WEIGHT"));
				isci.setSingle_weight_max(resultSet.getDouble("SINGLE_WEIGHT_MAX"));
				isci.setSingle_weight_min(resultSet.getDouble("SINGLE_WEIGHT_MIN"));
				isci.setOrder_price1(resultSet.getDouble("ORDER_PRICE1"));;
				isci.setThick(resultSet.getDouble("THICK"));
				isci.setWidth(resultSet.getDouble("WIDTH"));
				isci.setMemo(resultSet.getString("MEMO"));
				isci.setDelivery_state_desc(resultSet.getString("DELIVERY_STATE_DESC"));
				isci.setPrecisicon_type_desc(resultSet.getString("PRECISICON_TYPE_DESC"));
				isci.setLv_desc(resultSet.getString("LV_DESC"));
				isci.setPk_ask_code(resultSet.getString("PK_ASK_CODE"));
				isci.setPk_ask_desc(resultSet.getString("PK_ASK_DESC"));
				list.add(isci);	
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			close(resultSet, connection, preparedStatement);
		}		
		return list;	
	}
 
	/**
	 * 修改销售2级数据
	 */
	public int doUpdateSlmContractInfo(String contract_line_no,String contract_no){		 
		Connection connection = getConnection();
		int num = 0;
		//准备sql语句
		String sql = "update if_slm_contract_info set status = '2' where contract_line_no =? and contract_no =?";
		//创建语句传输对象
		PreparedStatement preparedStatement = null;
		try {			
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, contract_line_no); //合同行号
			preparedStatement.setString(2, contract_no);//合同号
			num = preparedStatement.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, connection, preparedStatement);
		}		
		return num;	
	}
	
	//1.插入优特钢代加工成品公共表成功
	public ResultModel doInsertIfCoil(IfTbl02CoilComm t) {
		 ResultModel rm = new ResultModel();		 
		 Connection connection=getConnection();
	     String sql="insert into if_tbl02_coil_comm(old_sampl_no,instr_coil_thk,instr_coil_wth,instr_coil_len,devlmt_dtime,ordcust_cd,"
	     		+ "coil_len,coil_thk,coil_wth,act_wgt,ord_no,ord_seq,stl_grd,ingr_dec_grd,extshape_dec_grd,size_dec_rst,matlqlty_dec_grd,"
	     		+ "tot_dec_grd,mill_dtime,smp_no,h_coil_no1,package_fl,package_level,package_reg,package_dtime,line_tp,coil_no,coil_stat,"
	     		+ "cur_prog_cd,cur_prog_cd_dtime,cur_prog_cd_pgm,ord_fl,cur_load_loc,spec_abbsym,spec_stl_grd,slab_no,ord_use_cd,extshape_quality) "
	     		+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	     PreparedStatement preparedStatement = null;
	     try {	    	 
	    	 preparedStatement = connection.prepareStatement(sql);
	         preparedStatement.setString(1, t.getOld_sampl_no());
	         preparedStatement.setDouble(2, t.getInstr_coil_thk());
	         preparedStatement.setDouble(3, t.getInstr_coil_wth());
	         preparedStatement.setDouble(4, t.getInstr_coil_len()==null?0d:t.getInstr_coil_len());
	         preparedStatement.setString(5, t.getDevlmt_dtime());
	         preparedStatement.setString(6, t.getOrdcust_cd());
	         preparedStatement.setDouble(7, t.getCoil_len()==null?0d:t.getCoil_len());
	         preparedStatement.setDouble(8, t.getCoil_thk()==null?0d: t.getCoil_thk());
	         preparedStatement.setDouble(9, t.getCoil_wth()==null?0d:t.getCoil_wth());//
	         preparedStatement.setDouble(10, t.getAct_wgt()==null?0d:t.getAct_wgt());//
	         preparedStatement.setString(11, t.getOrd_no());//预留3
	         preparedStatement.setString(12, t.getOrd_seq());//成品卷号
	         preparedStatement.setString(13, t.getStl_grd());//标准号
	         preparedStatement.setString(14, t.getIngr_dec_grd());//订单宽度(mm)
	         preparedStatement.setString(15, t.getExtshape_dec_grd());//订单厚度(mm)
	         preparedStatement.setString(16, t.getSize_dec_rst());//热卷重量(kg)
	         preparedStatement.setString(17, t.getMatlqlty_dec_grd());//热卷长度(m)
	         preparedStatement.setString(18, t.getTot_dec_grd());
	         preparedStatement.setString(19, t.getMill_dtime());
	         preparedStatement.setString(20, t.getSmp_no());
	         preparedStatement.setString(21, t.getH_coil_no1());
	         preparedStatement.setString(22, t.getPackage_fl());
	         preparedStatement.setString(23, t.getPackage_level());
	         preparedStatement.setString(24, t.getPackage_reg());
	         preparedStatement.setString(25, t.getPackage_dtime());
	         preparedStatement.setString(26, "S");
	         preparedStatement.setString(27, t.getCoil_no());
	         preparedStatement.setString(28, "2");
	         preparedStatement.setString(29, t.getCur_prog_cd());
	         preparedStatement.setString(30, t.getCur_prog_cd_dtime());
	         preparedStatement.setString(31, "YTGCP");
	         preparedStatement.setString(32, t.getOrd_fl());
	         preparedStatement.setString(33, t.getCur_load_loc());
	         preparedStatement.setString(34, t.getSpec_abbsym());
	         preparedStatement.setString(35, t.getSpec_stl_grd());
	         preparedStatement.setString(36, t.getSlab_no());
	         preparedStatement.setString(37, t.getOrd_use_cd());
	         preparedStatement.setString(38, t.getExtshape_quality());//外观等级
	         preparedStatement.executeUpdate();
	         
	   } catch (SQLException e) {
       		rm.setState("500");
            e.printStackTrace();
       }finally{
       	close(null, connection, preparedStatement);
       }
	     System.out.println("插入优特钢代加工成品公共表成功");	         
	     rm.setState("200");
	     rm.setMsgInfo("插入销售成本表成功");
	     return rm;
	}
	
	//2.冷轧酸轧成品公共表
	public ResultModel doInsertIfCoilC(IfTbl02CoilComm t) {
		 ResultModel rm = new ResultModel();		 
		 Connection connection=getConnection();
	     String sql="insert into c_tbl02_coil_comm(old_sampl_no,instr_coil_thk,instr_coil_wth,instr_coil_len,devlmt_dtime,ordcust_cd,"
	     		+ "coil_len,coil_thk,coil_wth,act_wgt,ord_no,ord_seq,stl_grd,ingr_dec_grd,extshape_dec_grd,size_dec_rst,matlqlty_dec_grd,"
	     		+ "tot_dec_grd,mill_dtime,smp_no,h_coil_no1,package_fl,package_level,package_reg,package_dtime,line_tp,coil_no,coil_stat,"
	     		+ "cur_prog_cd,cur_prog_cd_dtime,cur_prog_cd_pgm,ord_fl,cur_load_loc,spec_abbsym,spec_stl_grd,slab_no,ord_use_cd,extshape_quality) "
	     		+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	     PreparedStatement preparedStatement = null;
	     try {	    	 
	    	 preparedStatement = connection.prepareStatement(sql);
	         preparedStatement.setString(1, t.getOld_sampl_no());
	         preparedStatement.setDouble(2, t.getInstr_coil_thk());
	         preparedStatement.setDouble(3, t.getInstr_coil_wth());
	         preparedStatement.setDouble(4, t.getInstr_coil_len()==null?0d:t.getInstr_coil_len());
	         preparedStatement.setString(5, t.getDevlmt_dtime());
	         preparedStatement.setString(6, t.getOrdcust_cd());
	         preparedStatement.setDouble(7, t.getCoil_len()==null?0d:t.getCoil_len());
	         preparedStatement.setDouble(8, t.getCoil_thk()==null?0d: t.getCoil_thk());
	         preparedStatement.setDouble(9, t.getCoil_wth()==null?0d:t.getCoil_wth());//
	         preparedStatement.setDouble(10, t.getAct_wgt()==null?0d:t.getAct_wgt());//	        
	         preparedStatement.setString(11, t.getOrd_no());//预留3
	         preparedStatement.setString(12, t.getOrd_seq());//成品卷号
	         preparedStatement.setString(13, t.getStl_grd());//标准号
	         preparedStatement.setString(14, t.getIngr_dec_grd());//订单宽度(mm)
	         preparedStatement.setString(15, t.getExtshape_dec_grd());//订单厚度(mm)
	         preparedStatement.setString(16, t.getSize_dec_rst());//热卷重量(kg)
	         preparedStatement.setString(17, t.getMatlqlty_dec_grd());//热卷长度(m)
	         preparedStatement.setString(18, t.getTot_dec_grd());
	         preparedStatement.setString(19, t.getMill_dtime());
	         preparedStatement.setString(20, t.getSmp_no());
	         preparedStatement.setString(21, t.getH_coil_no1());
	         preparedStatement.setString(22, t.getPackage_fl());
	         preparedStatement.setString(23, t.getPackage_level());
	         preparedStatement.setString(24, t.getPackage_reg());
	         preparedStatement.setString(25, t.getPackage_dtime());
	         preparedStatement.setString(26, "S");
	         preparedStatement.setString(27, t.getCoil_no());
	         preparedStatement.setString(28, "2");
	         preparedStatement.setString(29, t.getCur_prog_cd());
	         preparedStatement.setString(30, t.getCur_prog_cd_dtime());
	         preparedStatement.setString(31, "YTGCP");
	         preparedStatement.setString(32, t.getOrd_fl());
	         preparedStatement.setString(33, t.getCur_load_loc());
	         preparedStatement.setString(34, t.getSpec_abbsym());
	         preparedStatement.setString(35, t.getSpec_stl_grd());
	         preparedStatement.setString(36, t.getSlab_no());
	         preparedStatement.setString(37, t.getOrd_use_cd());
	         preparedStatement.setString(38, t.getExtshape_quality());//外观等级
	         preparedStatement.executeUpdate();	         
	   } catch (SQLException e) {
      		rm.setState("500");
           e.printStackTrace();
      }finally{
      	close(null, connection, preparedStatement);
      }
	     System.out.println("插入冷轧酸轧成品公共表成功");	         
	     rm.setState("200");
	     rm.setMsgInfo("插入冷轧酸轧成品公共表成功");
	     return rm;
	}
	
	// 3.插入优特钢代加工成品公共表成功
	public ResultModel doInsertCtbl02CoilCommD(Ctbl02CoilCommD t) {
		 ResultModel rm = new ResultModel();		 
		 Connection connection=getConnection();
	     String sql="insert into C_TBL02_COIL_COMM_D(l_coil_no,cut_seq,ord_thk,ord_wth,ord_wgt,ord_wgt_min,ord_wgt_max,ord_no,ord_seq,ord_fl) "
	     		+ "values (?,?,?,?,?,?,?,?,?,?)";	     
	     PreparedStatement preparedStatement = null;
	     try {	    	 
	    	 preparedStatement = connection.prepareStatement(sql);
	         preparedStatement.setString(1, t.getL_coil_no());
	         preparedStatement.setString(2, t.getCut_seq());
	         preparedStatement.setDouble(3, t.getOrd_thk()==null?0:t.getOrd_thk());
	         preparedStatement.setDouble(4, t.getOrd_wth()==null?0:t.getOrd_wth());
	         preparedStatement.setDouble(5, t.getOrd_wgt()==null?0:t.getOrd_wgt());
	         preparedStatement.setDouble(6, t.getOrd_wgt_min()==null?0:t.getOrd_wgt_min());
	         preparedStatement.setDouble(7, t.getOrd_wgt_max()==null?0:t.getOrd_wgt_max());
	         preparedStatement.setString(8, t.getOrd_no());
	         preparedStatement.setString(9, t.getOrd_seq());//
	         preparedStatement.setString(10, t.getOrd_fl());//	        	         
	         preparedStatement.executeUpdate();	         
	   } catch (SQLException e) {
     		rm.setState("500");
          e.printStackTrace();
     }finally{
     	close(null, connection, preparedStatement);
     }
	     System.out.println("插入优特钢代加工成品公共表成功");	         
	     rm.setState("200");
	     rm.setMsgInfo("插入优特钢代加工成品公共表成功");
	     return rm;
	}
	
	//4.更新冷轧系统的原料表成功
	public ResultModel doUpdateC_tbk02_coil_comm(IfTbl02CoilComm t) {
		 ResultModel rm = new ResultModel();		 
		 Connection connection=getConnection();
	     String sql="update c_tbk02_coil_comm t set "
	     		+ "t.COIL_STAT = '3',"
	     		+ "t.CUR_LOAD_LOC='', "
	     		+ "t.TRNF_DTIME=to_char(sysdate,'yyyymmdd'),"
	     		+ "t.TRNF_USE_TIME=to_char(sysdate, 'yyyymmddhhmiss'), "
	     		+ "t.TRNF_REG='YTGCP' "
	     		+ "WHERE T.OLD_SAMPL_NO =?";	     
	     PreparedStatement preparedStatement = null;
	     try {	    	 
	    	 preparedStatement = connection.prepareStatement(sql);
	         preparedStatement.setString(1, t.getH_coil_no1());	                 	         
	         preparedStatement.executeUpdate();
	         
	   } catch (SQLException e) {
    		rm.setState("500");
         e.printStackTrace();
	   }finally{
		   close(null, connection, preparedStatement);
	   }
	     System.out.println("更新冷轧系统的原料表成功");	         
	     rm.setState("200");
	     rm.setMsgInfo("更新冷轧系统的原料表成功");
	     return rm;
	} 
			
	//5.调整垛位表
	public ResultModel doUpdatec_tbk08_coil_yard(IfTbl02CoilComm t) {
		 ResultModel rm = new ResultModel();		 
		 Connection connection=getConnection();
	     String sql="update c_tbk08_coil_yard t set t.COIL_NO='' where t.COIL_NO =?";	     
	     PreparedStatement preparedStatement = null;
	     try {	    	 
	    	 preparedStatement = connection.prepareStatement(sql);
	         preparedStatement.setString(1, t.getH_coil_no1());	                 	         
	         preparedStatement.executeUpdate();
	     } catch (SQLException e) {
    		rm.setState("500");
    		e.printStackTrace();
	     }finally{
	    	 close(null, connection, preparedStatement);
	     }
	     System.out.println("调整垛位表成功");	         
	     rm.setState("200");
	     rm.setMsgInfo("调整垛位表成功");
	     return rm;
	}
	
	/**
	 * 冷轧撤销：数据退回优特钢系统，需要进行(退火轧制..)加工
	 * @param t
	 * @return
	 */
	public ResultModel doCancelCtbl02CoilCommD(CommonPage<Ctbl02CoilCommD> cp) {
		 ResultModel rm = new ResultModel();
		 String username = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		 String coilno = cp.getMemo1();
		 ComBaseInfo cbi = this.getMapper(ComBaseInfoMapper.class).findById("5364");
		 if (cbi==null || StringUtils.isEmpty(cbi.getMemo()) || !cbi.getMemo().contains(username)) {
			rm.setMsgInfo("登录账号无权限进行此操作,请联系管理员");
			rm.setState("500");
			return rm;
		 }
		 
		 Connection connection=getConnection();
	     PreparedStatement preparedStatement = null;//判断是否下票	    
	     ResultSet resultSet = null;
	     try {	 
	    	 String sql="select count(1) from c_tbl02_coil_comm t where t.coil_no = ? and t.dliv_dirno is null";	     
	    	 preparedStatement = connection.prepareStatement(sql);
	    	 preparedStatement.setString(1, coilno); //卷号
	    	 resultSet = preparedStatement.executeQuery();
	    	 while(resultSet.next()) {
	    		 PreparedStatement preparedStatement2 = null;//执行更新
	    		 try {
	    			 //1、执行冷轧更新逻辑
	    			 String sql2 = "update c_tbl02_coil_comm t set t.cur_prog_cd='CCC', t.coil_stat='3',"
	 	    		 		+ " t.trnf_dtime= to_char(sysdate,'yyyyMMdd'), t.out_yard_kind='1', t.fl ='1' "
	 	    		 		+ " where t.coil_no = ? and t.dliv_dirno is null";
	    			 preparedStatement2 = connection.prepareStatement(sql2);
		    		 preparedStatement2.setString(1, coilno);
		    		 preparedStatement2.executeUpdate();
		    		 //2、更新库存状态为待入库
		    		 YdmProductDetail ypd = new YdmProductDetail();
		    		 ypd.setCoilno(coilno);
		    		 ypd.setState("-1");
		    		 this.getMapper(YdmProductDetailMapper.class).update(ypd);
	    		 } catch (Exception e) {
	    			 rm.setState("500");
	    			 rm.setMsgInfo("更新冷轧失败");
	    	    	 e.printStackTrace();
	    		 } finally{
	    	    	 close(null, null, preparedStatement2);
	    	     }	    		 
	    	 }     
	     } catch (SQLException e) {
    		rm.setState("500");
    		e.printStackTrace();
	     } finally{
	    	 close(resultSet, connection, preparedStatement);
	     }
	     System.out.println("退回优特钢MES成功");	         
	     rm.setState("200");
	     rm.setMsgInfo("退回优特钢MES成功");
	     return rm;
	}
	
	public ResultModel doUpdateC_TBL02_COIL_COMM_ROUTE(String matCoilNo, String route) {
		 ResultModel rm = new ResultModel();		 
		 Connection connection=getConnection();
		 rm.setState("200");
		 rm.setMsgInfo("返写冷轧委托加工接收状态成功");
	     String sql="update C_TBL02_COIL_COMM t set t.ROUTE="+ route +" where t.COIL_NO =?";	     
	     PreparedStatement preparedStatement = null;
	     try {	    	 
	    	 preparedStatement = connection.prepareStatement(sql);
	         preparedStatement.setString(1, matCoilNo);	                 	         
	         preparedStatement.executeUpdate();
	     } catch (SQLException e) {
	   		rm.setState("500");
	   		rm.setMsgInfo("返写冷轧委托加工接收状态失败");
	   		e.printStackTrace();
	     }finally{
	    	 close(null, connection, preparedStatement);
	     }
	     System.out.println("返写冷轧委托加工接收状态成功");	         
	     
	     
	     return rm;
	} 
}
