package com.steering.pss.plnsaleord.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.order.baseMethod.CoreAdjustWellMonth;
import com.steering.pss.plnsaleord.order.model.PlnOrderZgSEntity;
import com.steering.pss.plnsaleord.order.model.PlnSaleordSetEntity;
import com.steering.pss.plnsaleord.processOrder.CoreProcessFinish;

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

/**
 * 导入excl设置合同状态
 * @author xiaohai
 */

public class CoreOrderStatusSet extends DBCommon {

    /**
     * 查询导入设置记录
     * @param list
     * @return
     */
    public CoreReturnObject queryOrderSetLog(ArrayList<Object> list) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreOrdStatusSet.queryOrderSetLog", list
                .toArray());
        return cro;
    }

    /**
     * 保存导入日志文本
     * @param list
     * @return
     */
    public CoreReturnObject saveOrderSetlog(ArrayList<PlnSaleordSetEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();

        // 更新合同状态
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdStatusSet.insertOrderSetlog");
        for (int i = 0; i < list.size(); i++) {
            String sqlUp = EntityTool.fillSqlByEntity(sql, list.get(i));
            sqllist.add(sqlUp);
            parmlist.add(new Object[] {});
        }
        cro = this.setData(sqllist, parmlist);
        return cro;
    }

    /**
     * 保存导入修改单倍坯长（轧管排产）
     * @param 
     * @return
     */
    public CoreReturnObject updatePlnZgLenGpSin(ArrayList<String> jsonList) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            List<PlnOrderZgSEntity> list = PlnHelper.jsonsToEntityList(
                    PlnOrderZgSEntity.class, jsonList);
            PreparedStatement ps = null;
            ResultSet rs = null;
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CorePlnZgMStoGp.queryZgMSStatus");
            for (PlnOrderZgSEntity zgSEntity : list) {
                ps = conn.prepareStatement(sql);
                ps.setObject(1, zgSEntity.getProPlanId());
                ps.setObject(2, zgSEntity.getGxPlanNo());
                rs = ps.executeQuery();
                if (rs.next()) {
                    if (!rs.getString("EXE_STATUS").equals("0")) {
                        cro.setV_errMsg("轧管订单：" + zgSEntity.getProPlanId()+"/"+zgSEntity.getGxPlanNo()
                                + ",不是计划状态,不允许导入。");
                        return cro;
                    }
                }
                else {
                    cro.setV_errMsg("找不到轧管订单：" + zgSEntity.getProPlanId()+"/"+zgSEntity.getGxPlanNo()
                                + "。");
                    return cro;
                }
                rs.close();
                ps.close();

                // 更新轧管排产单倍坯长
                String sqlupdate = EntityTool.fillSqlByEntity(
                        CoreXmlSqlParsersFactory
                                .getSql("CoreOrdStatusSet.updatePlnZgLenGpSin"),
                        zgSEntity);
                ps = conn.prepareStatement(sqlupdate);
                ps.executeUpdate();
                ps.close();
            }
            cro.setV_errMsg("导入成功!");
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /***
     * 同步考核年月
     * @param list
     * @return
     */
    public CoreReturnObject updateOrderCheckMoth(ArrayList<PlnSaleordSetEntity> list)
    {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement psta = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            ArrayList<String> sqllist = new ArrayList<String>();
            for (PlnSaleordSetEntity checkEntity : list)
            {
                String updateSql = CoreXmlSqlParsersFactory.getSql("CoreOrderStatusSet.updateOrderCheckMoth");
                updateSql = EntityTool.fillSqlByEntity(updateSql,checkEntity);
                sqllist.add(updateSql);
            }

            cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
            if(cro.getV_errMsg().equals(""))
            {
                cro.setV_errMsg("同步成功!");
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if (conn != null) {
                try {
                    cro.setV_errMsg(e.getMessage());
                    conn.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (Exception e2) {
            }
        }
        return cro;
    }
    /**
     * 同步状态
     * @param list
     * @return
     */
    public CoreReturnObject updateOrderStatus(
            ArrayList<PlnSaleordSetEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement psta = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String systime = getData();
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            // 更新合同状态
            int count = 0;
            String errMessage = "";
            for (int i = 0; i < list.size(); i++) {
                String sqlOr = CoreXmlSqlParsersFactory
                        .getSql("CoreOrdStatusSet.queryPlnOrdStatus");
                psta = conn.prepareStatement(sqlOr);
                psta.setObject(1, list.get(i).getOrdLnDlyPk());
                ResultSet reSult = psta.executeQuery();
                if (reSult.next()) {
                    PreparedStatement ps = null;
                    String sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrdStatusSet.setOrdProcStatusByPk");
                    String ordLnPk = "";// 和同行pk
                    if (reSult.getString("ORD_LN_PK") == null) {
                        errMessage = "第" + String.valueOf(i + 1)
                                + "条数据，未找到对应交货行。";
                        break;
                    }
                    ordLnPk = reSult.getString("ORD_LN_PK");
                    ps = conn.prepareStatement(sql);
                    ps.setObject(1, list.get(i).getEndStatus());
                    ps.setObject(2, list.get(i).getUpdateMan());
                    ps.setObject(3, list.get(i).getUpdateMan());
                    ps.setObject(4,systime);
                    ps.setObject(5, list.get(i).getOrdLnDlyPk());
                    ps.setObject(6, list.get(i).getPlnDivideId());
                    ps.executeUpdate();
                    ps.close();

                    if (list.get(i).getEndStatus().equals("2")) {
                        sql = CoreXmlSqlParsersFactory
                                .getSql("CoreOrdStatusSet.setOrderStatusByPk");
                        ps = conn.prepareStatement(sql);
                        ps.setObject(1, list.get(i).getEndStatus());
                        ps.setObject(2, list.get(i).getOrdLnDlyPk());
                        ps.executeUpdate();
                        ps.close();
                    }

                    // 已接收
                    if (list.get(i).getEndStatus().equals("1")) {
                        boolean isChange = true;
                        sql = CoreXmlSqlParsersFactory
                                .getSql("CoreOrdStatusSet.queryPlnOrdStatus");
                        psta = conn.prepareStatement(sql);
                        psta.setObject(1, list.get(i).getOrdLnDlyPk());
                        ResultSet rs = psta.executeQuery();
                        while (rs.next()) {
                            if (rs.getString("PLANSTATUS") == null
                                    || !rs.getString("PLANSTATUS").trim()
                                            .equals("1")) {
                                isChange = false;
                            }
                        }
                        rs.close();
                        psta.close();

                        if (isChange) {
                            sql = CoreXmlSqlParsersFactory
                                    .getSql("CoreOrdStatusSet.setOrderStatusByPk");
                            ps = conn.prepareStatement(sql);
                            ps.setObject(1, list.get(i).getEndStatus());
                            ps.setObject(2, list.get(i).getOrdLnDlyPk());
                            ps.executeUpdate();
                            ps.close();
                        }
                    }
                    // 生产完成
                    if (list.get(i).getEndStatus().equals("4")) {
                        boolean isChange = true;
                        sql = CoreXmlSqlParsersFactory
                                .getSql("CoreOrdStatusSet.queryPlnOrdStatus");
                        psta = conn.prepareStatement(sql);
                        psta.setObject(1, list.get(i).getOrdLnDlyPk());
                        ResultSet rs = psta.executeQuery();
                        while (rs.next()) {
                            if (rs.getString("PLANSTATUS") == null
                                    || !rs.getString("PLANSTATUS").trim()
                                            .equals("4")) {
                                isChange = false;
                            }
                        }
                        rs.close();
                        psta.close();

                        if (isChange) {
                            sql = CoreXmlSqlParsersFactory
                                    .getSql("CoreOrdStatusSet.setOrderStatusByPk");
                            ps = conn.prepareStatement(sql);
                            ps.setObject(1, list.get(i).getEndStatus());
                            ps.setObject(2, list.get(i).getOrdLnDlyPk());
                            ps.executeUpdate();
                            ps.close();

                            // 工序生产完成
                            CoreProcessFinish.setOrdLnDlyProc(conn, list.get(i)
                                    .getOrdLnDlyPk(), "4");

                            if (!reSult.getString("ORDER_SOURCE")
                                    .equals("备料需求")) {
                                sql = CoreXmlSqlParsersFactory
                                        .getSql("CoreOrdStatusSet.setDeliveryStatusByPk");
                                ps = conn.prepareStatement(sql);
                                ps.setObject(1, "12020502");
                                ps.setObject(2, list.get(i).getOrdLnDlyPk());
                                ps.executeUpdate();
                                ps.close();

                                // 和同行生产状态设置
                                setOrdLineFinishSc(conn, ordLnPk);
                            }
                        }
                    }
                    // 缴库完成
                    if (list.get(i).getEndStatus().equals("5")) {
                        boolean isChange = true;
                        sql = CoreXmlSqlParsersFactory
                                .getSql("CoreOrdStatusSet.queryPlnOrdStatus");
                        psta = conn.prepareStatement(sql);
                        psta.setObject(1, list.get(i).getOrdLnDlyPk());
                        ResultSet rs = psta.executeQuery();
                        while (rs.next()) {
                            if (rs.getString("PLANSTATUS") == null
                                    || !rs.getString("PLANSTATUS").trim()
                                            .equals("5")) {
                                isChange = false;
                            }
                        }
                        rs.close();
                        psta.close();

                        if (isChange) {
                            sql = CoreXmlSqlParsersFactory
                                    .getSql("CoreOrdStatusSet.setOrderStatusByPk");
                            ps = conn.prepareStatement(sql);
                            ps.setObject(1, list.get(i).getEndStatus());
                            ps.setObject(2, list.get(i).getOrdLnDlyPk());
                            ps.executeUpdate();
                            ps.close();

                            // 工序生产完成
                            CoreProcessFinish.setOrdLnDlyProc(conn, list.get(i)
                                    .getOrdLnDlyPk(), "4");

                            if (!reSult.getString("ORDER_SOURCE")
                                    .equals("备料需求")) {
                                sql = CoreXmlSqlParsersFactory
                                        .getSql("CoreOrdStatusSet.setDeliveryStatusByPk");
                                ps = conn.prepareStatement(sql);
                                ps.setObject(1, "12020602");
                                ps.setObject(2, list.get(i).getOrdLnDlyPk());
                                ps.executeUpdate();
                                ps.close();

                                // 和同行缴库状态设置
                                setOrdLineFinishJk(conn, ordLnPk);
                            }
                        }
                    }

                    // 保存记录
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreOrdStatusSet.updateOrderSetlog");
                    ps = conn.prepareStatement(sql);
                    ps.setObject(1, list.get(i).getEndStatus());
                    ps.setObject(2, list.get(i).getOrdLnDlyPk());
                    ps.setObject(3, list.get(i).getPlnDivideId());
                    ps.setObject(4, list.get(i).getPlnDivideId());
                    ps.executeUpdate();
                    ps.close();
                    count++;
                }
                else {
                    errMessage = "第" + String.valueOf(i + 1) + "条数据，未找到对应交货行。";
                    break;
                }
            }
            conn.commit();
            cro.setV_errMsg(count + "条同步成功，"
                    + String.valueOf(list.size() - count) + "条同步失败！\n"
                    + errMessage);
        }
        catch (SQLException sqle) {
            try {
                if (conn != null){
                    conn.rollback();   
                }         
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        catch (ParseException ex) {
            if (conn != null) {
                try {
                    conn.rollback();
                }
                catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(ex.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }

    /***
     * 获取当前时间前
     * @return
     */
    public static  String getData()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 12);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return  df.format(calendar.getTime());
    }
    /**
     * 同步月份
     * @param list
     * @return
     */
    public CoreReturnObject updateOrderStatusMonth(
            ArrayList<PlnSaleordSetEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreOrdStatusSet.setOrderStatusMonthByPk");
            String sqlP = CoreXmlSqlParsersFactory
                    .getSql("CoreOrdStatusSet.setOrderStatusMonthByPkProc");
            String sqlQ = CoreXmlSqlParsersFactory
                    .getSql("CoreOrdStatusSet.queryRollWellMonth");
            for (int i = 0; i < list.size(); i++) {
                PreparedStatement psta = null;
                ps = conn.prepareStatement(sqlP);
                ps.setObject(1, list.get(i).getRollMonth());
                ps.setObject(2, list.get(i).getOrdLnDlyPk());
                ps.setObject(3, list.get(i).getPlnDivideId());
                ps.executeUpdate();
                ps.close();

                psta = conn.prepareStatement(sqlQ);
                psta.setObject(1, list.get(i).getOrdLnDlyPk());
                psta.setObject(2, list.get(i).getPlnDivideId());
                ResultSet rst = psta.executeQuery();
                if (rst.next()) {
                    if (rst.getString("ORDER_SOURCE") != null
                            && rst.getString("ORDER_SOURCE").trim().equals(
                                    "销售合同")) {
                        ps = conn.prepareStatement(sql);
                        ps.setObject(1, list.get(i).getRollMonth());
                        ps.setObject(2, list.get(i).getOrdLnDlyPk());
                        ps.executeUpdate();
                        ps.close();

                        if (rst.getString("ROLL_WELL_MONTH") != null
                                && rst.getString("ROLL_WELL_MONTH").length() >= 7) {
                            String rollWellMonth = rst
                                    .getString("ROLL_WELL_MONTH");
                            if (!list.get(i).getRollMonth().equals(
                                    rollWellMonth)
                                    && !rollWellMonth.equals("")) {
                                int mon = 0;
                                int year = Integer.parseInt(list.get(i)
                                        .getRollMonth().substring(0, 4));
                                int month = Integer.parseInt(list.get(i)
                                        .getRollMonth().substring(5, 7));
                                int yearWell = Integer.parseInt(rollWellMonth
                                        .substring(0, 4));
                                int monthWell = Integer.parseInt(rollWellMonth
                                        .substring(5, 7));
                                mon = (year - yearWell) * 12
                                        + (month - monthWell);
                                CoreAdjustWellMonth.adjustWellMonth(conn, list
                                        .get(i).getOrdLnDlyPk(), mon);
                            }
                        }
                    }
                }
                rst.close();
                psta.close();
            }
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 删除
     * @param list
     * @return
     */
    public CoreReturnObject deleteOrderStatus(
            ArrayList<PlnSaleordSetEntity> list) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        for (int i = 0; i < list.size(); i++) {
            sqllist.add("CoreOrdStatusSet.deleteOrderStatus");
            parmlist
                    .add(new Object[] { list.get(i).getOrdLnDlyPk(),
                            list.get(i).getPlnDivideId(),
                            list.get(i).getPlnDivideId() });
        }
        cro = this.setDataById(sqllist, parmlist);
        return cro;
    }

    /**
     * 设置合同行生产完成
     * @param ordLnPk 合同行Pk
     * @throws SQLException
     */
    public void setOrdLineFinishSc(Connection conn, String ordLnPk)
            throws SQLException {
        PreparedStatement psta = null;
        int count1 = 0;
        int count2 = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdStatusSet.getNumDeliveryByLine");
        String sqlUp = CoreXmlSqlParsersFactory
                .getSql("CoreOrdStatusSet.setOrdLineStatus");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            count1 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        sql = sql + " AND SUBSTR(T.DELIVERY_STATUS, 0, 6) = '120205'";
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        rs = psta.executeQuery();
        if (rs.next()) {
            count2 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        if (count2 > 0 && count1 > 0 && count1 < count2) {
            // 已开始生产
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020501");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
        if (count2 > 0 && count1 > 0 && count1 == count2) {
            // 生产完成
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020502");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
    }

    /**
     * 设置合同行缴库完成
     * @param ordLnPk 合同行Pk
     * @throws SQLException
     */
    public void setOrdLineFinishJk(Connection conn, String ordLnPk)
            throws SQLException {
        PreparedStatement psta = null;
        int count1 = 0;
        int count2 = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrdStatusSet.getNumDeliveryByLine");
        String sqlUp = CoreXmlSqlParsersFactory
                .getSql("CoreOrdStatusSet.setOrdLineStatus");
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            count1 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        sql = sql + " AND SUBSTR(T.DELIVERY_STATUS, 0, 6) = '120206'";
        psta = conn.prepareStatement(sql);
        psta.setObject(1, ordLnPk);
        rs = psta.executeQuery();
        if (rs.next()) {
            count2 = rs.getInt("DELIVERY_NUM");
        }
        rs.close();
        psta.close();

        if (count2 > 0 && count1 > 0 && count1 < count2) {
            // 已开始生产
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020601");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
        if (count2 > 0 && count1 > 0 && count1 == count2) {
            // 生产完成
            psta = conn.prepareStatement(sqlUp);
            psta.setObject(1, "12020602");
            psta.setObject(2, ordLnPk);
            psta.executeUpdate();
            psta.close();
        }
    }

}