package com.steering.pss.ydm.pipemanage;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.data.ComBaseInfo;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;
import com.steering.pss.ydm.entity.MatZcMEntity;
import com.steering.pss.ydm.entity.XOMatZcMinfoEntity;
import com.steering.pss.ydm.entity.YdmZcOutlistEntity;
import com.steering.pss.ydm.entity.YdmZcStocktakinglistEntity;
import org.apache.commons.beanutils.BeanUtils;

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

/**
 * @author TJG 2015-04-30
 */
public class FrmPipeInventoryOut extends DBCommon {

    /**
     * 查询库存实绩
     * @param
     * @return 平台统一返回对象
     */
    public CoreReturnObject getMangement(ArrayList<Object> params,
            String[] stoveages,String supplyUnit) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmPipeInventoryOut.getMangement");
        sql += CoreConverter.toSqlConditionString("T1.BELONG_CODE", stoveages);
        if(!params.get(0).equals(""))
        {
        	sql += " AND T1.INSTOCK_TIME BETWEEN TO_DATE( '"+params.get(0)+"', 'YYYY-MM-DD HH24:MI:SS') AND TO_DATE( '"+params.get(1)+"', 'YYYY-MM-DD HH24:MI:SS')";
        }
        if(!params.get(2).equals(""))
        {
        	sql += " AND T1.JUDGE_STOVE_NO = '"+params.get(2)+"'";
        }
        if(!params.get(3).equals(""))
        {
        	sql += " T2.STORAGE_NO = '"+params.get(3)+"'";
        }
        if(supplyUnit.equals("120501"))
        {
            sql += " AND (T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T1.SUPPLY_UNIT_CODE IS NULL)";
        }else if(supplyUnit.equals("120504")){
            sql += " AND T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
        }
        sql += " GROUP BY T1.BELONG_CODE,T1.BELONG_NAME,T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.PRODUCT_FLAG,T1.MAT_STATUS,T1.SPEC_CODE,T1.SPEC_NAME,"
                + "T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,T1.PRODUCCODE,T1.PRODUCNAME,T1.MATERIAL_NO,T1.MATERIAL_NAME,T1.STEELCODE,T1.STEELNAME,"
                + "T1.STD_CODE,T1.STD_NAME,T1.ORDER_NO,T1.ORDER_SEQ,T1.ORDER_SEQ_NO,T1.ORD_PK,T1.ORD_LN_PK,T1.ORD_LN_DLY_PK,T1.PRO_ORDER_NO,T1.PRO_ORDER_ID,"
                + "T1.MEMO,T1.JUDGE_RESULT_CODE,T1.JUDGE_RESULT,T2.STORAGE_NO,T1.MODEL_CODE,T1.MODEL_DESC,T1.STD_STYLE,T1.STD_STYLE_DESC,"
                + "T1.SUPPLY_UNIT_CODE,T1.SUPPLY_UNIT"
                +" ORDER BY T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.ORDER_NO,"
                + "T1.ORDER_SEQ,T1.ORDER_SEQ_NO,MIN(T1.INSTOCK_TIME)";
        return this.getData(sql);
        //T1.LOCK_FLAG,
    }

    /**
     * 查询盘亏信息
     * @param
     * @return 平台统一返回对象
     */
    public CoreReturnObject getOut(ArrayList<Object> params, String[] stoveages,String supplyUnit) {
        String sql = CoreXmlSqlParsersFactory.getSql("FrmPipeInventoryOut.getOut");
        sql += CoreConverter.toSqlConditionString("T1.BELONG_CODE", stoveages);
        if(supplyUnit.equals("120501"))
        {
            sql += " AND (T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T1.SUPPLY_UNIT_CODE IS NULL)";
        }else if(supplyUnit.equals("120504")){
            sql += " AND T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
        }
        sql += " GROUP BY T1.STOCKTAKING_DOC,T1.STOCKTAKING_TYPE_CODE,T1.STOCKTAKING_TYPE_NAME,T1.STOCKTAKING_RSN_CODE,T1.STOCKTAKING_RSN_NAME,T1.LOT_NO, T1.STOVE_NO,"
                + "T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.MATERIAL_NO,T1.MATERIAL_NAME,T1.PRODUCCODE,T1.PRODUCNAME,T1.STD_CODE,T1.STD_NAME,T1.GRADECODE,"
                + "T1.GRADENAME,T1.STEELCODE,T1.STEELNAME,T1.STD_STYLE,T1.STD_STYLE_DESC,T1.SPEC_CODE,T1.SPEC_NAME,T1.MODEL_CODE,T1.MODEL_DESC,T1.PLINE_CODE,"
                + "T1.PLINE_NAME,T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.ACT_LEN,T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,T1.BELONG_CODE,T1.BELONG_NAME,T1.LOCATION_NO,T1.STORAGE_ATTR,T1.BAL_YEAR_MONTH,"
                + "T1.STORAGE_ATTR_NAME,T1.STORAGE_TYPE_NO,T1.STORAGE_TYPE_NAME,T1.APPROVAL_FLAG,T1.MEMO,T1.CREATE_NAME, T1.STORAGE_NO,T2.STORAGE_NAME ORDER BY T1.STOCKTAKING_DOC, MIN(T1.CREATE_TIME) ";
        return this.getData(sql, params.toArray());
    }

    /**
     * 盘亏操作
     * @param matzcMEntity
     * @param params
     * @return CoreReturnObject
     */
    public CoreReturnObject InventoryOut(MatZcMEntity matzcMEntity,
            ArrayList<Object> params,String custom) {
        QualityDesignTool.nullConverNullString(matzcMEntity);
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        PreparedStatement ps = null;
        PreparedStatement psXs = null;
        ResultSet rs = null;
        String sql = "";
        int count = Integer.parseInt(params.get(0).toString());
        String reasonCode = params.get(1).toString();
        String reasonName = params.get(2).toString();
        String memo = params.get(3).toString();
        String userName = params.get(4).toString();
        String orderLinePk = params.get(5).toString();
        //String bathYear = params.get(6).toString();
        String bathYear = "120504".equals(matzcMEntity.getSupplyUnitCode())? ComBaseInfo.GetBalYear_2416(new Date()): ComBaseInfo.GetBalYear(new Date());
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss");
        String systime = dateFormat.format(now);
        String processCode = "";
        String processDesc = "";
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            sql = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOut.getMatZcMByInfo");
            if (!matzcMEntity.getOrdLnPk().equals("")) {
                sql = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeInventoryOut.getMageStatusByMononer");
            }
            sql = EntityTool.fillSqlByEntity(sql, matzcMEntity);
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            ArrayList<XOMatZcMinfoEntity> entityList = EntityTool
                    .getEntitysByRs(rs, XOMatZcMinfoEntity.class);
            rs.close();
            ps.close();
            if (entityList == null || entityList.size() == 0) {
                core.setV_errMsg("库存信息已经改变,请刷新数据!");
                return core;
            }
            if (entityList.size() < count) {
                core.setV_errMsg("库存信息已经改变,请刷新数据!");
                return core;
            }
            String outStockDoc = "";
            sql = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOut.getMaxStockTakingDoc");
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            if (rs.next()) {
                outStockDoc = rs.getString("INDEX_SEQ");
            }
            rs.close();
            ps.close();
            
            sql = CoreXmlSqlParsersFactory.getSql("FrmPipeEnter.selectProcess");
            ps = con.prepareStatement(sql);
            ps.setString(1,matzcMEntity.getPlineCode());
            rs = ps.executeQuery();
            if(rs.next())
            {
                processCode = rs.getString("PROCESS_CDOE");
                processDesc = rs.getString("PROCESS_DESC");
            }
            rs.close();
            ps.close();
            if(processCode.equals(""))
            {
                processCode = "D";
                processDesc = "轧制";
            }

            int index = 0;
            DecimalFormat df = new DecimalFormat("0000");
            String sqlDMat = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOut.deleteMatZcMByMatNo");
            String sqlDMatXs = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOutXs.deleteMatZcMByMatNo");
            String sqlDBuress = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOut.deleteYdmZcButtress");
            String sqlOut = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOut.addYdmZcOutlit");
            String sqlOutXs = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOutXs.addYdmZcOutlit");
            String sqlDoc = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeInventoryOut.addStocktakingDoc");
            for (XOMatZcMinfoEntity matZcMInfoEntity : entityList) {
                QualityDesignTool.nullConverNullString(matZcMInfoEntity);
                index++;
                if (index > count) {
                    break;
                }
                String outStockSqe = outStockDoc + df.format(index);
                // 删除库存信息
                ps = con.prepareStatement(sqlDMat);
                ps.setObject(1, matZcMInfoEntity.getMatNo());
                ps.executeUpdate();
                ps.close();
                //删除销售库存信息
                ps = con.prepareStatement(sqlDMatXs);
                ps.setObject(1, matZcMInfoEntity.getMatNo());
                ps.executeUpdate();
                ps.close();
                // 删除位置信息
                ps = con.prepareStatement(sqlDBuress);
                ps.setObject(1, matZcMInfoEntity.getMatNo());
                ps.executeUpdate();
                ps.close();
                // 增加盘亏实绩
                YdmZcStocktakinglistEntity listEntity = new YdmZcStocktakinglistEntity();
                BeanUtils.copyProperties(listEntity, matZcMInfoEntity);
                listEntity.setStocktakingSqe(outStockSqe);
                listEntity.setStocktakingDoc(outStockDoc);
                listEntity.setStocktakingRsnCode(reasonCode);
                listEntity.setStocktakingRsnName(reasonName);
                listEntity.setMemo(memo);
                listEntity.setCreateName(userName);
                listEntity.setStocktakingTypeCode("800602");
                listEntity.setStocktakingTypeName("盘亏");
                listEntity.setBalYearMonth(bathYear);
                listEntity.setStocktakingTime(systime);
                listEntity.setSupplyUnit(matzcMEntity.getSupplyUnit());
                listEntity.setSupplyUnitCode(matzcMEntity.getSupplyUnitCode());
                listEntity.setIsDealer(matZcMInfoEntity.getIsDealer());
                String sqlDocStr = EntityTool.fillSqlByEntity(sqlDoc,
                        listEntity);
                ps = con.prepareStatement(sqlDocStr);
                ps.executeUpdate();
                ps.close();
                // 增加出库实绩
                YdmZcOutlistEntity outEntity = new YdmZcOutlistEntity();
                BeanUtils.copyProperties(outEntity, matZcMInfoEntity);
                outEntity.setOutstockDoc(outStockDoc);
                outEntity.setOutstockSqe(outStockSqe);
                outEntity.setOutstockTypeCode("800802");
                outEntity.setOutstockTypeName("盘亏出库");
                outEntity.setDeliveryNo(matZcMInfoEntity.getOrderSeqNo());
                outEntity.setCreateName(userName);
                outEntity.setMemo(memo);
                outEntity.setBalYearMonth(bathYear);
                outEntity.setSupplyUnitCode(matzcMEntity.getSupplyUnitCode());
                outEntity.setSupplyUnit(matzcMEntity.getSupplyUnit());
                outEntity.setIsDealer(matZcMInfoEntity.getIsDealer());
                outEntity.setProcessCdoe(processCode);
                outEntity.setProcessDesc(processDesc);
                //增加销售库出库实绩
                BeanUtils.copyProperties(outEntity, matZcMInfoEntity);
                outEntity.setOutstockDoc(outStockDoc);
                outEntity.setOutstockSqe(outStockSqe);
                outEntity.setOutstockTypeCode("800802");
                outEntity.setOutstockTypeName("盘亏出库");
                outEntity.setDeliveryNo(matZcMInfoEntity.getOrderSeqNo());
                outEntity.setCreateName(userName);
                outEntity.setMemo(memo);
                outEntity.setBalYearMonth(bathYear);
                outEntity.setSupplyUnitCode(matzcMEntity.getSupplyUnitCode());
                outEntity.setSupplyUnit(matzcMEntity.getSupplyUnit());
                outEntity.setIsDealer(matZcMInfoEntity.getIsDealer());
                outEntity.setProcessCdoe(processCode);
                outEntity.setProcessDesc(processDesc);
                
                String sqlOutStr = EntityTool
                        .fillSqlByEntity(sqlOut, outEntity);
                String sqlOutStrXs = EntityTool
                        .fillSqlByEntity(sqlOutXs, outEntity);
                ps = con.prepareStatement(sqlOutStr);
                ps.executeUpdate();
                ps.close();
                psXs = con.prepareStatement(sqlOutStrXs);
                psXs.executeUpdate();
                psXs.close();

            }
			List<String[]> arrList = queryMatZc(con, orderLinePk, count);
			String[] arr = arrList.get(0);
			sql = CoreXmlSqlParsersFactory
					.getSql("FrmPipeInventoryOut.updateProcessOut");
			ps = con.prepareStatement(sql);
			ps.setString(1, String.valueOf(count));
			ps.setString(2, arr[1]);
			ps.setString(3, arr[2]);
			ps.setString(4, orderLinePk);// 交货行键值
			ps.executeUpdate();
			ps.close();
			core.setV_errMsg("盘亏成功!");
			con.commit();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (con != null) {
                try {
                    con.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return core;
    }
    
    /***
     * 查询盘亏总支数下的总重量、长度
     * @param con
     * @param order_diyPk
     * @param count
     * @return
     */
    public static List<String[]>  queryMatZc(Connection con,String order_diyPk,int count)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("CorePipeInTemp.queryMatZc");
    	PreparedStatement psta;
    	List<String[]> list = new ArrayList<String[]>();
		try {
			psta = con.prepareStatement(sql);
			psta.setString(1, order_diyPk);
			psta.setString(2, String.valueOf(count+1));
	    	ResultSet rs = psta.executeQuery();
	    	if(rs.next())
	    	{
	    		String[] arr = new String[3];
	    		arr[0] = rs.getString("ACT_COUNT");
	    		arr[1] = rs.getString("ACT_WEIGHT");
	    		arr[2] = rs.getString("ACT_LEN");
	    		list.add(arr);
	    	}
	    	rs.close();
	    	psta.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
    	
    	return list;
    }
    
    /***
     * 修改结转年月 
     * @param list
     * @return
     */
    public CoreReturnObject updateYear(ArrayList<String> list)
    {
    	return this.setDataBySqlID("FrmPipeInventoryOut.updateYear", list.toArray());
    }
}
