using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSSoft.Common;
using ICSSoft.Entity;

namespace ICSSoft.DataProject
{
    public class ISComplete
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        public string ConfirmRd08(List<Complete> Bills)
        {
            DataTable dtNew1 = null;
            DataTable dtNew2 = null;
            string mag = "";
            string sql = "";
            string connS = "";
            string newsql="";
            VouchKey key = new VouchKey();
            SqlConnection conn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();
            try
            {
                foreach (Complete head in Bills)
                {
                    connS = string.Format(connString, head.WorkPoint);
                    conn = new System.Data.SqlClient.SqlConnection(connS);
                    conn.Open();
                    SqlTransaction sqlTran = conn.BeginTransaction();
                    cmd = new SqlCommand();
                    cmd.Transaction = sqlTran;
                    cmd.Connection = conn;
                    foreach (Completes body in head.details)
                    {
                        if (head.SourceType == "生产订单")
                        {
                            newsql = "where a.MoCode='{0}' and b.SortSeq='{1}'";
                            newsql = string.Format(newsql, head.SourceCode, body.Sequence);
                            #region 齐套检验
                            sql = @" select cValue from AccInformation where cName=N'iMOProInCtrlBySet' ";
                            DataTable qt = DBHelper.SQlReturnData(sql, cmd);
                            if (qt != null && qt.Rows.Count > 0)
                            {
                              
                                if (qt.Rows[0]["cValue"].ToString() == "1")
                                {

                                    sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                    sql = string.Format(sql, head.SourceCode, body.Sequence);
                                  


                                }
                                else if (qt.Rows[0]["cValue"].ToString() == "2")
                                {
                                    sql = @"select cValue from AccInformation where cName=N'bControlKeyMaterial'";
                                    qt = DBHelper.SQlReturnData(sql, cmd);
                                    if (qt != null && qt.Rows.Count > 0)
                                    {
                                        if (qt.Rows[0]["cValue"].ToString() == "true")
                                        {
                                            sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1 and f.bInvKeyPart=1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                            sql = string.Format(sql, head.SourceCode, body.Sequence);
                                          

                                        }
                                        else
                                        {

                                            sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                            sql = string.Format(sql, head.SourceCode, body.Sequence);
                                           

                                        }
                                    }

                                }
                                else
                                {
                                    sql = @"select MoCode,SortSeq,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.MoCode,b.SortSeq,
                                    case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId
                                    end as AllocateId,sum(c.Qty) as Qty,SUM(c.IssQty) IssQty,SUM(c.IssQty)/(SUM(c.Qty)/b.Qty) lotqty
                                    from DBO.mom_order a 
                                    left join DBO.mom_orderdetail b on a.moid = b.moid
                                    left join DBO.mom_moallocate c on b.modid = c.modid
                                    left join 
                                    (select d.AllocateId,e.InvCode,d.MoallocateSubId from 
                                    DBO.mom_moallocatesub d 
                                    left join DBO.bas_part e ON d.partid = e.PartId ) aa on   c.MoallocateSubId=aa.MoallocateSubId
                                    left join DBO.Inventory_Sub f on c.InvCode=f.cInvSubCode
                                    where a.MoCode='{0}' and b.SortSeq='{1}'
                                    and c.WIPType<>1 and c.Qty<>0 and c.ByproductFlag<>1
                                    group by a.MoCode,b.SortSeq,case when aa.AllocateId IS null then c.AllocateId else aa.AllocateId end ,b.Qty 
                                    ) tt
                                    group by MoCode,SortSeq";
                                    sql = string.Format(sql, head.SourceCode, body.Sequence);
                                }
                            }

                            #endregion
                        }
                        else
                        {
                            newsql = " where a.cCode='{0}' and b.iVouchRowNo='{1}'";
                            newsql = string.Format(newsql, head.SourceCode, body.Sequence);
                            #region 齐套检验
                            sql = @" select cValue from AccInformation where cName=N'iMOProInCtrlBySet' ";
                            DataTable qt = DBHelper.SQlReturnData(sql, cmd);
                            if (qt != null && qt.Rows.Count > 0)
                            {
                                if (qt.Rows[0]["cValue"].ToString() == "1")
                                {

                                    sql = @"select cCode,iVouchRowNo,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.cCode,b.iVouchRowNo,
                                    c.MOMaterialsID  as AllocateId,sum(c.iQuantity) as Qty,SUM(c.iSendQTY) IssQty,SUM(c.iSendQTY)/(SUM(c.iQuantity)/b.iQuantity) lotqty
                                    from DBO.OM_MOMain a 
                                    left join DBO.OM_MODetails b on a.moid = b.moid
                                    left join DBO.OM_MOMaterials c on b.MODetailsID = c.MODetailsID
                             
                                    left join DBO.Inventory_Sub f on c.cInvCode=f.cInvSubCode
                                    where a.cCode='{0}' and b.iVouchRowNo='{1}'
                                    and  c.iQuantity<>0 
                                    group by a.cCode,b.iVouchRowNo,c.MOMaterialsID,b.iQuantity 
                                    ) tt
                                    group by cCode,iVouchRowNo";
                                    sql = string.Format(sql, head.SourceCode, body.Sequence);
                                  


                                }
                                else if (qt.Rows[0]["cValue"].ToString() == "2")
                                {
                                    sql = @"select cValue from AccInformation where cName=N'bControlKeyMaterial'";
                                    qt = DBHelper.SQlReturnData(sql, cmd);
                                    if (qt != null && qt.Rows.Count > 0)
                                    {
                                        if (qt.Rows[0]["cValue"].ToString() == "true")
                                        {
                                            sql = @"select cCode,iVouchRowNo,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.cCode,b.iVouchRowNo,
                                    c.MOMaterialsID  as AllocateId,sum(c.iQuantity) as Qty,SUM(c.iSendQTY) IssQty,SUM(c.iSendQTY)/(SUM(c.iQuantity)/b.iQuantity) lotqty
                                    from DBO.OM_MOMain a 
                                    left join DBO.OM_MODetails b on a.moid = b.moid
                                    left join DBO.OM_MOMaterials c on b.MODetailsID = c.MODetailsID
                             
                                    left join DBO.Inventory_Sub f on c.cInvCode=f.cInvSubCode
                                    where a.cCode='{0}' and b.iVouchRowNo='{1}'
                                    and  c.iQuantity<>0 
                                    group by a.cCode,b.iVouchRowNo,c.MOMaterialsID,b.iQuantity 
                                    ) tt
                                    group by cCode,iVouchRowNo";
                                            sql = string.Format(sql, head.SourceCode, body.Sequence);
                                            qt = DBHelper.SQlReturnData(sql, cmd);

                                      

                                        }
                                        else
                                        {

                                            sql = @"select cCode,iVouchRowNo,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.cCode,b.iVouchRowNo,
                                    c.MOMaterialsID  as AllocateId,sum(c.iQuantity) as Qty,SUM(c.iSendQTY) IssQty,SUM(c.iSendQTY)/(SUM(c.iQuantity)/b.iQuantity) lotqty
                                    from DBO.OM_MOMain a 
                                    left join DBO.OM_MODetails b on a.moid = b.moid
                                    left join DBO.OM_MOMaterials c on b.MODetailsID = c.MODetailsID
                             
                                    left join DBO.Inventory_Sub f on c.cInvCode=f.cInvSubCode
                                    where a.cCode='{0}' and b.iVouchRowNo='{1}'
                                    and  c.iQuantity<>0 
                                    group by a.cCode,b.iVouchRowNo,c.MOMaterialsID,b.iQuantity 
                                    ) tt
                                    group by cCode,iVouchRowNo";
                                            sql = string.Format(sql, head.SourceCode, body.Sequence);
                                            qt = DBHelper.SQlReturnData(sql, cmd);

                                         
                                        }
                                    }

                                }
                                else
                                {
                                    sql = @"select cCode,iVouchRowNo,MIN(lotqty) min_lotqty from 
                                    (
                                    select
                                    a.cCode,b.iVouchRowNo,
                                    c.MOMaterialsID  as AllocateId,sum(c.iQuantity) as Qty,SUM(c.iSendQTY) IssQty,SUM(c.iSendQTY)/(SUM(c.iQuantity)/b.iQuantity) lotqty
                                    from DBO.OM_MOMain a 
                                    left join DBO.OM_MODetails b on a.moid = b.moid
                                    left join DBO.OM_MOMaterials c on b.MODetailsID = c.MODetailsID
                             
                                    left join DBO.Inventory_Sub f on c.cInvCode=f.cInvSubCode
                                    where a.cCode='{0}' and b.iVouchRowNo='{1}'
                                    and  c.iQuantity<>0 
                                    group by a.cCode,b.iVouchRowNo,c.MOMaterialsID,b.iQuantity 
                                    ) tt
                                    group by cCode,iVouchRowNo";
                                    sql = string.Format(sql, head.SourceCode, body.Sequence);
                                }
                            }




                            #endregion
                        }
                    }


                    if (head.SourceType == "生产订单")
                    {
                        sql = @"select a.MoCode,b.SortSeq,C.SortSeq SubSortSeq,d.min_lotqty,b.Qty,b.QualifiedInQty,b.InvCode,c.InvCode subInvCode,c.Qty AxuQTY,c.IssQty 
                        into #info
                        from mom_order a 
                        LEFT JOIN mom_orderdetail b on a.moid = b.moid
                        LEFT JOIN mom_moallocate c on b.modid = c.modid
                        left join (" + sql + @") d on a.MoCode=d.MoCode and b.SortSeq=d.SortSeq   
                        1=1
                        select DISTINCT MoCode,SortSeq,MoCode+SortSeq GL,min_lotqty,Qty,QualifiedInQty,InvCode from #info
                        select DISTINCT MoCode,SortSeq,MoCode+SortSeq GL,SubSortSeq,subInvCode,AxuQTY,IssQty from #info
                        ";
                        sql = sql.Replace("1=1", newsql);
                    }
                    else
                    {
                        sql = @"select a.cCode MoCode,b.iVouchRowNo SortSeq,C.irowno SubSortSeq,d.min_lotqty,b.iQuantity Qty,b.iReceivedQTY QualifiedInQty,b.cInvCode InvCode,c.cInvCode subInvCode,c.iQuantity AxuQTY,c.iSendQTY IssQty 
                        into #info
                        from OM_MOMain a 
                        left join DBO.OM_MODetails b on a.moid = b.moid
                        left join DBO.OM_MOMaterials c on b.MODetailsID = c.MODetailsID
                        left join (" + sql + @") d on a.cCode=d.cCode and b.iVouchRowNo=d.iVouchRowNo
                        1=1
                        select DISTINCT MoCode,SortSeq,min_lotqty,Qty,QualifiedInQty,InvCode from #info
                        select DISTINCT MoCode,SortSeq,SubSortSeq,subInvCode,AxuQTY,IssQty from #info
                        ";
                        sql = sql.Replace("1=1", newsql);
                    }
            
                    DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
                    if (dtNew1 == null)
                        dtNew1 = ds.Tables[0];
                    else
                        dtNew1 = ds.Tables[0];
                    if (dtNew2 == null)
                        dtNew2 = ds.Tables[1];
                    else
                        dtNew2 = ds.Tables[1];

                }
            }
            catch (Exception ex)
            {
                cmd.Transaction.Rollback();
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Dispose();
            }
           

           
            string RelationName = "details";
            DataSet dz = new DataSet();
            dtNew1.TableName = "Table0";
            dtNew2.TableName = "Table1";
            dz.Tables.Add(dtNew1.Copy());
            dz.Tables.Add(dtNew2.Copy());
            DataRelation dh = new DataRelation(RelationName, dz.Tables[0].Columns["GL"], dz.Tables[1].Columns["GL"]);
            dz.Relations.Add(dh);
            mag = DBHelper.DataSetToJson(dz, RelationName);
            return mag;

        }
    }
}