package com.steering.pss.sale.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.pss.plan.order.model.SlmOrderHeadCopy;
import com.steering.pss.sale.order.ReviewForm.CoreDeliveryReview;
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.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CopyOrderApproval extends DBCommon {

    /**
     * 获取价格明细信息
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject GetOrderPriceList(String priceNo, String ordPk) {
        Object[] obj = new Object[] { priceNo, ordPk };
        return this.getDataBySqlID("CoreOrderApproval.GetOrderPriceList", obj);
    }

    /**
     * 合同头数据源绑定
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject doGetQuery(String order_no, String timesta,
            String timeend, String roderSTS1, String roderSTS2,
            String roderSTS3, String roderSTS4, String roderSTS5,
            String roderSTS6, String saleOrg) {
        Object[] obj = new Object[] { roderSTS1, roderSTS2, roderSTS3,
                roderSTS4, roderSTS5, roderSTS6, order_no, timesta, timeend,
                saleOrg };
        return this.getDataBySqlID("CoreOrderApproval.GetQuery", obj);
    }

    /**
     * 合同行数据源绑定
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject doGetLineOrder(String order_no) {
        Object[] obj = new Object[] { order_no };
        return this.getDataBySqlID("CoreOrderApproval.GetLineOrder", obj);
    }

    /**
     * 合同条目数据源绑定
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject doGetModelItem(String order_model_no) {
        Object[] obj = new Object[] { order_model_no };
        return this.getDataBySqlID("CoreOrderApproval.GetModelItem", obj);
    }

    /**
     * 合同定价数据源绑定
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject doGetOrderPrice(String ordpk) {
        Object[] obj = new Object[] { ordpk };
        return this.getDataBySqlID("CoreOrderApproval.GetOrderPrice", obj);
    }

    /**
     * 修改合同头
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject doUpdateHeadOrder(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("CoreOrderApproval.UpdateHeadOrder");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 退回修改合同头
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject doUpdateHeadOrderMeMo(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        String strSql = CoreXmlSqlParsersFactory
                .getSql("CoreOrderApproval.UpdateHeadOrderMeMo");
        try {
            cro = this.getDao("TgDao").ExcuteNonQuery(strSql, parm.toArray());
        }
        catch (SQLException e) {
            cro = cro.SetErrInfo(e.getMessage());
        }
        return cro;
    }

    /**
     * 保存合同行状态
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject UpdateHeadStatus(String ordPk, String hStatus,
            String hStatusDesc, String appName) {

        CoreReturnObject spbCro = new CoreReturnObject();
        ArrayList<String> spbSqlList = new ArrayList<String>();
        ArrayList<Object[]> spbParmList = new ArrayList<Object[]>();

        spbSqlList.add(CoreXmlSqlParsersFactory
                .getSql("CoreOrderApproval.doUpdateHeadSts"));

        spbSqlList.add(CoreXmlSqlParsersFactory
                .getSql("CoreOrderApproval.doUpdateLnStatus"));

        spbSqlList.add(CoreXmlSqlParsersFactory
                .getSql("CoreOrderApproval.doUpdateDelStatus"));

        // String hStatusDesc="";
        // if("12020210".equals(hStatus)){
        // hStatusDesc = "待交货期评审";
        // }
        // else if("12020202".equals(hStatus)){
        // hStatusDesc="技术评审通过";
        // }

        Object[] obj = new Object[] { hStatus, hStatusDesc, appName, ordPk };
        Object[] obj2 = new Object[] { hStatus, ordPk };
        Object[] obj3 = new Object[] { hStatus, ordPk };

        spbParmList.add(obj);
        spbParmList.add(obj2);
        spbParmList.add(obj3);

        try {
            spbCro = this.getDao("TgDao").ExcuteTransction(spbSqlList,
                    spbParmList);
        }
        catch (Exception e) {
            spbCro = spbCro.SetErrInfo(e.getMessage());
        }

        return spbCro;
    }

    // --------------------------------------- (2015/06/18)
    /**
     * 合同头数据源绑定(2015/06/18)
     * @param params 查询参数
     * @param customInfo自定义参数
     * @param arr 可以查看的片区的ID数组
     * @return CoreReturnObject
     */
    public CoreReturnObject doGetQuery(ArrayList<Object> params,
            String customInfo, String[] arr, String saleOrg, Boolean queryAll,
            Boolean queryPass) {
        return doGetQuery(params,customInfo,arr,saleOrg,queryAll,queryPass,"");
    }

    public CoreReturnObject doGetQuery(ArrayList<Object> params,
                                       String customInfo, String[] arr, String saleOrg, Boolean queryAll,
                                       Boolean queryPass, String supp) {
        String sql = "";
        if (saleOrg.equals("100102")) { // 国贸
            if (customInfo.contains("director")) { // 主管
                params.set(0, "12020251");
            }
        }
        if (queryAll) {
            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreOrderApproval.GetQueryAll");
        }
        else if (queryPass) {
            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreOrderApproval.GetQueryPass");
        }
        else {
            sql = CoreXmlSqlParsersFactory
                    .getSql("CoreOrderApproval.GetQuery");
        }
        sql += CoreConverter.toSqlConditionString("CREATE_DEPT",arr);
        if (!StringUtils.isEmpty(supp)) {
            sql+=" AND SUPPLY_UNIT = '"+ supp +"'";
        }
        sql += "   ORDER BY ORDER_NO";
        return this.getData(sql, params.toArray());
    }

    /**
     * 查询合同头状态 2015/06/18
     * @param ordPk 合同头号
     * @return CoreReturnObject
     */
    public CoreReturnObject getOrdPkStatus(String ordPk) {
        Object[] obj = new Object[] { ordPk };
        return this.getDataBySqlID("CoreOrderApproval.getOrdPkStatus", obj);
    }

    /**
     * 获取价格评审单状态
     * @param priceNo
     * @return
     */
    public CoreReturnObject getOrderPriceStatus(String priceNo) {
        Object[] obj = new Object[] { priceNo };
        return this
                .getDataBySqlID("CoreOrderApproval.getOrderPriceStatus", obj);
    }

    /**
     * 审批提报
     * @param ordPk 合同行
     * @param status
     * @return
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doExport(ArrayList<Object> parm, String reviewMemo,
            String name, String dept, String saleOrg) {

        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        CoreOrderInfoUpdate cou =new CoreOrderInfoUpdate();
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            for (int i = 0; i < parm.size(); i++) {
                ArrayList<Object> al = (ArrayList<Object>) parm.get(i);
                if (saleOrg.equals("100102")
                        && al.get(1).toString().equals("120102")) {
                    con.rollback();
                    core.setV_errMsg("此界面对国际贸易部的现货合同没有操作权限！");
                    core.setV_errCode(-1);
                    return core;
                }

                String ordPk = al.get(0).toString();
                // 查询是否为天淮成品合同的母合同
                SqlBuilder b = new SqlBuilder("CoreOrderApproval.getOrderHeadStatusByCustm");
                b.Fill(new String[]{ordPk});
                CoreOrderStatus orderStatus =EntityTool.getEntityBySqlNoClsCon(b.toString(), con,  CoreOrderStatus.class);
                if(orderStatus != null && Integer.parseInt(orderStatus.getOrderSts()) < 12020212 && orderStatus.getOrderNo().startsWith("TH")){
                    con.rollback();
                    core.setV_errMsg("请等待天淮合同技术评审，交货期通过！");
                    core.setV_errCode(-1);
                    return core;
                }
                // 修改合同头状态
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderApproval.updateOrderHeadStatus");
                PreparedStatement ps = con.prepareStatement(sql);
                ps.setObject(1, "12020220");
                ps.setObject(2, "待审批");
                ps.setObject(3, ordPk);
                ps.executeUpdate();
                cou.doCrmEvent(con, ordPk,"","","1","0");
                // 修改合同行状态
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderApproval.updateOrderLineStatus");
                ps = con.prepareStatement(sql);
                ps.setObject(1, "12020220");
                ps.setObject(2, ordPk);
                ps.executeUpdate();
                cou.doCrmEvent(con, ordPk,"","","1","1");
                // 修改交货行状态
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderApproval.updateOrderDeliveryStatus");
                ps = con.prepareStatement(sql);
                ps.setObject(1, "12020220");
                ps.setObject(2, ordPk);
                ps.executeUpdate();
                //修改crm状态
                cou.doCrmEvent(con, ordPk,"","","1","2");

                // 修改评审项目表中价格评审状态
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderApproval.updateOrderReviewItem");
                ps = con.prepareStatement(sql);
                ps.setObject(1, ordPk);
                ps.executeUpdate();
                // 修改评审明细项目表中价格评审状态
                if (!saleOrg.equals("100102")) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrderApproval.updateOrderReviewItemlist");
                    ps = con.prepareStatement(sql);
                    String obj = dept + "-" + name + "在[合同审批提报]界面，点击[提报审批]。";
                    ps.setObject(1, reviewMemo);
                    ps.setObject(2, name);
                    ps.setObject(3, dept);
                    ps.setObject(4, obj);
                    ps.setObject(5, ordPk);
                    ps.executeUpdate();
                    ps.close();

                    // 在新增一条当前数据
                    String reviewNo = cou.getOrderReviewNo(con, ordPk);

                    List<SlmOrderReviewItemListEntity> list = null;
                    if(al.get(1).toString().equals("120104")){
                        list = CoreOrderStatusCommFun
                                .selectOrderReviewItemListInfo(con, reviewNo, "D",
                                        "H", ordPk);
                        CoreOrderStatusCommFun.setOrderReviewItemListValue(con,
                                reviewNo, "D", "H", ordPk);
                    } else {
                        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("");
                        slm.setReviewFRs("");
                        slm.setRtReviewItm("");
                        CoreOrderStatusCommFun.addOrderReviewItemListInfo(con,
                                slm);
                    }
                    else {
                        con.rollback();
                    }
                }
            }
            con.commit();
        }
        catch (Exception e) {
        	core.setV_errMsg(e.getMessage());
            try {
                con.rollback();
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }

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

    /**
     * 撤销提报
     * @param ordPk 合同头号
     * @param orderType 合同类型
     * @return CoreReturnObject
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doCancel(ArrayList<Object> parm, String saleOrg) {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            for (int i = 0; i < parm.size(); i++) {
                ArrayList<Object> list = (ArrayList<Object>) parm.get(i);
                String ordPk = list.get(0).toString();
                String orderType = list.get(1).toString();
                if (saleOrg.equals("100102") && orderType.equals("120102")) {
                    con.rollback();
                    core.setV_errMsg("此界面对国际贸易部的现货合同没有操作权限！");
                    core.setV_errCode(-1);
                    return core;
                }

                // 修改合同头状态
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderApproval.updateOrderHeadStatus");
                PreparedStatement ps = con.prepareStatement(sql);
                CoreOrderInfoUpdate cou =new CoreOrderInfoUpdate();
                // 现货合同
                if (orderType.equals("120102")) {
                    ps.setObject(1, "12020213");
                    ps.setObject(2, "待提报审批");
                }
                else {
                    ps.setObject(1, "12020212");
                    ps.setObject(2, "交货期评审通过");
                }
                ps.setObject(3, ordPk);
                ps.executeUpdate();
                ps.close();
                cou.doCrmEvent(con, ordPk,"","","1","0");
                // 修改合同行状态
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderApproval.updateOrderLineStatus");
                ps = con.prepareStatement(sql);
                if (orderType.equals("120102")) {
                    ps.setObject(1, "12020213");
                }
                else {
                    ps.setObject(1, "12020212");
                }
                ps.setObject(2, ordPk);
                ps.executeUpdate();
                ps.close();
                cou.doCrmEvent(con, ordPk,"","","1","1");
                // 修改交货行状态
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderApproval.updateOrderDeliveryStatus");
                ps = con.prepareStatement(sql);     
                
                if (orderType.equals("120102")) {
                    ps.setObject(1, "12020213");
                }
                else {
                    ps.setObject(1, "12020212");
                }
                ps.setObject(2, ordPk);
                ps.executeUpdate();
                ps.close();
                cou.doCrmEvent(con, ordPk,"","","1","2");
            }
            con.commit();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        return core;
    }

    // -----------提报评审---业务主管界面----评审通过
    /**
     * 评审通过 业务主管
     * @param ordPk
     * @param name
     * @param dept
     * @param saleOrg
     * @return
     */
    public CoreReturnObject reviewPass(ArrayList<String> parm, String name,
            String dept, String reviewMemo, String saleOrg) {
        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);
                CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
                String reviewNo = cou.getOrderReviewNo(con, ordPk);
                java.sql.Date date = new java.sql.Date(
                        new java.util.Date().getTime());
                if (cos.getOrderSts().equals("12020220")) { // 待审批 状态
                    if (!saleOrg.equals("100102")) {
                        CoreOrderStatusCommFun.updateOrderHeadStatus(con,
                                ordPk, "12020220", "12020222", "审批通过", name,
                                date.toString());
                        cou.updateOrderLineStatus(con, ordPk, "12020220",
                                "12020222");
                        cou.updateOrderDeliveryLineStatus(con, ordPk,
                                "12020220", "12020222");
//                        cou.doCrmEvent(con, ordPk,"","","1","1");
                        // 评审明细
                        String obj = dept + "-" + name
                                + "在[合同审批管理(业务主管)]界面,点击[审批通过]";

                            String orderType = CoreOrderStatusCommFun.getOrderType(con,ordPk);
                        List<SlmOrderReviewItemListEntity> list = null;
                        // 查询客户合同
                        SqlBuilder b = new SqlBuilder("CoreOrderCopy.queryHead");
                        b.Fill(new String[]{ordPk});
                        SlmOrderHeadCopy orderHead = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmOrderHeadCopy.class);
                        CoreOrderCopy orderCopy = new CoreOrderCopy();
                        String order = orderCopy.getOrderByOrderNo(con, orderHead.getCustmOrderNo());
                        if(orderHead != null && orderHead.getOrderNo().startsWith("TH") && saleOrg.equals("100105") && !StringUtils.isEmpty(order)){
                            CoreOrderStatusCommFun.updateOrderReviewItemListEDate(
                                    con, reviewNo, "D", "H", ordPk, name, dept,
                                    "1", "1", "S", reviewMemo);
                            CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                                    reviewNo, "D", "H", ordPk, name, dept, "1",
                                    "1", "S", reviewMemo, obj);
                            list = CoreOrderStatusCommFun
                                    .selectOrderReviewItemListInfo(con, reviewNo,
                                            "D", "H", ordPk);
                            CoreOrderStatusCommFun.setOrderReviewItemListValue(con,
                                    reviewNo, "D", "H", ordPk);
                        } else if(orderType.equals("120104")){
                            CoreOrderStatusCommFun.updateOrderReviewItemListEDate(
                                    con, reviewNo, "D", "H", ordPk, name, dept,
                                    "1", "1", "S", reviewMemo);
                            CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                                    reviewNo, "D", "H", ordPk, name, dept, "1",
                                    "1", "S", reviewMemo, obj);
                            list = CoreOrderStatusCommFun
                                    .selectOrderReviewItemListInfo(con, reviewNo,
                                            "D", "H", ordPk);
                            CoreOrderStatusCommFun.setOrderReviewItemListValue(con,
                                    reviewNo, "D", "H", ordPk);
                        } else {
                            CoreOrderStatusCommFun.updateOrderReviewItemListEDate(
                                    con, reviewNo, "P", "H", ordPk, name, dept,
                                    "1", "1", "S", reviewMemo);
                            CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                                    reviewNo, "P", "H", ordPk, name, dept, "1",
                                    "1", "S", reviewMemo, obj);
                            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("");
                            slm.setReviewFRs("");
                            slm.setRtReviewItm("");
                            CoreOrderStatusCommFun.addOrderReviewItemListInfo(
                                    con, slm);
                        }
                        else {
                            con.rollback();
                        }
                    }
                    else {// 国贸  2022-09-27 国贸要过法务评审
                        CoreOrderStatusCommFun.updateOrderHeadStatus(con,
                                ordPk, "12020220", "12020222", "主管审批通过", name,
                                date.toString());
                        cou.updateOrderLineStatus(con, ordPk, "12020220",
                                "12020222");
                        cou.updateOrderDeliveryLineStatus(con, ordPk,
                                "12020220", "12020222");
//                        cou.doCrmEvent(con, ordPk,"","","1","1");
                    }
                }
                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
     * @return
     */
    public CoreReturnObject reviewBack(ArrayList<String> parm, String name,
            String dept, String reviewMemo, String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
        java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());

        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);
                CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
                if (cos.getOrderSts().equals("12020220")) { // 待审批 状态
                    if (saleOrg.equals("100102")) { // 国贸公司 暂不提供审批退回功能
                                                    // 2015-07-23加入功能

                        CoreOrderStatusCommFun.updateOrderHeadStatus(con,
                                ordPk, "12020220", "12020221", "主管审批退回", name,
                                date.toString());
                        cou.updateOrderLineStatus(con, ordPk, "12020220",
                                "12020221");
                        cou.updateOrderDeliveryLineStatus(con, ordPk,
                                "12020220", "12020221");
//                        cou.doCrmEvent(con, ordPk,"","","1","1");

                    }
                    String reviewNo = cou.getOrderReviewNo(con, ordPk);

                    CoreOrderStatusCommFun.updateOrderHeadStatus(con, ordPk,
                            "12020220", "12020221", "主管审批退回", name,
                            date.toString());
                    cou.updateOrderLineStatus(con, ordPk, "12020220",
                            "12020221");
                    cou.updateOrderDeliveryLineStatus(con, ordPk, "12020220",
                            "12020221");
                    // 评审明细表中价格评审（标识为“1”）的状态为“评审失败”
                    String obj = dept + "-" + name
                            + "在[合同审批管理(业务主管)]界面,点击[审批回退]";
                    
                    if (!saleOrg.equals("100102")) {

                        String orderType = CoreOrderStatusCommFun.getOrderType(con,ordPk);
                        List<SlmOrderReviewItemListEntity> list = null;
                        if(orderType.equals("120104")) {
                            list = CoreOrderStatusCommFun
                                    .selectOrderReviewItemListInfo(con, reviewNo, "D",
                                            "H", ordPk);
                            CoreOrderStatusCommFun.setOrderReviewItemListValue(con,
                                    reviewNo, "D", "H", ordPk);
                        } else {
                            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("");
                            slm.setReviewFRs("");
                            slm.setRtReviewItm("");
                            CoreOrderStatusCommFun.addOrderReviewItemListInfo(con,
                                    slm);
                            CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                                    reviewNo, "P", "H", ordPk, "F", "1", name,
                                    dept, reviewMemo, obj);
                        }
                        else {
                            con.rollback();
                        }
                        // 2015-10-28合同退回 修改价格评审状态
                        CoreOrderStatusCommFun.setOrderPriceStatus(con, ordPk);
                    }
                    con.commit();
                    cro.setV_errCode(0);
                }
                else {
                    if (cos.getOrderSts().equals("12020251")) {
                        if (saleOrg.equals("100102")) { // 国贸公司 暂不提供审批退回功能
                            // 2015-07-23加入功能

                            CoreOrderStatusCommFun.updateOrderHeadStatus(con,
                                    ordPk, "12020220", "12020221", "主管审批退回",
                                    name, date.toString());
                            cou.updateOrderLineStatus(con, ordPk, "12020220",
                                    "12020221");
                            cou.updateOrderDeliveryLineStatus(con, ordPk,
                                    "12020220", "12020221");
//                            cou.doCrmEvent(con, ordPk,"","","1","1");
                        }
                    }
                    else {
                        con.rollback();
                        cro.setV_errCode(-1);
                        cro.setResult("合同状态不是‘待审批’，不能进行审批退回操作！");
                        return cro;
                    }
                }
            }
            con.commit();
            cro.setV_errCode(0);
            return cro;
        }
        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
     * @return
     */
    public CoreReturnObject reviewPassManager(ArrayList<String> parm,
            String name, String dept, String reviewMemo) {
        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);
                CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);

                if (cos.getOrderSts().equals("12020222")) { // 审批通过（业务主管审批） 状态
                    String reviewNo = cou.getOrderReviewNo(con, ordPk);
                    String ordType = CoreOrderStatusCommFun.getOrderType(con,
                            ordPk);
                    if (ordType.equals("120104")) {
                        cou.updateOrderHeadStatus(con, ordPk, "12020222",
                                "12020301", "生效");
                        cou.updateOrderLineStatus(con, ordPk, "12020222",
                                "12020301");
                        cou.updateOrderDeliveryLineStatus(con, ordPk,
                                "12020222", "12020301");
//                        cou.doCrmEvent(con, ordPk, "", "", "1","1");
                        /*
                         * CoreOrderStatusCommFun.updateOrderReviewItemListEDate(
                         * con, reviewNo, "P", "H", ordPk, name, dept, "1", "1",
                         * "S", reviewMemo);
                         */

                        String obj = dept + "-" + name
                                + "在[合同审批管理(主管经理)]界面,点击[审批通过]";
                        CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                                reviewNo, "E", "H", ordPk, name, dept, "1");
                        CoreOrderStatusCommFun
                                .insertOrderReviewItemList(con, reviewNo, "E",
                                        "H", ordPk, "S", name, dept, obj);
                        CoreOrderStatusCommFun.updateOrderReviewItemListEDate(
                                con, reviewNo, "E", "H", ordPk, name, dept,
                                "1", "1", "S", "");
                        // 写入进程表
                        CoreOrderStatusCommFun.insertProcessOrder(con, ordPk);
                    } else {

                        cou.updateOrderHeadStatus(con, ordPk, "12020222",
                                "12020224", "经理审批通过");
                        cou.updateOrderLineStatus(con, ordPk, "12020222",
                                "12020224");
                        cou.updateOrderDeliveryLineStatus(con, ordPk,
                                "12020222", "12020224");
//                        cou.doCrmEvent(con, ordPk, "", "", "1","1");
                        CoreOrderStatusCommFun.updateOrderReviewItemListEDate(
                                con, reviewNo, "P", "H", ordPk, name, dept,
                                "1", "1", "S", reviewMemo);
                        // 评审明细
                        String obj = dept + "-" + name
                                + "在[合同审批管理(主管经理)]界面,点击[审批通过]";
                        CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                                reviewNo, "P", "H", ordPk, name, dept, "0",
                                "1", "S", reviewMemo, obj);

                        cou.insertOrderReviewItemList(con, reviewNo, "P", "H",
                                ordPk, "W", name, dept);
                        CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                                reviewNo, "P", "H", ordPk, "", "", "1", "1",
                                "W", "", "");
                    }
                }
                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 parm
     * @param name
     * @param dept
     * @param reviewMemo
     * @return
     */
    public CoreReturnObject reviewBackManager(ArrayList<String> parm,
            String name, String dept, String reviewMemo) {
        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);
                CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
                if (cos.getOrderSts().equals("12020222")) { // 审批通过（业务主管） 状态
                    String reviewNo = cou.getOrderReviewNo(con, ordPk);
                    cou.updateOrderHeadStatus(con, ordPk, "12020222",
                            "12020223", "审批退回");
                    cou.updateOrderLineStatus(con, ordPk, "12020222",
                            "12020223");
                    cou.updateOrderDeliveryLineStatus(con, ordPk, "12020222",
                            "12020223");
//                    cou.doCrmEvent(con, ordPk,"","","1","1");
                    // 评审明细表中价格评审（标识为“1”）的状态为“评审失败”
                    String obj = dept + "-" + name
                            + "在[合同审批管理(主管经理)]界面,点击[审批回退]";
                    CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                            reviewNo, "P", "H", ordPk, "F", "1", name, dept,
                            reviewMemo, obj);
                    // 2015-10-28合同退回更改价格状态
                    CoreOrderStatusCommFun.setOrderPriceStatus(con, ordPk);
                }
                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 dept
     * @param name
     * @param reviewMemo
     * @return
     */
    public CoreReturnObject backToDelivery(String ordPk, String dept,
            String name, String reviewMemo) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;
        CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
        java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
        CoreDeliveryReview cdr = new CoreDeliveryReview();
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
            String ordType = CoreOrderStatusCommFun.getOrderType(con, ordPk);
            if (ordType.equals("120102") || ordType.equals("120105")) {
                cro.setV_errCode(-1);
                cro.setV_errMsg("现货合同或者自产+外加工不能直接退回交货期！");
                return cro;
            }
            if (!cos.getOrderSts().equals("12020301")
                    && Integer.parseInt(cos.getOrderSts()) < 12020301
                    && Integer.parseInt(cos.getOrderSts()) >= 12020212) {
                String reviewNo = cou.getOrderReviewNo(con, ordPk);

                cou.updateOrderReviewItem(con, reviewNo, "P", "W");
                String obj = dept + "-" + name + "在[合同审批提报]界面,点击[退回交货期]";
                CoreOrderStatusCommFun.updateOrderHeadStatus(con, ordPk,
                        cos.getOrderSts(), "12020211", "交货期评审失败", name,
                        date.toString());
                cou.updateOrderLineStatus(con, ordPk, cos.getOrderSts(),
                        "12020211");
                cou.updateOrderDeliveryLineStatus(con, ordPk,
                        cos.getOrderSts(), "12020211");
//                cou.doCrmEvent(con, ordPk,"","","1","1");
                // 后台释放产能井
                cdr.freeCastWellList(con, ordPk, name);
                cou.updateOrderReviewItem(con, reviewNo, "D", "F");
                cou.updateOrderReviewItem(con, reviewNo, "P", "W");
                cou.updateOrderReviewItem(con, reviewNo, "F", "W");

                CoreOrderStatusCommFun.updateOrderReviewItemList(con, reviewNo,
                        "D", "H", ordPk, "F", "1", name, dept, reviewMemo, "");
                CoreOrderStatusCommFun.updateOrderReviewItemListEDate(con,
                        reviewNo, "D", "H", ordPk, name, dept, "0", "1", "F",
                        reviewMemo);
                CoreOrderStatusCommFun.updateOrderReviewItemList(con, reviewNo,
                        "P", "H", ordPk, "F", "1", name, dept, reviewMemo, obj);
                CoreOrderStatusCommFun.updateOrderReviewItemListEDate(con,
                        reviewNo, "P", "H", ordPk, name, dept, "0", "1", "F",
                        reviewMemo);

                CoreOrderStatusCommFun.updateOrderReviewItemList(con, reviewNo,
                        "F", "H", ordPk, "F", "1", name, dept, reviewMemo, obj);
                CoreOrderStatusCommFun.updateOrderReviewItemListEDate(con,
                        reviewNo, "F", "H", ordPk, name, dept, "0", "1", "F",
                        reviewMemo);
                CoreOrderStatusCommFun.insertOrderReviewItemList(con, reviewNo,
                        "D", "H", ordPk, "W", name, dept, obj);
                CoreOrderStatusCommFun.insertOrderReviewItemList(con, reviewNo,
                        "P", "H", ordPk, "W", name, dept, obj);
                CoreOrderStatusCommFun.insertOrderReviewItemList(con, reviewNo,
                        "F", "H", ordPk, "W", name, dept, obj);
                //
                CoreOrderStatusCommFun.setOrderPriceStatus(con, ordPk);
                CoreOrderReviewLaw.clearOrderLawRecord(con, ordPk);
                con.commit();
                cro.setV_errCode(0);
            }
            else {
                cro.setV_errCode(-1);
                cro.setV_errMsg("合同已生效或者处于交货期通过之前的状态，不能直接退回交货期！");
            }
        }
        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 ordPk
     * @param dept
     * @param name
     * @param reviewMemo
     * @return
     */
    public CoreReturnObject backToDeliveryIE(String ordPk, String dept,
            String name, String reviewMemo) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;
        CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
        java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
        CoreDeliveryReview cdr = new CoreDeliveryReview();
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
            String orderType = CoreOrderStatusCommFun.getOrderType(con, ordPk);
            if (!orderType.equals("120102") && !orderType.equals("120105")) {// 非现货合同
                if (!cos.getOrderSts().equals("12020301")
                        && Integer.parseInt(cos.getOrderSts()) < 12020301
                        && Integer.parseInt(cos.getOrderSts()) >= 12020212) {
                    String reviewNo = cou.getOrderReviewNo(con, ordPk);

                    // String obj = dept + "-" + name
                    // + "在[合同审批提报(业务主管)]界面,点击[退回交货期]";
                    CoreOrderStatusCommFun.updateOrderHeadStatus(con, ordPk,
                            cos.getOrderSts(), "12020211", "交货期评审失败", name,
                            date.toString());
                    cou.updateOrderLineStatus(con, ordPk, cos.getOrderSts(),
                            "12020211");
                    cou.updateOrderDeliveryLineStatus(con, ordPk,
                            cos.getOrderSts(), "12020211");
//                    cou.doCrmEvent(con, ordPk,"","","1");
                    // 释放产能井
                    cdr.freeCastWellList(con, ordPk, name);
                    // 评审明细记录
                    cou.updateOrderReviewItem(con, reviewNo, "D", "F");
                    List<SlmOrderReviewItemListEntity> list = CoreOrderStatusCommFun
                            .selectOrderReviewItemListInfo(con, reviewNo, "D",
                                    "H", ordPk);
                    CoreOrderStatusCommFun.setOrderReviewItemListValue(con,
                            reviewNo, "D", "H", ordPk);
                    if (list != null && list.size() > 0) {
                        SlmOrderReviewItemListEntity slm = list.get(0);
                        slm.setReviewEdate(date.toString());
                        slm.setReviewDept(dept);
                        slm.setReviewMan(name);
                        // slm.setRtReviewItm(obj);
                        slm.setReviewStatus("F");
                        CoreOrderStatusCommFun.addOrderReviewItemListInfo(con,
                                slm);
                    }
                    else {
                        con.rollback();
                        cro.setV_errCode(0);
                        return cro;
                    }
                    CoreOrderStatusCommFun.setOrderPriceStatus(con, ordPk);
                    con.commit();
                    cro.setV_errCode(0);
                }
                else {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("合同已生效或者处于交货期通过之前的状态，不能直接退回交货期！");
                }
            }
            else { // 现货合同 没有交货期 ----预留在这里
                cro.setV_errCode(-1);
                cro.setV_errMsg("现货合同和贸易合同不能直接退回交货期！");
                return cro;
            }
        }
        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 ordPk
     * @param dept
     * @param name
     * @param reviewMemo
     * @return
     */
    public CoreReturnObject backEdit(String ordPk, String dept, String name,
            String reviewMemo, String saleOrg) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;
        CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
        java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            CoreOrderStatus cos = cou.getOrderStatus(con, ordPk);
            String ordType = CoreOrderStatusCommFun.getOrderType(con, ordPk);
            if (!ordType.equals("120102") && !ordType.equals("120105")) {
                cro.setV_errCode(-1);
                cro.setV_errMsg("非现货和采购期货(不加工)合同不能直接退回录入状态！");
                return cro;
            }
            if (!cos.getOrderSts().equals("12020301")
                    && Integer.parseInt(cos.getOrderSts()) < 12020301
                    && Integer.parseInt(cos.getOrderSts()) >= 12020212) {
                String reviewNo = cou.getOrderReviewNo(con, ordPk);

                cou.updateOrderReviewItem(con, reviewNo, "P", "W");
                String obj = dept + "-" + name + "在[合同审批提报]界面,点击[现货退回]";
                CoreOrderStatusCommFun.updateOrderHeadStatus(con, ordPk,
                        cos.getOrderSts(), "12020101", "录入", name,
                        date.toString());
                cou.updateOrderLineStatus(con, ordPk, cos.getOrderSts(),
                        "12020101");
                cou.updateOrderDeliveryLineStatus(con, ordPk,
                        cos.getOrderSts(), "12020101");
//                cou.doCrmEvent(con, ordPk,"","","1","1");
                /*
                 * cou.updateOrderReviewItem(con, reviewNo, "D", "L");
                 * CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                 * reviewNo, "D", "H", ordPk, "F", "1", name, dept, reviewMemo,
                 * "");
                 * CoreOrderStatusCommFun.updateOrderReviewItemListEDate(con,
                 * reviewNo, "D", "H", ordPk, name, dept, "0", "1", "F",
                 * reviewMemo);
                 */// 不存在交货期
                if (!saleOrg.equals("100102")) {
                    cou.updateOrderReviewItem(con, reviewNo, "P", "W");
                    cou.updateOrderReviewItem(con, reviewNo, "F", "W");
                    CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                            reviewNo, "P", "H", ordPk, "F", "1", name, dept,
                            reviewMemo, obj);
                    CoreOrderStatusCommFun.updateOrderReviewItemListEDate(con,
                            reviewNo, "P", "H", ordPk, name, dept, "0", "1",
                            "F", reviewMemo);

                    CoreOrderStatusCommFun.updateOrderReviewItemList(con,
                            reviewNo, "F", "H", ordPk, "F", "1", name, dept,
                            reviewMemo, obj);
                    CoreOrderStatusCommFun.updateOrderReviewItemListEDate(con,
                            reviewNo, "F", "H", ordPk, name, dept, "0", "1",
                            "F", reviewMemo);
                    // CoreOrderStatusCommFun.insertOrderReviewItemList(con,
                    // reviewNo, "D", "H", ordPk, "W", name, dept, obj);
                    CoreOrderStatusCommFun.insertOrderReviewItemList(con,
                            reviewNo, "P", "H", ordPk, "W", name, dept, obj);
                    CoreOrderStatusCommFun.insertOrderReviewItemList(con,
                            reviewNo, "F", "H", ordPk, "W", name, dept, obj);
                    CoreOrderStatusCommFun.clearOrderPriceStatus(con, ordPk);
                    CoreOrderReviewLaw.clearOrderLawRecord(con, ordPk);
                }

                con.commit();
                cro.setV_errCode(0);
            }
            else {
                cro.setV_errCode(-1);
                cro.setV_errMsg("合同已生效或者处于交货期通过之前的状态，不能直接退回录入状态！");
            }
        }
        catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setV_errMsg(e.getMessage());
                e.printStackTrace();
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return cro;
    }


    public CoreReturnObject getThOrderStatus(String ordPk){
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        CoreOrderInfoUpdate cou =new CoreOrderInfoUpdate();
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            // 查询是否为天淮成品合同的母合同
            SqlBuilder b = new SqlBuilder("CoreOrderApproval.getOrderHeadStatusByCustm");
            b.Fill(new String[]{ordPk}) 
            ;
            CoreOrderStatus orderStatus = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, CoreOrderStatus.class);
            if (orderStatus != null && Integer.parseInt(orderStatus.getOrderSts()) < 12020212 && orderStatus.getOrderNo().startsWith("TH")) {
                con.rollback();
                core.setV_errMsg("请等待天淮合同技术评审，交货期通过！");
                core.setResult(-1);
                return core;
            }
            if (orderStatus != null && Integer.parseInt(orderStatus.getOrderSts()) >= 12020212 && orderStatus.getOrderNo().startsWith("TH")) {
                con.rollback();
                core.setV_errMsg("天淮合同技术评审，交货期已通过！无法修改");
                core.setResult(2);
                return core;
            }

            b = new SqlBuilder("FrmTHOrderManage.doQueryZcState");
            b.Fill(new String[]{ordPk});
            SlmOrderHeadCopy slmOrderHead = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmOrderHeadCopy.class);
            if (slmOrderHead != null &&!slmOrderHead.getThOrderFalgZc().equals("1")) {
                con.rollback();
                core.setV_errMsg("配套服务科未确认下发，无法提报！");
                core.setResult(1);
                return core;
            }
            core.setResult(0);
        }catch (SQLException e) {

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

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