using NFine.Data.Extensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NFine.Code;
using NFine.Repository;
using System.Data.Common;
using NFine.Domain._03_Entity.SRM;
using ICS.Application.Entity;
using Newtonsoft.Json;
using System.Configuration;
using System.Data.SqlClient;
using ICS.Data;
using Newtonsoft.Json.Linq;

namespace NFine.Application.WMS
{
    public class YLICSMoPickApp : RepositoryFactory<ICSVendor>
    {
        public static DataTable Invmes = new DataTable();
        //工单备料(工单子件)
        public DataTable GetGridJson(string queryJson, ref Pagination jqgridparam)
        {
            string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
            DataTable dt = new DataTable();
            var queryParam = queryJson.ToJObject();
            List<DbParameter> parameter = new List<DbParameter>();
            string sql = "";
            #region [SQL]

            sql = @"select a.ID,b.MOCode as Code,a.Sequence as ZSequence,b.Sequence as MSequence,b.Sequence + '-' + a.Sequence AS Sequence,a.EATTRIBUTE2,
a.MTIME,a.MUSERName,a.MUSER,a.WHCode,c.WarehouseName,a.InvCode,d.InvName,d.InvDesc,d.InvStd,d.InvUnit,
            							case when e.SourceID is null then '未合并' else '已合并' end as IsNew,a.Quantity
            ,f.Colspan  ,f.ProjectCode  ,f.BatchCode    ,f.Version  ,f.Brand    ,f.cFree1   ,f.cFree2   ,f.cFree3   ,f.cFree4
            ,f.cFree5   ,f.cFree6   ,f.cFree7   ,f.cFree8   ,f.cFree9   ,f.cFree10,a.IssueQuantity as IssueQuantity
                                        from ICSMOPick a
                                        left
                                        join ICSMO b on a.MODetailID = b.MODetailID and a.WorkPoint = b.WorkPoint and b.MOStatus<>'3'
										left join Sys_SRM_Items g on g.F_EnCode='Reduction'
                                        left join ICSWarehouse c on a.WHCode = c.WarehouseCode and a.WorkPoint = c.WorkPoint
                                        inner join ICSInventory d on a.InvCode = d.InvCode and a.WorkPoint = d.WorkPoint 
                                        left join ICSMOPickMerge e on a.ID = e.SourceID and a.WorkPoint = e.WorkPoint
                                        left join ICSExtension f on a.ExtensionID = f.ID and a.WorkPoint = f.WorkPoint
                                        where  a.EATTRIBUTE1 <> '1' 

										and SUBSTRING(b.InvCode, 1, CONVERT(int,g.F_Description)) NOT IN (select b.F_ItemCode from Sys_SRM_Items a left join Sys_SRM_ItemsDetail b on a.F_Id=b.F_ItemId

where a.F_EnCode='Reduction')";
            sql = string.Format(sql, WorkPoint);
            sql = string.Format(sql, DbHelper.GetErpIp(), DbHelper.GetErpName());
            #endregion

            if (!string.IsNullOrWhiteSpace(queryJson))
            {
                if (!string.IsNullOrWhiteSpace(queryParam["POCode"].ToString()))
                {
                    sql += " and b.MOCode like '%" + queryParam["POCode"].ToString() + "%' ";
                }
                if (!string.IsNullOrWhiteSpace(queryParam["InvCode"].ToString()))
                {
                    sql += " and a.InvCode like '%" + queryParam["InvCode"].ToString() + "%' ";
                }
                if (!string.IsNullOrWhiteSpace(queryParam["Mechanism"].ToString()))
                {
                    sql += " and a.EATTRIBUTE2 like '%" + queryParam["Mechanism"].ToString() + "%' ";
                }
                if (!string.IsNullOrWhiteSpace(queryParam["TimeFrom"].ToString()))
                {
                    sql += " and convert(nvarchar(20),b.CreateDateTime,23) >= '" + queryParam["TimeFrom"].ToString() + "' ";
                }
                if (!string.IsNullOrWhiteSpace(queryParam["TimeArrive"].ToString()))
                {
                    sql += " and convert(nvarchar(20),b.CreateDateTime,23) <= '" + queryParam["TimeArrive"].ToString() + "' ";
                }
            }
            return Repository().FindTablePageBySql(sql.ToString(), parameter.ToArray(), ref jqgridparam);
        }









        public DataTable GetICSMOPickMergeTemp(string ID, string Type)
        {

            string MUSER = NFine.Code.OperatorProvider.Provider.GetCurrent().UserCode;
            string MUSERNAME = NFine.Code.OperatorProvider.Provider.GetCurrent().UserName;
            string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
            ID = string.IsNullOrWhiteSpace(ID) ? "''" : ID.TrimEnd(',');

            string sqls = "";
            string wheresql = "";
            #region 各单据sql
            if (Type == "1")
            {
                #region 工单备料sql
             

                sqls = @" SELECT
	                        c.MOCode as Code,
c.Sequence+'-'+a.Sequence as Sequence,
	                        a.InvCode,
	                        b.InvName,
	                        b.InvStd,
	                        SUM(ISNULL(a.Quantity, 0)) AS iQuantity,
	                        a.WhCode,
                            b.InvUnit,
							a.ExtensionID,
a.EATTRIBUTE2,
							f.ProjectCode	,f.BatchCode	,f.Version	,f.Brand	,f.cFree1	,f.cFree2	,f.cFree3	,f.cFree4	
,f.cFree5	,f.cFree6	,f.cFree7	,f.cFree8	,f.cFree9	,f.cFree10
                        FROM
	                        ICSMOPick a
							inner join ICSMO c on a.MODetailID=c.MODetailID and a.WorkPoint=c.WorkPoint and c.MOStatus<>'3'
                            LEFT JOIN ICSINVENTORY b ON a.InvCode = b.InvCode AND a.WorkPoint=b.WorkPoint
                            LEFT JOIN  ICSExtension f on a.ExtensionID=f.ID and a.WorkPoint=f.WorkPoint
                            WHERE  c.MOCode+c.Sequence+'-'+a.Sequence  in ({0}) AND a.WorkPoint = '{1}' AND ISNULL(a.Quantity, 0)>ISNULL(a.IssueQuantity, 0) and a.EATTRIBUTE1<>'1' 
GROUP BY c.MOCode,a.InvCode,b.InvName,b.InvStd,b.InvUnit,a.WhCode,a.ExtensionID,a.EATTRIBUTE2,c.Sequence+'-'+a.Sequence,f.ProjectCode	,f.BatchCode	,f.Version	,f.Brand	,f.cFree1	,f.cFree2	,f.cFree3	,f.cFree4	
,f.cFree5   ,f.cFree6   ,f.cFree7   ,f.cFree8   ,f.cFree9   ,f.cFree10";

                #endregion
            }



            #endregion

            sqls = string.Format(sqls, ID, WorkPoint);

            string sql = $@"SELECT row_number() over ( order by c.EATTRIBUTE2,c.InvCode,d.LocationCode) AS rowNo,
	                        c.Code,
c.Sequence,
	                        c.InvCode,
	                        c.InvName,
	                        c.InvStd,
                            c.InvUnit,
	                        c.iQuantity AS iQuantity,
	                        c.WHCode AS WarehouseCode, 
	                        d.LotNO,
                            ISNULL(d.Quantity, 0) AS QTY,
                            ISNULL(d.Quantity, 0) AS QTYLeft,
                            CONVERT(decimal(18,6),0) AS SendQTY,
                            d.LocationCode AS LocationCode,
	                        CONVERT(varchar(100),d.MTIME, 23) MTIME,
	                        f.QTYTotal QTYTotal,c.ExtensionID,
                            c.EATTRIBUTE2,
	getdate() as NowMTIME

                        FROM
                        ({sqls}) c
                        left join (select d.WarehouseCode,d.Quantity-d.LockQuantity as Quantity,d.INVCode, m.LotNo, d.MTIME,d.LocationCode,m.ExtensionID ,
	f.ProjectCode	,f.BatchCode	,f.Version	,f.Brand	,f.cFree1	,f.cFree2	,f.cFree3	,f.cFree4	
,f.cFree5	,f.cFree6	,f.cFree7	,f.cFree8	,f.cFree9	,f.cFree10
                                     from ICSWareHouseLotInfo d ,ICSInventoryLot m 
	LEFT JOIN  ICSExtension f on m.ExtensionID=f.ID and m.WorkPoint=f.WorkPoint
					                where d.LotNo=m.LotNo and d.WorkPoint=m.WorkPoint
								      and d.WorkPoint='{WorkPoint}' AND d.Quantity-d.LockQuantity>0 AND d.Quantity>0
                                   
                             ) d 
                               on c.InvCode=d.INVCode 
	                    AND (LEN(ISNULL(c.WHCode,''))<=0 OR (LEN(ISNULL(c.WHCode,''))>0 AND c.WHCode=d.WarehouseCode))
						AND (LEN(ISNULL(c.ProjectCode,''))<=0 OR (LEN(ISNULL(c.ProjectCode,''))>0 AND c.ProjectCode=d.ProjectCode))
						AND (LEN(ISNULL(c.BatchCode,''))<=0 OR (LEN(ISNULL(c.BatchCode,''))>0 AND c.BatchCode=d.BatchCode))
						AND (LEN(ISNULL(c.Version,''))<=0 OR (LEN(ISNULL(c.Version,''))>0 AND c.Version=d.Version))
						AND (LEN(ISNULL(c.Brand,''))<=0 OR (LEN(ISNULL(c.Brand,''))>0 AND c.Brand=d.Brand))
						AND (LEN(ISNULL(c.cFree1,''))<=0 OR (LEN(ISNULL(c.cFree1,''))>0 AND c.cFree1=d.cFree1))
						AND (LEN(ISNULL(c.cFree2,''))<=0 OR (LEN(ISNULL(c.cFree2,''))>0 AND c.cFree2=d.cFree2))
						AND (LEN(ISNULL(c.cFree3,''))<=0 OR (LEN(ISNULL(c.cFree3,''))>0 AND c.cFree3=d.cFree3))
						AND (LEN(ISNULL(c.cFree4,''))<=0 OR (LEN(ISNULL(c.cFree4,''))>0 AND c.cFree4=d.cFree4))
						AND (LEN(ISNULL(c.cFree5,''))<=0 OR (LEN(ISNULL(c.cFree5,''))>0 AND c.cFree5=d.cFree5))
						AND (LEN(ISNULL(c.cFree6,''))<=0 OR (LEN(ISNULL(c.cFree6,''))>0 AND c.cFree6=d.cFree6))
						AND (LEN(ISNULL(c.cFree7,''))<=0 OR (LEN(ISNULL(c.cFree7,''))>0 AND c.cFree7=d.cFree7))
						AND (LEN(ISNULL(c.cFree8,''))<=0 OR (LEN(ISNULL(c.cFree8,''))>0 AND c.cFree8=d.cFree8))
						AND (LEN(ISNULL(c.cFree9,''))<=0 OR (LEN(ISNULL(c.cFree9,''))>0 AND c.cFree9=d.cFree9))
						AND (LEN(ISNULL(c.cFree10,''))<=0 OR (LEN(ISNULL(c.cFree10,''))>0 AND c.cFree10=d.cFree10))
                         LEFT JOIN (SELECT INVCode,WarehouseCode,SUM(Quantity-LockQuantity) AS QTYTotal FROM ICSWareHouseLotInfo  WHERE WorkPoint='{WorkPoint}' GROUP BY INVCode,WarehouseCode) f ON c.InvCode=f.INVCode AND c.WhCode=f.WarehouseCode
                                   order by cast( row_number()  over ( order by c.EATTRIBUTE2,c.InvCode,d.LocationCode) as int), c.EATTRIBUTE2,c.InvCode,d.LocationCode ";
            // sql = string.Format(sql, sqls)1;
            var dataset = Repository().FindDataSetBySql(sql);
            if (dataset.Tables[0].Rows.Count == 0)
                return null;
            DataTable table = dataset.Tables[0];
            decimal qtyCount = 0;
            bool remove = false;
            List<int> removeList = new List<int>();
            for (int i = 0; i < table.Rows.Count; i++)
            {
                if (i != 0
                 && (!table.Rows[i]["InvCode"].ToString().Equals(table.Rows[i - 1]["InvCode"].ToString())
                  || !table.Rows[i]["Sequence"].ToString().Equals(table.Rows[i - 1]["Sequence"].ToString())
                  || !table.Rows[i]["Code"].ToString().Equals(table.Rows[i - 1]["Code"].ToString())
                  || !table.Rows[i]["ExtensionID"].ToString().Equals(table.Rows[i - 1]["ExtensionID"].ToString()))
                 )
                {
                    qtyCount = 0;
                    remove = false;
                }
                if (table.Rows[i]["QTYLeft"].ToString().ToDecimal() == 0 && table.Rows[i]["LotNO"].ToString() != "")
                {
                    table.Rows[i]["LotNO"] = "";
                    string a = "0.000000";
                    table.Rows[i]["QTY"] = Convert.ToDecimal(a);
                    //removeList.Add(i);
                    continue;
                }
                if (remove && table.Rows[i]["LotNO"].ToString() != "")
                {
                    removeList.Add(i);
                }

                else
                {
                    var lotQty = table.Rows[i]["QTYLeft"].ToString().ToDecimal();
                    var orderQty = table.Rows[i]["iQuantity"].ToString().ToDecimal();
                    qtyCount += lotQty;
                    foreach (DataRow dr in table.Rows)
                    {
                        if (dr["LotNO"].ToString() == table.Rows[i]["LotNO"].ToString())
                        {
                            if (qtyCount > orderQty)
                            {
                                dr["QTYLeft"] = Convert.ToDecimal(qtyCount) - Convert.ToDecimal(orderQty);
                            }
                            else
                            {
                                dr["QTYLeft"] = 0;
                            }
                        }
                    }
                    if (qtyCount >= orderQty)
                    {
                        table.Rows[i]["SendQTY"] = Convert.ToDecimal(lotQty) - (Convert.ToDecimal(qtyCount) - Convert.ToDecimal(orderQty));
                        remove = true;
                    }
                    else
                    {
                        table.Rows[i]["SendQTY"] = lotQty;
                    }
                }
            }
            if (removeList.Count > 0)
            {
                removeList.Reverse();
                foreach (var item in removeList)
                {
                    table.Rows.RemoveAt(item);
                }
            }
            try
            {
                DataRow [] dss= table.Select("LotNO=''");
                foreach (var item in dss)
                {
                    DataRow[] dsss = table.Select("Code='"+ item["Code"].ToString()+ "' and Sequence='"+ item["Sequence"].ToString() + "' and LotNO <> '' ");
                    if (dsss!=null && dsss.Length>0)
                    {
                        table.Rows.Remove(item);
                    }
                }
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    table.Rows[i]["rowNo"] = i+1;
                }



                var result = ConvertCellToString(table);
                if (Invmes.Rows.Count > 0)
                {
                    result.Merge(Invmes, false);
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public DataTable ConvertCellToString(DataTable data)
        {
            DataTable dtCloned = data.Clone();
            foreach (DataColumn col in dtCloned.Columns)
            {
                col.DataType = typeof(string);
            }
            foreach (DataRow row in data.Rows)
            {
                DataRow newrow = dtCloned.NewRow();
                foreach (DataColumn column in dtCloned.Columns)
                {
                    newrow[column.ColumnName] = row[column.ColumnName].ToString();

                }
                dtCloned.Rows.Add(newrow);
            }
            return dtCloned;
        }







        public string CheckQty(string objArr)
        {
            objArr = objArr.TrimEnd(',');
            string sql = @"select * from ICSMOPickMerge a 
								left join ICSMOPick b on a.SourceID=b.ID and a.WorkPoint=b.WorkPoint
								left join ICSMO c on b.MODetailID=c.MODetailID and b.WorkPoint=c.WorkPoint and c.MOStatus<>'3'
								 where MOCode in ({0})";
            sql = string.Format(sql, objArr);
            DataTable dt = SqlHelper.GetDataTableBySql(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                return "1";
            }


            return "0";

        }









        public object SeachPickingListType(string Type)
        {
            string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;

            string sql = @"	select b.F_EnabledMark as flag from Sys_SRM_Items a left join Sys_SRM_ItemsDetail b on a.F_Id=b.F_ItemId 
where a.F_EnCode='PL00001' and b.F_ItemCode='{0}'  order by cast(b.F_SortCode as int) asc";
            sql = string.Format(sql, Type);
            object flag = SqlHelper.ExecuteScalar(sql);

            return flag;




        }









    }
}