package com.seeyon.apps.src_ordinary.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.util.JDBCAgent;

public class OrdinaryDaoImpl implements IOrdinaryDao{

	private static final Log log = LogFactory.getLog(OrdinaryDaoImpl.class);
	
	private String getOrdinaryCodes = "select field0249 as CONTRACTCODE from formmain_3757 where field0249 like ? ";
//	private String getOrdinaryCodes = "select field0249 as CONTRACTCODE from formmain_3738 where field0249 like ? ";
//	private String getOrdinaryCodes = "select field0221 from formmain_0037 where field0221 like ? ";
	
	private String updateOrdinaryCodes = "update formmain_3757 set field0249 = ? where field0115 = ?";
//	private String updateOrdinaryCodes = "update formmain_3738 set field0249 = ? where field0115 = ?";
	
	@Override
	public List<String> getOrdinaryCodes(String unitCode) {
		JDBCAgent agent = new JDBCAgent();
		List<String> contractCodes = new ArrayList<String>();
		try {
			StringBuilder sql = new StringBuilder(getOrdinaryCodes);
			List<Object> p = new ArrayList<Object>();
			p.add(unitCode+"%");
			System.out.println(sql);
			System.out.println(unitCode);
			agent.execute(sql.toString(), p);
			List<Map> list = agent.resultSetToList();
			System.out.println(list);
			if(list.size()>0) {
				for (Map map : list) {
					System.out.println(map);
					String  contractSerial = map.get("contractcode").toString().
							substring(map.get("contractcode").toString().length()-3);
					contractCodes.add(contractSerial);
				}
			}
		} catch (BusinessException e) {
			log.info(e);
			e.printStackTrace();
		} catch (SQLException e) {
			log.info(e);
			e.printStackTrace();
		}finally {
			if (agent != null) {
				agent.close();
			}
		}
		return contractCodes;
	}

	@Override
	public int updateOrdinaryCodes(String contractCodes,String oanum) {
		JDBCAgent agent = new JDBCAgent();
		int i = 0;
		try {
			StringBuilder sql = new StringBuilder(updateOrdinaryCodes);
			List<Object> p = new ArrayList<Object>();
			p.add(contractCodes);
			p.add(oanum);
			agent.execute(sql.toString(), p);
//			List<Map> list = agent.resultSetToList();
			i=agent.execute(sql.toString(), p);
		} catch (BusinessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			if (agent != null) {
				agent.close();
			}
		}
		return i;
	}
	
	
	
}
