package com.steering.mes.mcp.Mch;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.db.DBCommon;
import com.steering.mes.mcp.common.PlanService;
import com.steering.mes.mcp.entity.MchEntity.PlnZyJgxMEntity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created by 朱少波 on 2018/9/18.
 */
public class MchComm extends DBCommon {

	/**
	 * 更新长度
	 */
	public CoreReturnObject updateLen(String orderNo, String orderNoSeq ,String BatchGroudNo) {
		CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String Querysql = "select t2.len_min min ,t2.len_max max from SLM_ORDER_HEAD t1,SLM_ORDER_LINE t2\r\n" + 
        		"where\r\n" + 
        		"t1.ord_pk = t2.ord_pk\r\n" + 
        		"and t1.order_no = '"+orderNo+"'\r\n" + 
        		"and t2.order_seq = '"+orderNoSeq+"'";
        PreparedStatement psta = null;
        ResultSet rs = null;
        ResultSet rs2 = null;
        ResultSet rs3 = null;
        String strOrderNo = orderNo+"/"+orderNoSeq;
        try {
        	
        	psta = connection.prepareStatement(Querysql);
        	rs = psta.executeQuery();
        	if(rs.next()) {
        		String min = rs.getString("MIN");
        		String max = rs.getString("MAX");
        	String QueryMchGroupByNoSql = "SELECT COUNT(1) ACOUNT FROM  MCH_GROUPNO T WHERE T.ORDER_NO = '"+strOrderNo+"' AND T.GROUP_MAX = '"+max+"' AND T.GROUP_MIN = '"+min+"' ";
        	psta = connection.prepareStatement(QueryMchGroupByNoSql);
        	rs2 = psta.executeQuery();
        	if(rs2.next() && Integer.parseInt(rs2.getString(1))<1) {
//        		if(Integer.parseInt(rs2.getString("ACOUNT"))> 0) {
//        			 String update = CoreXmlSqlParsersFactory
//								.getSql("MchGroupNo.updateComInfo");
//        			 PreparedStatement 	 updatepsta = connection.prepareStatement(update);
//        			 updatepsta.setString(1, max);
//        			 updatepsta.setString(2, min);
//        			 updatepsta.setString(3, strOrderNo);
//        			 updatepsta.setString(4, BatchGroudNo);
//        			 //updatepsta.addBatch();
//        			 //updatepsta.executeBatch();
//        			 
//        		}
//        		else {
        		String maxGropNo = "select to_char(nvl(max(t.group_no)+1,1),'FM000') maxGropNo from MCH_GROUPNO t WHERE  ORDER_NO = '"+strOrderNo+"'";
        		psta = connection.prepareStatement(maxGropNo);
        		rs3 = psta.executeQuery();
        		if(rs3.next()) {
        			String insert = CoreXmlSqlParsersFactory
							.getSql("MchGroupNo.insertComInfo");
		 			 PreparedStatement 	 insertpsta = connection.prepareStatement(insert);
		 			insertpsta.setString(1, strOrderNo);
		 			insertpsta.setString(2, max);
		 			insertpsta.setString(3, min);
		 			insertpsta.setString(4, rs3.getString(1));
		 			insertpsta.addBatch();
		 			insertpsta.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 HeatPlanId  炉计划ID
     * @param BatchNo 批号
     * @param gx  工序代码
     * @param PlineCode 产线代码
     * @return
     */
    public CoreReturnObject updateDoBeside(String HeatPlanId, String BatchNo, String gx, String PlineCode ) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String updateSql = CoreXmlSqlParsersFactory
                    .getSql("MchComm.doBeside1");// 修改工序状态为结炉
            PreparedStatement updateSqlPsta = connection
                    .prepareStatement(updateSql);
            String updatePln = CoreXmlSqlParsersFactory
                    .getSql("MchComm.doPlnBeside");// 修改计划表结炉状态
            PreparedStatement updatePlnPsta = connection
                    .prepareStatement(updatePln);


            String updatePln1 = CoreXmlSqlParsersFactory
                    .getSql("MchComm.doPlnBeside1");// 修改计划表结炉状态
            PreparedStatement updatePlnPsta1 = connection
                    .prepareStatement(updatePln1);

            String cutFalg = "";
            sql = CoreXmlSqlParsersFactory
                    .getSql("FrmMcpLoading.qureyGxComInfo");// 查询工序是否是结炉状态
            psta = connection.prepareStatement(sql);

            psta.setString(1, HeatPlanId);
            psta.setString(2, BatchNo);
            psta.setString(3, gx);
            rs = psta.executeQuery();
            if (rs.next()) {
                cutFalg = rs.getString("STATION_STATUS");
            }
            else {
                cro.setV_errMsg("无当前工序实绩,无法进行结炉!");
                return cro;
            }
            if (cutFalg.equals("2")) {
                cro.setV_errMsg("已结炉,不允许此操作！");
                return cro;
            }
            rs.close();
            psta.close();

            if(gx.equals("701313")) {

                String Status = "";
                sql = CoreXmlSqlParsersFactory
                        .getSql("MchComm.canBeside");// 查询工序是否是结炉状态
                psta = connection.prepareStatement(sql);

                psta.setString(1, HeatPlanId);
                psta.setString(2, BatchNo);
                rs = psta.executeQuery();
                if (rs.next()) {
                    Status = rs.getString("STATUS");
                }
                else {
                    cro.setV_errMsg("找不到炉次计划!");
                    return cro;
                }

                rs.close();
                psta.close();


                if(Status!=null && Status.equals("0")){
                    cro.setV_errMsg("处置未反馈或者未验证,不允许结炉!");
                    return cro;
                }

                updatePlnPsta1.setString(1, Status);
                updatePlnPsta1.setString(2, HeatPlanId);
                updatePlnPsta1.setString(3, BatchNo);
                updatePlnPsta1.addBatch();
                updatePlnPsta1.executeBatch();

            }else if (gx.equals("701305")){


            }else {

                String LastGx = GetLastGx(gx, PlineCode);
                if (!"".equals(LastGx)) {
                    cutFalg = "";
                    sql = CoreXmlSqlParsersFactory
                            .getSql("FrmMcpLoading.qureyGxComInfo");// 查询工序是否是结炉状态
                    psta = connection.prepareStatement(sql);

                    psta.setString(1, HeatPlanId);
                    psta.setString(2, BatchNo);
                    psta.setString(3, LastGx);
                    rs = psta.executeQuery();
                    if (rs.next()) {
                        cutFalg = rs.getString("STATION_STATUS");
                    } else {
                        cro.setV_errMsg("上工序未结炉,无法结炉");
                        return cro;
                    }
                    if (!cutFalg.equals("2")) {
                        cro.setV_errMsg("上工序未结炉,无法结炉！");
                        return cro;
                    }
                    rs.close();
                    psta.close();
                }


                updatePlnPsta.setString(1, GetBesideStringByGx(gx));
                updatePlnPsta.setString(2, HeatPlanId);
                updatePlnPsta.setString(3, BatchNo);

                updatePlnPsta.addBatch();


                updatePlnPsta.executeBatch();

            }


            updateSqlPsta.setString(1, "2");
            updateSqlPsta.setString(2, "");
            updateSqlPsta.setString(3, HeatPlanId);
            updateSqlPsta.setString(4, BatchNo);
            updateSqlPsta.setString(5, gx);

            updateSqlPsta.addBatch();
            updateSqlPsta.executeBatch();





            cro.setV_errMsg("结炉成功！");
            connection.commit();
        }
        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 HeatPlanId  炉计划ID
     * @param BatchNo 批号
     * @param gx  工序代码
     * @param PlineCode 产线代码
     * @return
     */
    public CoreReturnObject undoBeside(String HeatPlanId, String BatchNo, String gx, String PlineCode) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String updateSql = CoreXmlSqlParsersFactory
                    .getSql("MchComm.doBeside");// 修改工序状态为结炉
            PreparedStatement updateSqlPsta = connection
                    .prepareStatement(updateSql);
            String updatePln = CoreXmlSqlParsersFactory
                    .getSql("MchComm.doPlnBeside");// 修改计划表结炉状态
            PreparedStatement updatePlnPsta = connection
                    .prepareStatement(updatePln);

            String updatePln2 = CoreXmlSqlParsersFactory
                    .getSql("MchComm.doPlnBeside2");// 修改计划表结炉状态
            PreparedStatement updatePlnPsta2 = connection
                    .prepareStatement(updatePln2);

            PlnZyJgxMEntity pln = PlanService.getSendHttPlanCInfo3(connection,
            HeatPlanId,BatchNo);


            //region 检查
            if (pln == null){
                cro.setV_errMsg("找不到炉计划数据！");
                return cro;
            }

            if (pln.getPlanstatus().equals("40")) {
                cro.setV_errMsg("炉计划已经关闭！");
                return cro;
            }

            String cutFalg = "";
            sql = CoreXmlSqlParsersFactory
                    .getSql("FrmMcpLoading.qureyGxComInfo");// 查询工序是否是结炉状态
            psta = connection.prepareStatement(sql);

            psta.setString(1, HeatPlanId);
            psta.setString(2, BatchNo);
            psta.setString(3, gx);
            rs = psta.executeQuery();
            if (rs.next()) {
                cutFalg = rs.getString("STATION_STATUS");
            }
            else {
                cro.setV_errMsg("无当前工序实绩,不允许次操作!");
                return cro;
            }
            if (!cutFalg.equals("2")) {
                cro.setV_errMsg("当前工序未结炉,不允许此操作！");
                return cro;
            }
            rs.close();
            psta.close();

            if(gx.equals("701313")) {
                updatePlnPsta2.setString(1, HeatPlanId);
                updatePlnPsta2.setString(2, BatchNo);
                updatePlnPsta2.addBatch();
                updatePlnPsta2.executeBatch();
            }else if (gx.equals("701305")){

            }else {


                String NextGx = GetNextGx(gx, PlineCode);
                if (!"".equals(NextGx)) {
                    cutFalg = "";
                    sql = CoreXmlSqlParsersFactory
                            .getSql("FrmMcpLoading.qureyGxComInfo");// 查询工序是否是结炉状态
                    psta = connection.prepareStatement(sql);

                    psta.setString(1, HeatPlanId);
                    psta.setString(2, BatchNo);
                    psta.setString(3, NextGx);
                    rs = psta.executeQuery();
                    if (rs.next()) {
                        cutFalg = rs.getString("STATION_STATUS");

                        if (cutFalg.equals("2")) {
                            cro.setV_errMsg("下工序已结炉,无法结炉！请先撤销下工序");
                            return cro;
                        }
                    }

                    rs.close();
                    psta.close();
                }


                    // 修改计划结炉状态
                    updatePlnPsta.setObject(1, GetBesideStringByGx(GetLastGx(gx, PlineCode)));
                    updatePlnPsta.setString(2, HeatPlanId);
                    updatePlnPsta.setString(3, BatchNo);
                    updatePlnPsta.addBatch();
            }

            updateSqlPsta.setString(1, "1");
            updateSqlPsta.setString(2, HeatPlanId);
            updateSqlPsta.setString(3, BatchNo);
            updateSqlPsta.setString(4, gx);

            updateSqlPsta.addBatch();




            updateSqlPsta.executeBatch();
            updatePlnPsta.executeBatch();

            cro.setV_errMsg("撤销结炉成功!");
            connection.commit();
        }
        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;
    }

    public String GetBesideStringByGx(String Gx) throws Exception {
        //00-上料开始,10-探伤开始，20-切管开始，30-车丝开始，40-螺纹检验开始，50拧接开始，60-通径开始,70-水压开始，80-倒凌开始，90-测量点开始，11-交库开始

        if(Gx.equals("701301")){
            return "00";
        }
        if(Gx.equals("701302")){
            return "10";
        }
        if(Gx.equals("701303")){
            return "20";
        }
        if(Gx.equals("701304")){
            return "30";
        }
        if(Gx.equals("701305")){
            return "40";
        }
        if(Gx.equals("701306")){
            return "50";
        }
        if(Gx.equals("701307")){
            return "60";
        }
        if(Gx.equals("701308")){
            return "70";
        }
        if(Gx.equals("701309")){
            return "80";
        }

        if(Gx.equals("701310")){
            return "90";
        }

        if(Gx.equals("701311")){
            return "11";
        }

        return "";

    }

   public CoreReturnObject GetGx(String PlineCode){
         return  getDataBySqlID("MchComm.GetMchPrcoess",new Object[]{PlineCode});
   }

    public static String[] GetGxs(String PlineCode){
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = new DBCommon().getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        try {
            String stationStr = "";
            sql = CoreXmlSqlParsersFactory
                    .getSql("MchComm.GetMchPrcoess");// 查询工序是否是结炉状态
            psta = connection.prepareStatement(sql);
            psta.setString(1, PlineCode);
            rs = psta.executeQuery();
            if (rs.next()) {
                stationStr = rs.getString("STATION_CODES");
            }
            rs.close();
            psta.close();

            if("".equals(stationStr) || stationStr ==null){
                stationStr = "701301;701311";
            }

            return stationStr.split(";");

        }
        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 null;
    }

    public static String GetLastGx(String CurrentGx, String PlineCode){
        String[] Gxs = GetGxs(PlineCode);

        String LastGx = "";
        for (String Gx :Gxs
             ) {
            if(CurrentGx.equals(Gx)) return LastGx;
            LastGx = Gx;
        }
        return "";
    }

    public static String GetNextGx(String CurrentGx, String PlineCode){
        String[] Gxs = GetGxs(PlineCode);

        boolean FindFlag =false;
        for (String Gx :Gxs
                ) {
            if (FindFlag) return Gx;
            if(CurrentGx.equals(Gx)) FindFlag= true ;
        }
        return "";
    }


    /**
     * 查询打捆实绩
     */
    public CoreReturnObject getUnCheckCout(String heatNo ,String BatchNo) {
        return this.getDataBySqlID("MchComm.getUnCheckCout",
                new Object[] { heatNo,BatchNo});
    }
}
