package com.steering.pss.sale.order.qualityDesign;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.comm.tools.StringTool;
import com.steering.pss.sale.order.model.DesignFallBackEntity;
import com.steering.pss.sale.order.model.DesignStatusEntity;

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

/**
 * 质量设计回退功能
 * @author Administrator
 */
public class QualityDesignFallback extends DBCommon {

    public CoreReturnObject getItems(String ordLnPk) {
        Object[] params = new Object[] { ordLnPk };
        return this.getDataBySqlID("QualityDesignFallback.getItemByOrdLnPk",
                params);
    }
    
    public CoreReturnObject getCraftItems(String ordLnPk) {
        SqlBuilder b = new SqlBuilder("QualityDesignFallback.getCraftItemByOrdLnPk");
        b.Fill(new String[]{ordLnPk});
        return this.getData(b.toString());
    }
    
    public CoreReturnObject getCraftDesignSts(String ordLnPk){
    	String sql = CoreXmlSqlParsersFactory.getSql("QualityDesignFallback.getCraftDesignStsByOrdLnPk");
    	sql = StringTool.ReplaceAll(sql, "#ORD_LN_PK#", ordLnPk);
    	return this.getData(sql);
    }

    /**
     * 是否存在回退记录
     * @param ordLnPk 合同行号
     * @return
     */
    public CoreReturnObject checkFallBack(String ordLnPk) {
        Object[] params = new Object[] { ordLnPk };
        return this.getDataBySqlID("QualityDesignFallback.checkFallBack",
                params);
    }

    /**
     * 将回退状态致无效
     * @param ordLnPk 合同行号
     * @return
     */
    public CoreReturnObject updateFallBack(String ordLnPk) {
        Object[] params = new Object[] { ordLnPk };
        return this.setDataBySqlID("QualityDesignFallback.deleteFallBack",
                params);
    }
    
    /**
     * 工艺回退
     * @param ordLnPk
     * @param seqIdex
     * @return
     */
    public CoreReturnObject craftFallBack(String ordLnPk, String item, String reason,
    		String mscPline, String processCode, String dimater, String height, String pic){
    	String sql = CoreXmlSqlParsersFactory.getSql("QualityDesignFallback.craftFallBack");
    	sql = StringTool.ReplaceAll(sql, "#ORD_LN_PK#", ordLnPk);
    	sql = StringTool.ReplaceAll(sql, "#LST_ITEM#", item);
    	sql = StringTool.ReplaceAll(sql, "#REASON#", reason);
    	sql = StringTool.ReplaceAll(sql, "#MSC_PLINE#", mscPline);
    	sql = StringTool.ReplaceAll(sql, "#PROCESS_CODE#", processCode);
    	sql = StringTool.ReplaceAll(sql, "#DIMATER#", dimater);
    	sql = StringTool.ReplaceAll(sql, "#HEIGHT#", height);
    	sql = StringTool.ReplaceAll(sql, "#PIC#", pic);
    	return this.setData(sql);
    }
    
    private CoreReturnObject fallBackOrder(ArrayList<String> infos, Connection con) throws SQLException{
    	// 合同行号
        String ordLnPk = infos.get(0);
        // 回退点
        String backItem = infos.get(1);
        // 回退原因
        String backReason = infos.get(2);
        // 科室代码
        String departCode = infos.get(3);
        // 科室名称
        String departDesc = infos.get(4);
        // 操作人
        String userName = infos.get(5);
        String userId = infos.get(6);
    	
        CoreReturnObject core = new CoreReturnObject();
    	String ordLnStatus = QualityDesignFallback.getOrderLineStatus(con,
                ordLnPk);
        if (!ordLnStatus.equals("12020201")) {
            core.setV_errMsg("不是技术评审中的合同行,不能回退");
            return core;
        }
        DesignStatusEntity maxNextStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "", "1", false);
        if (maxNextStatus == null) {
            core.setV_errMsg("合同技术评审没有评审流程通过评审,无需评审回退");
            return core;
        }
        if (!departCode.equals("002")) {
            if (!maxNextStatus.getUnitCode().equals(departCode)) {
                core.setV_errMsg("合同技术评审当前流程在 "
                        + maxNextStatus.getUnitDesc() + "," + departDesc
                        + " 没有权限评审回退");
                return core;
            }
        }
        if (backItem.equals("MSC(n)管理科室")
                && Integer.parseInt(maxNextStatus.getSeqIndex()) >= 10) {
            core.setV_errMsg("合同技术特殊要求已经通过评审,无法回退至MSC(n)管理科室");
            return core;
        }

        DesignStatusEntity backStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, backItem, "0", false);
        if (Integer.parseInt(backStatus.getSeqIndex()) > Integer
                .parseInt(maxNextStatus.getSeqIndex())) {
            core.setV_errMsg("合同技术评审当前流程: " + maxNextStatus.getLstItem()
                    + "," + "不能技术评审回退至:" + backItem);
            return core;
        }
        // 1. 判断是否删除管理科室
        DesignStatusEntity deptStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "MSC(n)管理科室", "0", false);
        if (Integer.parseInt(backStatus.getSeqIndex()) <= Integer
                .parseInt(deptStatus.getSeqIndex())) {
            QualityDesignFallback.deleteDept(con, ordLnPk);
        }
        // 2. 判断是否删除指定制程
        DesignStatusEntity mscPlineStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "制程", "0", false);
        if (Integer.parseInt(backStatus.getSeqIndex()) <= Integer
                .parseInt(mscPlineStatus.getSeqIndex())) {
            QualityDesignFallback.deleteSetMscPline(con, ordLnPk);
            QualityDesignFallback.updateListItemStatusByZC(con, ordLnPk);
        }
        
        //删除设定接箍
        DesignStatusEntity mscJgStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "制程", "0", false);
        if (Integer.parseInt(backStatus.getSeqIndex()) <= Integer
                .parseInt(mscJgStatus.getSeqIndex())) {
        	deleteSetMscJg(con, ordLnPk);
            QualityDesignFallback.updateListItemStatusByZC(con, ordLnPk);
        }
        
        //删除设定水压
        DesignStatusEntity mscWaterStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "水压标准", "0", false);
        if (Integer.parseInt(backStatus.getSeqIndex()) == Integer
                .parseInt(mscWaterStatus.getSeqIndex())) {
        	deleteSetWaterRatio(con, ordLnPk);
        }
        
        
        // 3.判断是否删除长度
        // DesignStatusEntity lengthStatus = QualityDesignFallback
        // .getListItemPoint(con, ordLnPk, "长度", "0");
        // if (Integer.parseInt(backStatus.getSeqIndex()) <= Integer
        // .parseInt(lengthStatus.getSeqIndex())) {
        // QualityDesignFallback.deleteLength(con, ordLnPk);
        // }
        // 4.判断是否删除MPS
        DesignStatusEntity mpsStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "MPS", "0", false);
        if (Integer.parseInt(backStatus.getSeqIndex()) <= Integer
                .parseInt(mpsStatus.getSeqIndex())) {
            QualityDesignFallback.deleteMPS(con, mpsStatus.getDesginKey());
        }
        /**
         * 回退处理数据
         */
        // 5.将回退点向后的明细项全部置为等待
        QualityDesignFallback.updateListItemStatusAfterItem(con, ordLnPk,
                backStatus.getSeqIndex());
        // 6. 新增一条回退发起点明细状态
        maxNextStatus.setCreateName(userId);
        maxNextStatus.setUpdateName(userId);
        maxNextStatus.setUnitCode(departCode);
        maxNextStatus.setUnitDesc(departDesc);
        maxNextStatus.setDesignSts("F");
        maxNextStatus.setDesignStsRs("92");
        maxNextStatus.setDesignStsDesc(maxNextStatus.getDesignStsDesc()
                + "(技术回退至:" + backItem + ")");
        maxNextStatus.setValidflag("0");
        QualityDesignFallback.addListItemStartStatusByItem(con,
                maxNextStatus);
        // 7.修改回退点明细状态
        backStatus.setDesignSts("F");
        backStatus.setDesignStsRs("91");
        backStatus.setDesignStsDesc(backReason + "(从:"
                + maxNextStatus.getLstItem() + "  回退至:"
                + backStatus.getLstItem() + ")");
        backStatus.setCreateName(userId);
        QualityDesignFallback.udpateListItemEndStatusItem(con, backStatus);
        // 8.新增回退记录
        QualityDesignFallback.deleteFallBack(con, ordLnPk);
        DesignFallBackEntity fallBack = new DesignFallBackEntity();
        fallBack.setOrderLnPk(ordLnPk);
        fallBack.setFlag("1");
        fallBack.setFallbackDeptCode(departCode);
        fallBack.setFallbackDeptDesc(departDesc);
        fallBack.setFallbackItem(backItem);
        fallBack.setFallbackMan(userName);
        fallBack.setFallbackReason(backReason + "(从:"
                + maxNextStatus.getLstItem() + "  回退至:"
                + backStatus.getLstItem() + ")");
        QualityDesignFallback.addFallBack(con, fallBack);

        // 9.修改合同审批状态
        QualityDesignFallback.updateTklgStatusByOrdLnPK(con, ordLnPk);
        core.setResult(true);
        core.setV_errMsg("回退成功!");
        
        return core;
    }
    
    private CoreReturnObject fallBackBL(ArrayList<String> infos, Connection con) throws SQLException{
    	// 合同行号
        String ordLnPk = infos.get(0);
        // 回退点
        String backItem = infos.get(1);
        // 回退原因
        String backReason = infos.get(2);
        // 科室代码
        String departCode = infos.get(3);
        // 科室名称
        String departDesc = infos.get(4);
        // 操作人
        String userName = infos.get(5);
        String userId = infos.get(6);
    	
        CoreReturnObject core = new CoreReturnObject();
        DesignStatusEntity backStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, backItem, "0", true);
        // 2. 判断是否删除指定制程
        DesignStatusEntity mscPlineStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "制程", "0", true);
        if (Integer.parseInt(backStatus.getSeqIndex()) <= Integer
                .parseInt(mscPlineStatus.getSeqIndex())) {
            QualityDesignFallback.deleteSetMscPline(con, ordLnPk);
            QualityDesignFallback.updateListItemStatusByZC(con, ordLnPk);
        }
        
        DesignStatusEntity maxNextStatus = QualityDesignFallback
                .getListItemPoint(con, ordLnPk, "", "1", true);
        
        if (maxNextStatus == null) {
            core.setV_errMsg("合同技术评审没有评审流程通过评审,无需评审回退");
            return core;
        }
        
        if (Integer.parseInt(backStatus.getSeqIndex()) > Integer
                .parseInt(maxNextStatus.getSeqIndex())) {
            core.setV_errMsg("合同技术评审当前流程: " + maxNextStatus.getLstItem()
                    + "," + "不能技术评审回退至:" + backItem);
            return core;
        }
        
        /**
         * 回退处理数据
         */
        // 5.将回退点向后的明细项全部置为等待
        QualityDesignFallback.updateListItemStatusAfterItem(con, ordLnPk,
                backStatus.getSeqIndex());
        // 6. 新增一条回退发起点明细状态
        maxNextStatus.setCreateName(userId);
        maxNextStatus.setUpdateName(userId);
        maxNextStatus.setUnitCode(departCode);
        maxNextStatus.setUnitDesc(departDesc);
        maxNextStatus.setDesignSts("F");
        maxNextStatus.setDesignStsRs("92");
        maxNextStatus.setDesignStsDesc(maxNextStatus.getDesignStsDesc()
                + "(技术回退至:" + backItem + ")");
        maxNextStatus.setValidflag("0");
        QualityDesignFallback.addListItemStartStatusByItem(con,
                maxNextStatus);
        // 7.修改回退点明细状态
        backStatus.setDesignSts("F");
        backStatus.setDesignStsRs("91");
        backStatus.setDesignStsDesc(backReason + "(从:"
                + maxNextStatus.getLstItem() + "  回退至:"
                + backStatus.getLstItem() + ")");
        backStatus.setCreateName(userId);
        QualityDesignFallback.udpateListItemEndStatusItem(con, backStatus);
        // 8.新增回退记录
        QualityDesignFallback.deleteFallBack(con, ordLnPk);
        DesignFallBackEntity fallBack = new DesignFallBackEntity();
        fallBack.setOrderLnPk(ordLnPk);
        fallBack.setFlag("1");
        fallBack.setFallbackDeptCode(departCode);
        fallBack.setFallbackDeptDesc(departDesc);
        fallBack.setFallbackItem(backItem);
        fallBack.setFallbackMan(userName);
        fallBack.setFallbackReason(backReason + "(从:"
                + maxNextStatus.getLstItem() + "  回退至:"
                + backStatus.getLstItem() + ")");
        QualityDesignFallback.addFallBack(con, fallBack);
        
        core.setResult(true);
        core.setV_errMsg("回退成功!");
        return core;
    }

    public CoreReturnObject fallBack(ArrayList<String> infos) {
    	// 合同行号
        String ordLnPk = infos.get(0);
        CoreReturnObject core = new CoreReturnObject();
        core.setResult(false);
        Connection con = null;
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            if(ordLnPk.startsWith("BL")){
            	core = fallBackBL(infos, con);
            }else{
            	core = fallBackOrder(infos, con);
            }
            con.commit();
        }
        catch (SQLException e) {
            try {
                con.rollback();
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {
            try {
                if(con!=null)
                con.close();
            }
            catch (SQLException e) {

                e.printStackTrace();
            }
        }
        return core;
    }

    /**
     * 查询明细状态
     * @param con 连接字符串
     * @param ordLnPk 合同行号
     * @param item 明细项目
     * @param flag 标识
     * @return DesignStatusEntity
     * @throws SQLException
     */
    public static DesignStatusEntity getListItemPoint(Connection con,
            String ordLnPk, String item, String flag, boolean isBL) throws SQLException {
        String sql = "";
        PreparedStatement ps;
        if (flag.equals("0")) {
            sql = CoreXmlSqlParsersFactory
                    .getSql("QualityDesignFallback.getListItemStatusByitem");
            ps = con.prepareStatement(sql);
            ps.setObject(1, ordLnPk);
            ps.setObject(2, item);
        }
        else {
            sql = CoreXmlSqlParsersFactory
                    .getSql("QualityDesignFallback.getNextMaxListItemStatus");
            ps = con.prepareStatement(sql);
            ps.setObject(1, (isBL ? "14" : "24"));
            ps.setObject(2, ordLnPk);
            ps.setObject(3, ordLnPk);
        }

        
        ResultSet rs = ps.executeQuery();
        List<DesignStatusEntity> statuses = EntityTool.getEntitysByRs(rs,
                DesignStatusEntity.class);
        rs.close();
        ps.close();
        if (statuses != null && statuses.size() > 0) {
            QualityDesignTool.nullConverNullString(statuses.get(0));
            return statuses.get(0);
        }
        else {
            return null;
        }
    }

    /**
     * 合同行当前状态
     * @param con 连接字符串
     * @param ordLnPk 合同行号
     * @return String
     * @throws SQLException
     */
    public static String getOrderLineStatus(Connection con, String ordLnPk)
            throws SQLException {
        String orderLineStatus = "";
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.getOrderLineStatus");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            orderLineStatus = rs.getString("ORDER_LN_STATUS");
        }
        rs.close();
        ps.close();
        return orderLineStatus;
    }

    /**
     * 新增回退记录
     * @param con
     * @param fallBack
     * @throws SQLException
     */
    public static void addFallBack(Connection con, DesignFallBackEntity fallBack)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.addFallBack");
        sql = EntityTool.fillSqlByEntity(sql, fallBack);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 修改回退点后明细状态为等待
     * @param con
     * @param ordLnPk
     * @param seqIndex
     * @throws SQLException
     */
    public static void updateListItemStatusAfterItem(Connection con,
            String ordLnPk, String backSeqIndex) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.updateListItemStatusAfterItem");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.setObject(2, backSeqIndex);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 修改回退点状态
     * @param con
     * @param design
     * @throws SQLException
     */
    public static void udpateListItemEndStatusItem(Connection con,
            DesignStatusEntity design) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.updateListItemEndStatusItem");
        sql = EntityTool.fillSqlByEntity(sql, design);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 新增回退发起点明细状态
     * @param con
     * @param ordLnPk
     * @param backReason
     * @param seqIndex
     * @throws SQLException
     */
    public static void addListItemStartStatusByItem(Connection con,
            DesignStatusEntity design) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.addListItemStartStatusItem");
        sql = EntityTool.fillSqlByEntity(sql, design);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 修改质量设计状态
     * @param con
     * @param ordLnPk
     * @throws SQLException
     */
    public static void updateTklgStatusByOrdLnPK(Connection con, String ordLnPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.updateTklgStatusByOrdLnPK");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 删除管理科室
     * @param con
     * @param ordLnPk
     * @throws SQLException
     */
    public static void deleteDept(Connection con, String ordLnPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.deleteDept");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 删除指定制程
     * @param con
     * @param ordLnPk
     * @throws SQLException
     */
    public static void deleteSetMscPline(Connection con, String ordLnPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.deleteSetMscPline");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.executeUpdate();
        ps.close();
    }
    
    private void deleteSetMscJg(Connection con, String ordLnPk) throws SQLException {
    	String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.deleteMscJg");
    	sql = StringTool.ReplaceAll(sql, "#ORD_LN_PK#", ordLnPk);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.executeUpdate();
        ps.close();
    }
    
    private void deleteSetWaterRatio(Connection con, String ordLnPk) throws SQLException {
    	String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.deleteSetWaterRatio");
    	sql = StringTool.ReplaceAll(sql, "#ORD_LN_PK#", ordLnPk);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 删除MPS
     * @param con
     * @param ordLnPk
     * @throws SQLException
     */
    public static void deleteMPS(Connection con, String designKey)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.deleteMPS");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, designKey);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 删除长度
     * @param con
     * @param ordLnPk
     * @throws SQLException
     */
    public static void deleteLength(Connection con, String ordLnPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.deleteLength");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 删除长度
     * @param con
     * @param ordLnPk
     * @throws SQLException
     */
    public static void deleteFallBack(Connection con, String ordLnPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.deleteFallBack");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.executeUpdate();
        ps.close();
    }

    /**
     * 查询合同行信息
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject getOrdLineInfo(String ordLnPk) {
        Object[] params = new Object[] { ordLnPk };
        return this.getDataBySqlID("QualityDesignFallback.getOrdLineInfo",
                params);
    }

    /**
     * 回退修改制程
     * @param con
     * @param ordLnPk
     * @throws SQLException
     */
    public static void updateListItemStatusByZC(Connection con, String ordLnPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("QualityDesignFallback.updateListItemStatusByZC");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordLnPk);
        ps.executeUpdate();
        ps.close();
    }
    
    /**
     * 获取工艺制程、工序
     * @param con
     * @param designKey
     * @return
     */
    public CoreReturnObject getCraftBackLogProcess(String ordLnPk, String craftSeq){
    	SqlBuilder b = new SqlBuilder("QualityDesignFallback.getCraftBackLogProcess");
    	b.Fill(new String[]{ ordLnPk, craftSeq });
    	
    	return this.getData(b.toString());
    }
}
