package com.steering.pss.sale.order;

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.StringTool;
import com.steering.pss.sale.order.model.CoreOrderStatus;
import com.steering.pss.sale.order.model.SlmOrderReviewItemListEntity;

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

public class frmOrderReviewPrice extends DBCommon {
    /**
     * 合同价格评审界面数据查询.
     * @param doQuery
     * @param appdate 签约时间
     * @param order 合同号
     * @param appstatus 审批状态
     * @return CoreReturnObject
     */
    public CoreReturnObject CoreOrderReviewPriceQuery(String appdate,
                                                      String order, String appstatus, String[] arr, Boolean queryPass) {
        return CoreOrderReviewPriceQuery(appdate,order,appstatus,arr,queryPass,"");
    }
    public CoreReturnObject CoreOrderReviewPriceQuery(String appdate,
            String order, String appstatus, String[] arr, Boolean queryPass,String supp) {
        if (queryPass) {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmOrderReviewPrice.CoreOrderReviewPriceQueryPass");
            if (!StringTool.isNullOrEmpty(appdate)) {
                sql += appdate;
            }
            if (!StringTool.isNullOrEmpty(order)) {
                sql += " and B.ORDER_NO LIKE '%" + order + "%'";
            }
            if (!StringTool.isNullOrEmpty(supp)) {
                sql += " and B.SUPPLY_UNIT = '" + supp + "'";
                if("120504".equals(supp)){
                    sql += " and (B.ORDER_NO LIKE 'TH%' OR B.ORDER_NO LIKE 'HG%')";
                }
            }
            String condition = CoreConverter.toSqlConditionString(
                    "CREATE_DEPT", arr);
            sql += condition;
            sql += " order by ORDER_NO";
            return this.getData(sql);
        }
        else {
            String sql = CoreXmlSqlParsersFactory
                    .getSql("frmOrderReviewPrice.CoreOrderReviewPriceQuery");
            if (!StringTool.isNullOrEmpty(appdate)) {
                sql += appdate;
            }
            if (!StringTool.isNullOrEmpty(order)) {
                sql += " and B.ORDER_NO LIKE '%" + order + "%'";
            }
            if (!StringTool.isNullOrEmpty(appstatus)) {
                sql += " and B.ORDER_STS = '" + appstatus + "'";
            }
            if (!StringTool.isNullOrEmpty(supp)) {
                sql += " and B.SUPPLY_UNIT = '" + supp + "'";
                if("120504".equals(supp)){
                    sql += " and (B.ORDER_NO LIKE 'TH%' OR B.ORDER_NO LIKE 'HG%')";
                }
            }
            String condition = CoreConverter.toSqlConditionString(
                    "CREATE_DEPT", arr);
            sql += condition;
            sql += " order by ORDER_NO";
            return this.getData(sql);
        }
    }

    /**
     * 根据合同号查询价格说明
     * @param ordermodel 合同范本
     * @return CoreReturnObject
     */
    public CoreReturnObject orderPriceQuery(String order) {
        Object[] obj = new Object[] { order };
        return this.getDataBySqlID("frmOrderReviewPrice.orderPriceQuery", obj);
    }

    /**
     * 根据合同号查询合同行信息
     * @param ordermodel 合同范本
     * @return CoreReturnObject
     */
    public CoreReturnObject orderPriceListQuery(String order) {
        Object[] obj = new Object[] { order };
        return this.getDataBySqlID("frmOrderReviewPrice.orderPriceListQuery",
                obj);
    }

    /**
     * 合同价格审批业务.
     * @param parm 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceAdd(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceAdd");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 合同价格审批业务.
     * @param parm 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceAdd2(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceAdd2");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 合同价格审批业务.
     * @param parm 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceAdd3(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceAdd3");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 合同价格审批业务.
     * @param parm 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceAdd4(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceAdd4");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 合同价格审批不通过业务.
     * @param parm 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceUpdate(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceUpdate");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 合同价格审批不通过业务.
     * @param order 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceUpdate2(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceUpdate2");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 合同价格审批不通过业务.
     * @param order 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceUpdate3(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceUpdate3");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 合同价格审批不通过业务.
     * @param order 参数
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject appPriceUpdate4(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.appPriceUpdate4");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    // -----------------------2015-06-19----------------------------------------------------------状态控制---------------------------------

    /**
     * 价格评审 评审通过(放行通过）
     * @param ordPk
     * @param name
     * @param dept
     * @return
     */
    public CoreReturnObject priceReviewPass(ArrayList<Object> parm,
            String name, String dept, String reviewMemo) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;

        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            java.sql.Date date = new java.sql.Date(
                    new java.util.Date().getTime());
            for (int i = 0; i < parm.size(); i++) {
                String ordPk = parm.get(i).toString();
                CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
                CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
                if (cos.getOrderSts().equals("12020224")) { // 审批通过
                    String reviewNo = cou.getOrderReviewNo(con, ordPk);
                    CoreOrderStatusCommFun.updateOrderHeadStatus(con, ordPk,
                            "12020224", "12020232", "价格评审通过", name,
                            date.toString());
                    cou.updateOrderLineStatus(con, ordPk, "12020224",
                            "12020232");
                    cou.updateOrderDeliveryLineStatus(con, ordPk, "12020224",
                            "12020232");
//                    cou.doCrmEvent(con, ordPk,"","","1");
                    // 评审表
                    String obj = dept + "-" + name + "在[合同价格评审]界面,点击[价格放行通过]";
                    CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                            reviewNo, "P", "H", ordPk, "S", "1", name, dept,
                            reviewMemo, obj);
                    CoreOrderStatusCommFun.updateOrderReviewItemEDate(con,
                            reviewNo, "P", "S");
                    String stsT = cou.getOrderReviewItemSatus(con, reviewNo,
                            "T");
                    String stsD = cou.getOrderReviewItemSatus(con, reviewNo,
                            "D");
                    String stsP = cou.getOrderReviewItemSatus(con, reviewNo,
                            "P");
                    String stsF = cou.getOrderReviewItemSatus(con, reviewNo,
                            "F");
                    if (stsT.equals("S") && stsD.equals("S")
                            && stsP.equals("S") && stsF.equals("S")) {
                        CoreOrderStatusCommFun.updateOrderHeadStatus(con,
                                ordPk, "12020224", "12020251", "评审通过", name,
                                date.toString());
                        cou.updateOrderLineStatus(con, ordPk, "12020224",
                                "12020251");
                        cou.updateOrderDeliveryLineStatus(con, ordPk,
                                "12020224", "12020251");
//                        cou.doCrmEvent(con, ordPk,"","","1");
                    }
                    else {
                        List<SlmOrderReviewItemListEntity> list = CoreOrderStatusCommFun
                                .selectOrderReviewItemListInfo(con, reviewNo,
                                        "P", "H", ordPk);
                        CoreOrderStatusCommFun.setOrderReviewItemListValue(con,
                                reviewNo, "P", "H", ordPk);
                        if (list != null && list.size() > 0) {
                            SlmOrderReviewItemListEntity slm = list.get(0);
                            slm.setCreateName(name);
                            slm.setReviewDept(dept);
                            slm.setReviewEdate("");
                            slm.setReviewBdate("");
                            CoreOrderStatusCommFun.addOrderReviewItemListInfo(
                                    con, slm);
                        }
                        else {
                            con.rollback();
                        }
                    }
                    // 更新出厂价 结算价到合同行 也许后来不会用
                    String sql = CoreXmlSqlParsersFactory
                            .getSql("frmOrderReviewPrice.updateOutBalPrice");
                    PreparedStatement ps = con.prepareStatement(sql);
                    ps.setObject(1, ordPk);
                    ps.executeUpdate();
                    ps.close();
                    // 2015-09-21新增逻辑 价格放行时间写入合同头
                    String sql1 = CoreXmlSqlParsersFactory
                            .getSql("frmOrderReviewPrice.updateOrderPassTime");
                    ps = con.prepareStatement(sql1);
                    ps.setObject(1, ordPk);
                    ps.executeUpdate();
                    ps.close();
                }
                else {
                    con.rollback();
                    cro.setV_errCode(-1);
                    cro.setResult("合同状态不是‘审批通过’，不能进行审批通过操作！");
                    return cro;
                }
            }
            con.commit();
            cro.setV_errCode(0);
        }
        catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setResult(e.getMessage());
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }

        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return cro;
    }

    /**
     * 评审不通过
     * @param ordPk
     * @param name
     * @param dept
     * @param reviewMemo
     * @return
     */
    public CoreReturnObject priceReviewBack(String ordPk, String name,
            String dept, String reviewMemo) {
        CoreReturnObject cro = new CoreReturnObject();

        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            con.setAutoCommit(false);
            java.sql.Date date = new java.sql.Date(
                    new java.util.Date().getTime());

            CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
            CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
            if (cos.getOrderSts().equals("12020224")) { // 审批通过
                String reviewNo = cou.getOrderReviewNo(con, ordPk);
                // cou.updateOrderHeadStatus(con, ordPk, "12020224", "12020231",
                // "价格评审失败");
                CoreOrderStatusCommFun
                        .updateOrderHeadStatus(con, ordPk, "12020224",
                                "12020231", "价格评审失败", name, date.toString());
                cou.updateOrderLineStatus(con, ordPk, "12020224", "12020231");
                cou.updateOrderDeliveryLineStatus(con, ordPk, "12020224",
                        "12020231");
                // 评审表
                String obj = dept + "-" + name + "在[合同价格评审]界面,点击[评审不通过]";
                CoreOrderStatusCommFun.updateOrderReviewItemList(con, reviewNo,
                        "P", "H", ordPk, "F", "1", name, dept, reviewMemo, obj);
                CoreOrderStatusCommFun.updateOrderReviewItemNoDate(con,
                        reviewNo, "P", "F");
                con.commit();
                cro.setV_errCode(0);
            }
            else {
                cro.setV_errCode(-1);
                cro.setResult("合同状态不是‘经理审批通过’，不能进行审批不通过操作！");
            }

        }
        catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setResult(e.getMessage());
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }

        }
        finally {
            try {
                con.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return cro;
    }

    // -----------------------------------------------用于合同价格变更（界面跟价格评审为同一个）代码---------------------------------------------------

    public CoreReturnObject chgeQueryPrice(String appdate, String order,
            String[] arr, String saleOrg) {
        String sql = "";
        // String sql1 = "";
        // String sql2 = "";
        // if (saleOrg.equals("100101") || saleOrg.equals("100103")) {
        // sql1 = CoreXmlSqlParsersFactory
        // .getSql("frmOrderReviewPrice.ChgeOrderPriceQueryXSAndGM");
        // }
        // else if (saleOrg.equals("100102")) {
        // sql1 = CoreXmlSqlParsersFactory
        // .getSql("frmOrderReviewPrice.ChgeOrderPriceQueryIE");
        // }
        // else if (saleOrg.equals("admin")) {
        // sql1 = CoreXmlSqlParsersFactory
        // .getSql("frmOrderReviewPrice.ChgeOrderPriceQueryXSAndGM");
        // sql2 = CoreXmlSqlParsersFactory
        // .getSql("frmOrderReviewPrice.ChgeOrderPriceQueryIE");
        // }
        sql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.ChgeOrderPriceQueryIE");
        if (!StringTool.isNullOrEmpty(appdate)) {
            sql += appdate;
        }
        if (!StringTool.isNullOrEmpty(order)) {
            sql += " and B.ORDER_NO LIKE '%" + order + "%'";
        }

        String condition = CoreConverter.toSqlConditionString("CREATE_DEPT",
                arr);
        sql += condition;
        sql += " order by ORDER_NO";

        return this.getData(sql);
    }

    // ------------------------------第二个Tab页的查询-----------------------------------
    /**
     * 价格岗数据查询
     * @param order
     * @param appstatus
     * @param arr
     * @return
     */
    public CoreReturnObject queryPrice(String order, String appstatus,
            String[] arr,String priceNo,String timeStart,String timeEnd) {

        String sql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.queryPrice");
        Object[] obj = new Object[] { order };
        if (appstatus.equals("1")) {
            sql = sql.replaceAll("##ASK##", "=0");
        }
        else if (appstatus.equals("0")) {
            sql = sql.replaceAll("##ASK##", ">0");
        }
        else {
            sql = sql.replaceAll("##ASK##", ">=0");
        }        
        String condition = CoreConverter.toSqlConditionString("CREATE_DEPT",
                arr);
        sql += condition;
        
        if(!StringTool.isNullOrEmpty(priceNo)){
            sql += " AND A.PRICE_NO LIKE '%"+priceNo+"%'";
        }
        if (!StringTool.isNullOrEmpty(timeStart) && !StringTool.isNullOrEmpty(timeEnd)) {
            sql += " AND A.CREATE_TIME BETWEEN TO_DATE('" + timeStart
                    + "','YYYY-MM-DD HH24:MI:SS')" + " AND TO_DATE('" + timeEnd
                    + "','YYYY-MM-DD HH24:MI:SS')";
        }
        
        sql += " ORDER BY ORDER_NO";
        return this.getData(sql, obj);
    }

    /**
     * 取消计算价格的确认（未结算之前）
     * @param parm
     * @return
     */
    public CoreReturnObject undoConfirm(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
        Connection con = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            for (int i = 0; i < parm.size(); i++) {
                String ordPk = parm.get(i).toString();
                // 先查看结算价状态
                String balStatus = getBalPriceStatus(con, ordPk);
                if (balStatus.equals("0")) {
                    con.rollback();
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("结算价尚未确认的合同，无法取消确认！");
                    return cro;
                }
                else {
                    String priceStatus = getOrderPriceStatus(con, ordPk);
                    if (!priceStatus.equals("S")) {
                        con.rollback();
                        cro.setV_errCode(-1);
                        cro.setV_errMsg("价格评审尚未通过的合同，无法取消确认！");
                        return cro;
                    }
                    // 价格评审单置为无效
                    String sql = CoreXmlSqlParsersFactory
                            .getSql("frmOrderReviewPrice.updateOrderPriceStatus");
                    PreparedStatement ps = con.prepareStatement(sql);
                    ps.setObject(1, ordPk);
                    ps.executeUpdate();
                    ps.close();
                    // 合同行计算价状态无效
                    String sql1 = CoreXmlSqlParsersFactory
                            .getSql("frmOrderReviewPrice.updateBalPriceStatus");
                    ps = con.prepareStatement(sql1);
                    ps.setObject(1, ordPk);
                    ps.executeUpdate();
                    ps.close();
                    // 清空确认时间
                    String sql2 = CoreXmlSqlParsersFactory
                            .getSql("frmOrderReviewPrice.UndoOrderConfirmTime");
                    ps = con.prepareStatement(sql2);
                    ps.setObject(1, ordPk);
                    ps.executeUpdate();
                    ps.close();
                    // 添加出crm记录
                    cou.doCrmEvent(con, ordPk,"","","1");
                }
            }
            con.commit();
            cro.setV_errCode(0);
        }
        catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 获取价格评审单的状态
     * @param con
     * @param ordPk
     * @return
     * @throws SQLException
     */
    public String getOrderPriceStatus(Connection con, String ordPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.getOrderPriceStatus");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordPk);
        ResultSet rs = ps.executeQuery();
        String status = "";
        if (rs.next()) {
            status = rs.getString(1);
        }
        rs.close();
        ps.close();
        return status;
    }

    /**
     * 获取结算价状态
     * @param con
     * @param ordPk
     * @return
     * @throws SQLException
     */
    public String getBalPriceStatus(Connection con, String ordPk)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("frmOrderReviewPrice.getBalPriceStatus");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordPk);
        ResultSet rs = ps.executeQuery();
        String status = "";
        if (rs.next()) {
            status = rs.getString(1);
        }
        rs.close();
        ps.close();
        return status;
    }

}
