package com.steering.pss.ydm.Stuffmanage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.StringTool;
import com.steering.pss.ydm.Stuffmanage.Entity.MatGpMEntity;
import com.steering.pss.ydm.base.MeanValueCalculation;
import com.steering.pss.ydm.entity.MatZcMEntity1;

public class FrmStuffAdjust extends DBCommon{

	/***
	 * 查询调差实绩
	 * @param parm
	 * @param startTim
	 * @param endTim
	 * @param arr
	 * @return
	 */
	public CoreReturnObject doQueryStock(ArrayList<String> parm,String startTim,String endTim,String[] arr)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmStuffAdjust.doQueryStock");
		if(!startTim.equals(""))
		{
			sql += " AND STOCKTAKING_TIME >= to_date('"+startTim+"','YYYY-MM-DD HH24:MI:SS') AND STOCKTAKING_TIME <= to_date('"+endTim+"','YYYY-MM-DD HH24:MI:SS')";
		}
		sql += CoreConverter.toSqlConditionString("STORAGE_NO", arr);
		return this.getData(sql, parm.toArray());
	}
	
	/***
	 * 调差
	 * @param parm
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doAddAdjust(ArrayList<String> parm,String strBound,String userName,String mangeNo,String mangement,String departId,String departMent)
	{
		CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        Date now = new Date();
 	   SimpleDateFormat dateFormat = new SimpleDateFormat(
        "yyyyMM");
 	  SimpleDateFormat df = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm:ss");
         String systime = dateFormat.format(now);
         String time = df.format(now);
        PreparedStatement psta = null;
        String sql = "";
        ResultSet rs = null;
        String acount = "";
        
        double adjustWgt = 0;//总量
        int count = 0;//总支数
        String oldWgt = "";//原重量
        try {
			connection.setAutoCommit(false); // 取消自动提交事务
			String updateMatWgt = CoreXmlSqlParsersFactory.getSql("FrmStuffAdjust.updateActWgt");
			PreparedStatement updateMatWgtpsta = connection.prepareStatement(updateMatWgt);
			String insertAdjustSql = CoreXmlSqlParsersFactory.getSql("FrmStuffAdjust.insertAdjust");
			PreparedStatement insertAdjustpsta = connection.prepareStatement(insertAdjustSql);
			for(String str:parm)
			{
				int n=0;
				MatGpMEntity matGpList = EntityTool.getEntityByJSONStr(str, MatGpMEntity.class);
				String adjustDoc = queryAdjustDoc(connection,strBound,"TC");
				sql = CoreXmlSqlParsersFactory.getSql("FrmStuffAdjust.selectMatStaus");
				psta = connection.prepareStatement(sql);
				psta.setString(1, matGpList.getStoveNo());
				psta.setString(2, matGpList.getJudgeStoveNo());
				psta.setString(3, matGpList.getBatchNo());
				psta.setString(4, matGpList.getGroudNo());
				psta.setString(5, matGpList.getProductFlag());
				psta.setString(6, matGpList.getMatStatus());
				psta.setString(7, matGpList.getStorageNo());
				rs = psta.executeQuery();
				if(rs.next())
				{
					acount= rs.getString("ACOUNT");
					oldWgt = rs.getString("WEIGHT");
				}
				rs.close();
				psta.close();
				if(Integer.parseInt(acount) != Integer.parseInt(matGpList.getActCount()))
				{
					cro.setV_errMsg("材料状态发生了变化,请刷新页面!");
					return cro;
				}
				adjustWgt = Double.parseDouble(matGpList.getAdjustActWeight())+Double.parseDouble(oldWgt);
				count = Integer.parseInt(acount);
				 ArrayList<String>  storeWgtList = new ArrayList<String>();
					List<double[]> listwgt = MeanValueCalculation
							.MeanCalculation(adjustWgt, 
									count);// 重量
					for (int k = 0; k < listwgt.size(); k++) {
						double[] conLen = listwgt.get(k);
						if ((int) conLen[0] > 0) {
							for (int x = 0; x < (int) conLen[0]; x++) {
								DecimalFormat dt = new DecimalFormat(
										"0.000");
								storeWgtList.add(dt.format(conLen[1])
										.toString());
							}
						}
					}
					sql = CoreXmlSqlParsersFactory.getSql("FrmStuffAdjust.selectMatNo");
					psta = connection.prepareStatement(sql);
					psta.setString(1, matGpList.getStoveNo());
					psta.setString(2, matGpList.getJudgeStoveNo());
					psta.setString(3, matGpList.getBatchNo());
					psta.setString(4, matGpList.getGroudNo());
					psta.setString(5, matGpList.getProductFlag());
					psta.setString(6, matGpList.getMatStatus());
					psta.setString(7, matGpList.getStorageNo());
					rs = psta.executeQuery();
					List<MatGpMEntity> matZcEntity = EntityTool
					.getEntitysByRs(rs, MatGpMEntity.class);
                   rs.close();
                   psta.close();
					if(matZcEntity == null)
					{
						 cro.setV_errMsg("不存在需要调差的炉批库存信息!");
	                	 return cro;
					}
					for(MatGpMEntity matGplist:matZcEntity)
					{
						updateMatWgtpsta.setString(1,storeWgtList.get(n));
						updateMatWgtpsta.setObject(2, matGplist.getMatNo());
						updateMatWgtpsta.addBatch();
						n++;
					}
					insertAdjustpsta.setObject(1, matGpList.getBelongName());
					insertAdjustpsta.setObject(2, matGpList.getProOrderNo());
					insertAdjustpsta.setObject(3, matGpList.getProOrderId());
					insertAdjustpsta.setObject(4, time);
					insertAdjustpsta.setObject(5, matGpList.getStorageNo());
					insertAdjustpsta.setObject(6, matGpList.getStorageNo()+"100101");
					insertAdjustpsta.setObject(7, matGpList.getStorageAttr());
					insertAdjustpsta.setObject(8, matGpList.getStorageAttrName());
					insertAdjustpsta.setObject(9, matGpList.getStorageTypeNo());
					insertAdjustpsta.setObject(10, matGpList.getStorageTypeName());
					insertAdjustpsta.setObject(11, departId);
					insertAdjustpsta.setObject(12, departMent);
					insertAdjustpsta.setObject(13, mangeNo);
					insertAdjustpsta.setObject(14, mangement);
					insertAdjustpsta.setObject(15, systime);
					insertAdjustpsta.setObject(16, matGpList.getMemo());
					insertAdjustpsta.setObject(17, userName);
					insertAdjustpsta.setObject(18, time);
					insertAdjustpsta.setObject(19, querySendSql(connection, adjustDoc));
					insertAdjustpsta.setObject(20, adjustDoc);
					insertAdjustpsta.setObject(21, strBound);
					insertAdjustpsta.setObject(22, "量差调整");
					insertAdjustpsta.setObject(23, "");
					insertAdjustpsta.setObject(24, matGpList.getStocktakingRsnName());
					insertAdjustpsta.setObject(25, matGpList.getProductFlag());
					insertAdjustpsta.setObject(26, matGpList.getMatStatus());
					insertAdjustpsta.setObject(27, matGpList.getStoveNo());
					insertAdjustpsta.setObject(28, matGpList.getFlagStoveNo());
					insertAdjustpsta.setObject(29, matGpList.getLotNo());
					insertAdjustpsta.setObject(30, matGpList.getJudgeStoveNo());
					insertAdjustpsta.setObject(31, matGpList.getGroudNo());
					insertAdjustpsta.setObject(32, matGpList.getBatchNo());
					insertAdjustpsta.setObject(33, matGpList.getCastNo());
					insertAdjustpsta.setObject(34, matGpList.getCcmid());
					insertAdjustpsta.setObject(35, matGpList.getSampleFlag());
					insertAdjustpsta.setObject(36, matGpList.getCuttingFlag());
					insertAdjustpsta.setObject(37, matGpList.getCuttingNum());
					insertAdjustpsta.setObject(38, matGpList.getMaterialNo());
					insertAdjustpsta.setObject(39, matGpList.getMaterialName());
					insertAdjustpsta.setObject(40, matGpList.getProduccode());
					insertAdjustpsta.setObject(41, matGpList.getProducname());
					insertAdjustpsta.setObject(42, matGpList.getJudgeGradecode());
					insertAdjustpsta.setObject(43, matGpList.getJudgeGradename());
					insertAdjustpsta.setObject(44, matGpList.getJudgeStdCode());
					insertAdjustpsta.setObject(45, matGpList.getJudgeStdName());
					insertAdjustpsta.setObject(46, matGpList.getActDimater());
					insertAdjustpsta.setObject(47, matGpList.getActHeight());
					insertAdjustpsta.setObject(48, matGpList.getActLen());
					insertAdjustpsta.setObject(49, matGpList.getActLenMin());
					insertAdjustpsta.setObject(50, matGpList.getActLenMax());
					insertAdjustpsta.setObject(51, matGpList.getActFixNum());
					insertAdjustpsta.setObject(52, matGpList.getActFixLen());
					insertAdjustpsta.setObject(53, "0");
					insertAdjustpsta.setObject(54, matGpList.getAdjustActWeight());
					insertAdjustpsta.setObject(55, "0");
					insertAdjustpsta.setObject(56, matGpList.getPlineCode());
					insertAdjustpsta.setObject(57, matGpList.getPlineName());
					insertAdjustpsta.setObject(58, matGpList.getBelongCode());
					insertAdjustpsta.addBatch();
			}
			updateMatWgtpsta.executeBatch();
			insertAdjustpsta.executeBatch();
			connection.commit();
			cro.setV_errMsg("调差成功!");
        }
	   	catch (Exception e) {
            System.out.println(e.getMessage());
            if (connection != null) {
                try {
                	cro.setV_errMsg(e.getMessage());
                    connection.rollback(); // 回滚事务 
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
	}
	
	/**
     * 每支材料对应的调差单号
     * @param conn c
     * @param strlist 传递参数
     * @return obj
     * @throws Exception 异常处理
     */
    public String queryAdjustDoc(Connection conn, String strlist,String memo)
            throws Exception {
        int seq = 0;
         PreparedStatement psta = null;
         Date dt = new Date();
         SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
         SimpleDateFormat matter2 = new SimpleDateFormat("yyMMdd");
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmStuffAdjust.queryAdjustList");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1, matter1.format(dt));
        psta.setString(2, strlist);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            String res = rs.getString(1);
            if (res == null) {
                res = memo + matter2.format(dt) + "00001";
            }
            else {
                seq = Integer.parseInt(res.substring(8, 13));
            }
        }
        rs.close();
        psta.close();
        return  memo + matter2.format(dt) + StringTool.formatDecimal(++seq, "00000");
    }
    
    /***
     * 每支材料对应的调查（调差）流水号
     * @param conn
     * @param strlist
     * @param strType
     * @return
     * @throws Exception
     */
    public String querySendSql(Connection conn, String strlist)  throws Exception {
        int seq = 0;
        PreparedStatement psta = null;
        Date dt = new Date();
        SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmStuffAdjust.queryAdjustList1");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1,matter1.format(dt));
        psta.setString(2,strlist);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            String res = rs.getString(1);
            if (res == null) {
                res = strlist + "0001";
            }
            else {
                seq = Integer.parseInt(res.substring(13, 17));
            }
        }
        rs.close();
        psta.close();
        return strlist + StringTool.formatDecimal(++seq, "0000");
    }
}
