package com.steering.pss.ydm.pipemanage;

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.judge.model.PlnZyZgMEntity;
import com.steering.pss.plnsaleord.planStove.StoveHelper;
import com.steering.pss.plnsaleord.planStove.entity.YdmBcInlistEntity;
import com.steering.pss.plnsaleord.stove.PlanFurnProduction;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;
import com.steering.pss.ydm.entity.*;
import org.springframework.beans.BeanUtils;

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 FrmBillInStorage extends DBCommon {

    public static void main(String[] args) {
        System.out.println(Integer.parseInt("6.0"));
    }

    /**
     * 未接收查询
     */
    public CoreReturnObject doQuery(String startTime, String endTime, String billNo,String OrderNo) {
        String sql = CoreXmlSqlParsersFactory.getSql("FrmBillInStorage.doQuery");
        String condition = "";
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(startTime)) {
            condition += " AND T.CREATE_TIME >= TO_DATE('" + startTime + "','YYYY-MM-DD HH24:MI:SS')";
            condition += " AND T.CREATE_TIME <= TO_DATE('" + endTime + "','YYYY-MM-DD HH24:MI:SS')";
        }
        if (!StringUtils.isEmpty(billNo)) {
            condition += " AND T.BILL_NO LIKE '%" + billNo + "%'";
        }
        if (!StringUtils.isEmpty(OrderNo)) {
            condition += " AND t.ORDER_NO LIKE '%"+OrderNo+"%' ";
        }
        sql = sql.replaceAll("#condition#", condition);
        return this.getData(sql);
    }


    /**
     * 查询发货实绩表的材料信息
     */
    public CoreReturnObject queryMativery(ArrayList<String> list) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmBillInStorage.queryMativery");
        return this.getData(sql, list.toArray());
    }


    /**
     * 已接收查询
     *
     * @return
     */
    public CoreReturnObject doQuery1(String startTime, String endTime, String billNo, String judgeStoveNo) {
        return doQuery1(startTime,endTime,billNo,judgeStoveNo,"");
    }

    public CoreReturnObject doQuery1(String startTime, String endTime, String billNo, String judgeStoveNo,String orderNo) {
        return doQuery1(startTime,endTime,billNo,judgeStoveNo,"","");
    }
    public CoreReturnObject doQuery1(String startTime, String endTime, String billNo, String judgeStoveNo,String orderNo,String flagStoveNo) {
        String sql = CoreXmlSqlParsersFactory.getSql("FrmBillInStorage.doQuery1");
        String condition = "";
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(startTime)) {
            condition += " AND T.CREATE_TIME >= TO_DATE('" + startTime + "','YYYY-MM-DD HH24:MI:SS')";
            condition += " AND T.CREATE_TIME <= TO_DATE('" + endTime + "','YYYY-MM-DD HH24:MI:SS')";
        }
        if (!StringUtils.isEmpty(billNo)) {
            condition += " AND c.bill_No LIKE '%" + billNo + "%'";
        }
        if (!StringUtils.isEmpty(judgeStoveNo)) {
            condition += " AND T.JUDGE_STOVE_NO LIKE '%" + judgeStoveNo + "%'";
        }
        if (!StringUtils.isEmpty(orderNo)) {
            condition += " AND T.ORDER_NO LIKE '%" + orderNo + "%'";
        }
        if (!StringUtils.isEmpty(flagStoveNo)) {
            condition += " AND T.FLAG_STOVE_NO_ZG LIKE '%" + flagStoveNo + "%'";
        }
        sql = sql.replaceAll("#condition#", condition);
        return this.getData(sql);
    }

    /**
     * 接收
     *
     * @param list
     * @return
     */
    public CoreReturnObject doAdd(ArrayList<String> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "";
        String nextProcessCode = "";
        String nextProcessName = "";
        try {
            con.setAutoCommit(false);
            //回写排产支数、重量
            String updatePlnOrderZgS = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.updatePlanOrderZgS");
            //新增下线点实绩
            String sqlInMil = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.addMilInStore");
            for (String json : list) {
                FrmBillInStorageEntity billInStorageEntity = EntityTool.getEntityByGson(json, FrmBillInStorageEntity.class);
                // 获取轧管订单
                SqlBuilder getOrderZgs = new SqlBuilder("FrmBillInStorage.doQueryOrderZgS");
                getOrderZgs.Fill(new String[]{billInStorageEntity.getOrderNo() + "/" + billInStorageEntity.getOrderSeq()});
                PlnOrderZgSEntity plnOrdZgS = EntityTool.getEntityBySqlNoClsCon(getOrderZgs.toString(), con, PlnOrderZgSEntity.class);
                if (plnOrdZgS == null) {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("没有找到对应的轧管订单!");
                    return cro;
                }
                QualityDesignTool.nullConverNullString(plnOrdZgS);

                String inDocCq = getInDocCq(con);//获取产权入库单号
                String judegeNo = StoveHelper.queryMaxJudgeNoWg(con);
                // 本部的6位炉号
                if(billInStorageEntity.getStoveNo().length()==6){
                    judegeNo = billInStorageEntity.getStoveNo();
                }
                // 获取查询是否入库判定炉号
                SqlBuilder getJudgeStoveNo = new SqlBuilder("FrmBillInStorage.doGetJudgeStoveNo");
                getJudgeStoveNo.Fill(new String[]{billInStorageEntity.getJudgeStoveNo(),billInStorageEntity.getBillNo()});
                PlnZyZgMEntity plnZyZgMEntity = EntityTool.getEntityBySqlNoClsCon(getJudgeStoveNo.toString(), con, PlnZyZgMEntity.class);
                if (plnZyZgMEntity != null && !StringUtils.isEmpty(plnZyZgMEntity.getFlagStoveNo())) {
                    judegeNo = plnZyZgMEntity.getFlagStoveNo();
                }
                // 获取查询喷印炉号
                SqlBuilder getFlagHeatNo = new SqlBuilder("FrmBillInStorage.doFlagHeatNo");
                getFlagHeatNo.Fill(new String[]{billInStorageEntity.getJudgeStoveNo()});
                plnZyZgMEntity = EntityTool.getEntityBySqlNoClsCon(getFlagHeatNo.toString(), con, PlnZyZgMEntity.class);
                if (plnZyZgMEntity != null && !StringUtils.isEmpty(plnZyZgMEntity.getFlagStoveNo())) {
                    judegeNo = plnZyZgMEntity.getFlagStoveNo();
                }

                if (plnOrdZgS.getWholeBacklogDesc().contains("镦拔扩")) {
                    nextProcessCode = "E";
                    nextProcessName = "镦拔扩";
                } else if (plnOrdZgS.getWholeBacklogDesc().contains("热处理")) {
                    nextProcessCode = "F";
                    nextProcessName = "热处理";
                } else if (plnOrdZgS.getWholeBacklogDesc().contains("加工")) {
                    nextProcessCode = "G";
                    nextProcessName = "管加工";
                } else {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("工艺制程有问题，请核实!");
                    return cro;
                }


                if (nextProcessCode.equals("E")) {
                    sql = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.SelectDbkS");//查询镦拔扩订单
                } else if (nextProcessCode.equals("F")) {
                    sql = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.SelectRclS");//查询热处理订单
                } else if (nextProcessCode.equals("G")) {
                    sql = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.SelectGxS");//查询管加工订单
                }
                sql = EntityTool.fillSqlByEntity(sql, plnOrdZgS);
                ps = con.prepareStatement(sql);
                rs = ps.executeQuery();
                List<PlnOrderZgSEntity> allOrderS = EntityTool.getEntitysByRs(rs, PlnOrderZgSEntity.class);
                rs.close();
                ps.close();

                YdmZcInlistEntity ydmInList = new YdmZcInlistEntity();
                billInStorageEntity.setInstockDoc(inDocCq);
                billInStorageEntity.setBelongCode("002001001");
                billInStorageEntity.setBelongName("生产计划部");
                billInStorageEntity.setJudgeNo(judegeNo);
                billInStorageEntity.setPlineCode(plnOrdZgS.getPlineCode());
                billInStorageEntity.setPlineName(plnOrdZgS.getPlineName());
                for (YdmBcButtressEntity buttressEntity : billInStorageEntity.getButtressList()) {
                    billInStorageEntity.setLocationNo(buttressEntity.getLocationNo());
                    billInStorageEntity.setLaryNo(buttressEntity.getLaryNo());
                    BeanUtils.copyProperties(billInStorageEntity, ydmInList);
                    ydmInList.setOrderNoNew(plnOrdZgS.getOrderNo());
                    ydmInList.setActCount(buttressEntity.getActCount());
                    ydmInList.setOrderSeqNew(plnOrdZgS.getOrderSeq());
                    ydmInList.setOrdPkNew(plnOrdZgS.getOrdPk());
                    ydmInList.setOrdLnPkNew(plnOrdZgS.getOrdLnPk());
                    ydmInList.setOrdLnDlyPkNew(plnOrdZgS.getOrdLnDlyPk());
                    ydmInList.setProOrderNo(plnOrdZgS.getOrderNo() + '/' + plnOrdZgS.getOrderSeq());
                    ydmInList.setProOrderId(plnOrdZgS.getProPlanId());
                    ydmInList.setGxPlanNo(plnOrdZgS.getGxPlanNo());
                    ydmInList.setCraftFileNo(plnOrdZgS.getCraftFileNo());
                    ydmInList.setCraftSeq(plnOrdZgS.getCraftSeq());
                    ydmInList.setGxPlanNo(plnOrdZgS.getGxPlanNo());
                    ydmInList.setModelCode(plnOrdZgS.getModelCode());
                    ydmInList.setModelDesc(plnOrdZgS.getModelDesc());
                    ydmInList.setNextProcessCdoe(nextProcessCode);
                    ydmInList.setNextProcessName(nextProcessName);
                    ydmInList.setCraftFileNo(plnOrdZgS.getCraftFileNo());
                    ydmInList.setCraftSeq(plnOrdZgS.getCraftSeq());
                    ydmInList.setTarget(plnOrdZgS.getDecision());
                    String insertCqSql = CoreXmlSqlParsersFactory.getSql("FrmBillInStorage.doAddInListData");
                    insertCqSql = EntityTool.fillSqlByEntity(insertCqSql, ydmInList);
                    ps = con.prepareStatement(insertCqSql);
                    ps.executeUpdate();
                    ps.close();
                }

                ydmInList.setJudgeStoveNo(judegeNo);
                //查询半成品表
                sql = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.SelectMatBc");
                sql = EntityTool.fillSqlByEntity(sql, ydmInList);
                ps = con.prepareStatement(sql);
                rs = ps.executeQuery();
                List<MatBcMEntity> matBcEntity = EntityTool.getEntitysByRs(rs, MatBcMEntity.class);
                rs.close();
                ps.close();

                for (int m = 0; m < allOrderS.size(); m++) {
                    double allOrderSWgt = Double.parseDouble(allOrderS.get(m).getWeigthS());//订单量
                    double zyMWgt = Double.parseDouble(allOrderS.get(m)
                            .getPlnInsingleWt().equals("") ? "0" : allOrderS.get(m)
                            .getPlnInsingleWt());//炉计划已挂订单量

                    for (int n = 0; n < matBcEntity.size(); n++) {
                        MatBcMEntity matBcTity = new MatBcMEntity();
                        if (m + 1 == allOrderS.size()) {
                            matBcTity.setJudgeStoveNo(matBcEntity.get(n)
                                    .getJudgeStoveNo());
                            matBcTity.setBatchNo(matBcEntity.get(n).getBatchNo());
                            matBcTity.setMatNo(matBcEntity.get(n).getMatNo());
                            matBcTity.setProPlanIdNext(allOrderS.get(m)
                                    .getProPlanId());
                            matBcTity.setGxPlanNoNext(allOrderS.get(m)
                                    .getGxPlanNo());
                            String updateMatBcSql = CoreXmlSqlParsersFactory
                                    .getSql("FrmSemiFinish.UpdateMatBcPro");
                            updateMatBcSql = EntityTool.fillSqlByEntity(
                                    updateMatBcSql, matBcTity);
                            ps = con.prepareStatement(updateMatBcSql);
                            ps.executeUpdate();
                            ps.close();
                        } else {
                            if (allOrderSWgt > Double.parseDouble(matBcEntity.get(n).getActWeight()) + zyMWgt) {
                                matBcTity.setJudgeStoveNo(matBcEntity.get(n)
                                        .getJudgeStoveNo());
                                matBcTity.setBatchNo(matBcEntity.get(n).getBatchNo());
                                matBcTity.setMatNo(matBcEntity.get(n).getMatNo());
                                matBcTity.setProPlanIdNext(allOrderS.get(m)
                                        .getProPlanId());
                                matBcTity.setGxPlanNoNext(allOrderS.get(m)
                                        .getGxPlanNo());
                                String updateMatBcSql = CoreXmlSqlParsersFactory
                                        .getSql("FrmSemiFinish.UpdateMatBcPro");
                                updateMatBcSql = EntityTool.fillSqlByEntity(
                                        updateMatBcSql, matBcTity);
                                ps = con.prepareStatement(updateMatBcSql);
                                ps.executeUpdate();
                                ps.close();
                                zyMWgt = zyMWgt + Double
                                        .parseDouble(matBcEntity.get(n).getActWeight());
                            }
                        }
                    }
                    PlanFurnProduction.addPlnFurnWg(allOrderS.get(m)
                                    .getProPlanId(), allOrderS.get(m)
                                    .getGxPlanNo(),
                            ydmInList.getCreateName(), ydmInList.getJudgeStoveNo(), nextProcessCode,
                            con);
                }
                //生成下线点实绩编号
                String resultNo = "";
                sql = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.SelectMaxresultNo");
                ps = con.prepareStatement(sql);
                rs = ps.executeQuery();
                if (rs.next()) {
                    resultNo = rs.getString("RESULT_NO");
                }
                rs.close();
                ps.close();

                // 计算支数与重量
                int actNum = Integer.parseInt(billInStorageEntity.getActCount());
                double actWgt = Double.parseDouble(ydmInList.getActWeight());

                ydmInList.setResultNo(resultNo);
                ydmInList.setActCount(String.valueOf(actNum));
                ydmInList.setActWeight(String.valueOf(actWgt));
                ydmInList.setJudgeStoveNo(ydmInList.getJudgeStoveNo() + "-01");
                ydmInList.setProPlanId(plnOrdZgS.getProPlanId());
                ydmInList.setGxPlanNo(plnOrdZgS.getGxPlanNo());
                String insertInStoreSql = EntityTool.fillSqlByEntity(sqlInMil, ydmInList);
                ps = con.prepareStatement(insertInStoreSql);
                ps.executeUpdate();
                ps.close();

                plnOrdZgS.setFinishnum(String.valueOf(actNum));
                plnOrdZgS.setFinishweight(String.valueOf(actWgt));
                String updatePlnSql = EntityTool.fillSqlByEntity(updatePlnOrderZgS, plnOrdZgS);
                ps = con.prepareStatement(updatePlnSql);
                ps.executeUpdate();
                ps.close();

                // 复制性能
                ydmInList.setJudgeStoveNo(billInStorageEntity.getJudgeStoveNo());
                ydmInList.setCrafNo(plnOrdZgS.getCraftFileNo());
                ydmInList.setIndexSeq(plnOrdZgS.getIndexSeq());
                ydmInList.setOrdLnDlyPk(plnOrdZgS.getOrdLnDlyPk());
                ydmInList.setCic(plnOrdZgS.getCicGp());
                ydmInList.setPic(plnOrdZgS.getPic());
                String copyJyh = CoreXmlSqlParsersFactory.getSql("FrmBillInStorage.doCopyCheck");
                copyJyh = EntityTool.fillSqlByEntity(copyJyh, ydmInList);
                ps = con.prepareStatement(copyJyh);
                ps.executeUpdate();
                ps.close();

            }
            con.commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            cro.setV_errCode(-1);
            if (con != null) {
                try {
                    cro.setV_errMsg(e.getMessage());
                    con.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (Exception e2) {
            }
        }

        return cro;
    }

    public CoreReturnObject doDelete(ArrayList<String> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "";
        int actCount = 0;
        try {
            con.setAutoCommit(false);
            for (String json : list) {
                YdmBcInlistEntity ydmBcInlistEntity = EntityTool.getEntityByGson(json, YdmBcInlistEntity.class);
                sql = CoreXmlSqlParsersFactory.getSql("FrmBillInStorage.SelectMatZcCount");
                ps = con.prepareStatement(sql);
                ps.setObject(1, ydmBcInlistEntity.getJudgeStoveNo());
                ps.setObject(2, ydmBcInlistEntity.getBatchNo());
                ps.setObject(3, ydmBcInlistEntity.getBatchGroudNo());
                ps.setObject(4, ydmBcInlistEntity.getOrderNo());
                rs = ps.executeQuery();
                if(rs.next())
                {
                    actCount = Integer.parseInt(rs.getString("ACT_COUNT"));
                }
                ps.close();
                rs.close();
                if(actCount != Integer.parseInt(ydmBcInlistEntity.getActCount()))
                {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("库存支数已变化,不允许进行撤销!");
                    return cro;
                }
                sql = CoreXmlSqlParsersFactory
                        .getSql("FrmBillInStorage.SelectApplyMatZcCount");
                ps = con.prepareStatement(sql);
                ps.setObject(1, ydmBcInlistEntity.getJudgeStoveNo());
                ps.setObject(2, ydmBcInlistEntity.getBatchNo());
                ps.setObject(3, ydmBcInlistEntity.getBatchGroudNo());
                ps.setObject(4, ydmBcInlistEntity.getOrderNo());
                rs = ps.executeQuery();
                if (rs.next()) {
                    actCount = Integer.parseInt(rs.getString("APPLY_ACT_COUNT"));
                }
                ps.close();
                rs.close();
                if (actCount >0) {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("已有申请判定支数,不允许进行撤销!");
                    return cro;
                }

                PlanFurnProduction.deletePlnFurnWg(ydmBcInlistEntity.getProPlanId(),
                        ydmBcInlistEntity.getJudgeStoveNo(),
                        con);

                String insertCqSql = CoreXmlSqlParsersFactory.getSql("FrmBillInStorage.doDeleteInListData");
                insertCqSql = EntityTool.fillSqlByEntity(insertCqSql, ydmBcInlistEntity);
                ps = con.prepareStatement(insertCqSql);
                ps.executeUpdate();
                ps.close();

            }
            con.commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            cro.setV_errCode(-1);
            if (con != null) {
                try {
                    cro.setV_errMsg(e.getMessage());
                    con.rollback(); // 回滚事务
                } catch (Exception e2) {
                }
            }
        } finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (Exception e2) {
            }
        }
        return cro;
    }

    /***
     * 生成产c出入库单号
     * @return
     * @throws SQLException
     */
    public String getInDocCq(Connection con) {
        String inDoc = "";
        String sql = CoreXmlSqlParsersFactory.getSql("FrmSemiFinish.SelectMaxInDoc");
        PreparedStatement psta = null;
        try {
            psta = con.prepareStatement(sql);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                inDoc = rs.getString("INSTOCK_DOC");
            }
            rs.close();
            psta.close();
        } catch (SQLException e) {

            e.printStackTrace();
        }
        return inDoc;
    }

    /***
     * 查询库位信息
     * @param storageNo
     * @return
     */
    public CoreReturnObject doQueryLocation(String storageNo) {
        return this.getDataBySqlID("FrmBillInStorage.doQueryLocation", new Object[]{storageNo});
    }

    /***
     * 根据数据权限绑定仓库
     * @return
     */
    public CoreReturnObject doQueryStorageArr(String[] arr) {
        String sql = CoreXmlSqlParsersFactory.getSql("FrmBillInStorage.doQueryStorageArr");
        sql += CoreConverter.toSqlConditionString("T.STORAGE_NO", arr);
        sql += " ORDER BY T.STORAGE_NO ASC";
        return this.getData(sql);
    }

    public CoreReturnObject getWarehousePermissionsStore(String[] validDataPurviewIds) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmBillInStorage.getWarehousePermissionsStore");
        sql += CoreConverter.toSqlConditionString("T.MANAGEMENT_NO",
                validDataPurviewIds);
        return this.getData(sql);
    }
}
