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;
using System.Net;
using System.IO;
using NFine.Domain._03_Entity.WMS;

namespace NFine.Application.WMS
{
   public class DeciliterApp : RepositoryFactory<ICSVendor>
    {
        /// <summary>
        /// 点击委外退料生成条码
        /// </summary>
        public string GetNewLotNo(string LotNO)
        {
            DataTable dt = new DataTable();

            List<DbParameter> parameter = new List<DbParameter>();
            //string sql = @"select max(LotNo) as NewLotNo from ICSInventoryLot where EATTRIBUTE1='{0}' ";
            string sql = $@"SELECT  TOP 1 
                            LotNO as NewLotNo FROM ICSInventoryLot WHERE EATTRIBUTE1='{LotNO}'  
                            ORDER BY CAST(SUBSTRING(LotNO, (LEN(LotNO)-CHARINDEX('-',REVERSE(LotNO))+1)+1,CHARINDEX('-',REVERSE(LotNO))-1) AS INT) DESC"; 
            dt=  Repository().FindTableBySql(sql.ToString());
            if (dt==null||dt.Rows.Count==0|| dt.Rows[0]["NewLotNo"].ToString()=="")
            {
                return LotNO+"-1";
            }
            else
            {
                string newLotNO = dt.Rows[0]["NewLotNo"].ToString();
                int COUNT = Convert.ToInt32(newLotNO.Substring(newLotNO.LastIndexOf('-') + 1)) + 1;
                return LotNO + "-"+ COUNT.ToString();
            }
        }

        public string Split(string Parameter)
        {
            string msg = "";
            try
            {
                string user = NFine.Code.OperatorProvider.Provider.GetCurrent().UserCode;
                string userName = NFine.Code.OperatorProvider.Provider.GetCurrent().UserName;
                var models = Parameter.ToObject<List<LotNoCombineHead>>().FirstOrDefault();
                //StringBuilder sqlString = new StringBuilder();

                //if (models.LotNo == null || models.detail == null)
                //{
                //    msg = "拆分失败,拆分数据不能为空";
                //    return msg;
                //}
                //foreach (var mode in models.detail)
                //{
                //    sqlString.Append($@" INSERT INTO ICSInventoryLot (ID,LotNo,InvCode,ProductDate,ExpirationDate,Quantity,Amount,ExtensionID,Type,PrintTimes,LastPrintUser,
                //                                                 LastPrintTime,MUSER,MUSERName,MTIME,WorkPoint,EATTRIBUTE1 )
                //                                             SELECT NEWID(),'{mode.CurrentLotNo}',InvCode,ProductDate,ExpirationDate,CONVERT(NUMERIC(10,2),{mode.CurrentQuantity}),Amount,ExtensionID,Type,PrintTimes,
                //                                                 LastPrintUser,LastPrintTime,'{user}','{userName}','{models.MTIME}',WorkPoint,'{models.LotNo}' 
                //                                          FROM ICSInventoryLot
                //                                          WHERE LotNo='{models.LotNo}'    ");
                //    sqlString.Append($@" INSERT INTO ICSWareHouseLotInfo
                //                       SELECT
                //                           NEWID(), '{mode.CurrentLotNo}', WarehouseCode, LocationCode, InvCode, CONVERT(NUMERIC(10,2),{mode.CurrentQuantity}), InDate, LockQuantity, '{user}','{userName}', '{models.MTIME}', WorkPoint, EATTRIBUTE1 
                //                        FROM ICSWareHouseLotInfo
                //                        WHERE LotNo='{models.LotNo}'  ");
                //    sqlString.Append($@" UPDATE [dbo].[ICSWareHouseLotInfo] SET [Quantity] = Quantity-{mode.CurrentQuantity.ToInt()} Where [LotNo]='{models.LotNo}' ");

                //    sqlString.Append($@" INSERT INTO ICSWareHouseLotInfoLog SELECT NEWID(), Identification, TransCode, TransSequence, '{mode.CurrentLotNo}', InvCode, FromWarehouseCode, FromLocationCode, ToWarehouseCode, ToLocationCode, CONVERT(NUMERIC(10,2),{mode.CurrentQuantity}), Memo, Lock, '4', BusinessCode, ERPUpload, ERPID, ERPDetailID, ERPCode, ERPSequence, LogID, MergeID, '{user}','{userName}', '{models.MTIME}', WorkPoint, EATTRIBUTE1, EATTRIBUTE2, EATTRIBUTE3 
                //                       FROM ICSWareHouseLotInfoLog WHERE LotNo='{models.LotNo}'  ");

                //    sqlString.Append($@" INSERT INTO ICSInventoryLotDetail SELECT '{mode.CurrentLotNo}', TransCode, TransSequence,'{user}','{userName}', '{models.MTIME}', WorkPoint, EATTRIBUTE1 FROM ICSInventoryLotDetail WHERE LotNo='{models.LotNo}';");

                //    sqlString.Append($@" UPDATE [dbo].[ICSWareHouseLotInfoLog] SET [Quantity] = Quantity-{mode.CurrentQuantity.ToInt()} Where [LotNo]='{models.LotNo}' ");

                //}
                //var sql = sqlString.ToString();
                //var count = SqlHelper.CmdExecuteNonQueryLi(sqlString.ToString());
                //if (count <= 0)
                //{
                //    msg = "操作失败";
                //}
                string APIURL = ConfigurationManager.ConnectionStrings["APIURL"].ConnectionString + "LOTSplit/Create";
                string result = HttpPost(APIURL, Parameter);
                JObject Obj = (JObject)JsonConvert.DeserializeObject(result);//或者JObject jo = JObject.Parse(jsonText);
                string MessAge = Obj["Message"].ToString();
                string Success = Obj["Success"].ToString();
                if (Success.ToUpper() == "FALSE")
                {
                    msg = MessAge;
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return msg;
        }


        //接口api解析
        public static string HttpPost(string url, string body)
        {
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json; charset=utf-8";

                byte[] buffer = encoding.GetBytes(body);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 根据ID获取条码
        /// </summary>
        /// <returns></returns>
        public DataTable GetLotNoByID(string ID)
        {
            string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
            string sql = @"select '' as ID,'' as LotNo union all
SELECT ID,LotNo FROM ICSWareHouseLotInfo WITH (NOLOCK) WHERE ID in ({0}) ";
            sql = string.Format(sql, ID.TrimEnd(','));
            //string role = NFine.Code.OperatorProvider.Provider.GetCurrent().RoleEnCode;
            //if (role != "admin")
            //{
            //    sql += " and b.WorkPoint='" + WorkPoint + "'";
            //}
            DataTable dt = SqlHelper.GetDataTableBySql(sql);
            return dt;
        }


        //合批
        //public string Combine(string LotNo, string ID)
        //{
        //    string msg = "";
        //    try
        //    {
        //        string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
        //        string MUSER = NFine.Code.OperatorProvider.Provider.GetCurrent().UserCode;
        //        string sql = @"	select distinct LotNo,Quantity from ICSWareHouseLotInfo  WHERE ID IN (" + ID.TrimEnd(',') + ")";
        //        DataTable dt = Repository().FindTableBySql(sql.ToString());
        //        List<LotNoCombineHead> asn = new List<LotNoCombineHead>();
        //        LotNoCombineHead ass = new LotNoCombineHead();
        //        for (int i = 0; i < dt.Rows.Count; i++)
        //        {
        //            if (LotNo == dt.Rows[i]["LotNo"].ToString())
        //            {
        //                continue;
        //            }
        //            LotNoCombineBody DetailList = new LotNoCombineBody();
        //            DetailList.CurrentLotNo = dt.Rows[i]["LotNo"].ToString();
        //            DetailList.CurrentQuantity = dt.Rows[i]["Quantity"].ToString();
        //            ass.detail.Add(DetailList);
        //        }
        //        ass.LotNo = LotNo;
        //        ass.User = MUSER;
        //        ass.WorkPoint = WorkPoint;
        //        ass.MTIME = System.DateTime.Now.ToString("s");
        //        asn.Add(ass);
        //        StringBuilder sqlString = new StringBuilder();
        //        decimal quantity = 0;
        //        foreach (var models in asn)
        //        {
        //            if (models.LotNo == null || models.detail == null)
        //            {
        //                throw new Exception("合并失败");
        //            }
        //            foreach (var mode in models.detail)
        //            {

        //                sqlString.Append($@"IF NOT EXISTS(SELECT a.LotNo FROM ICSWareHouseLotInfo a WHERE a.WarehouseCode=(SELECT top 1 WarehouseCode FROM ICSWareHouseLotInfo WHERE LotNo='{mode.CurrentLotNo}') AND a.InvCode=(SELECT top 1 InvCode FROM ICSWareHouseLotInfo WHERE LotNo='{mode.CurrentLotNo}') AND a.LotNo='{models.LotNo}')
        //                        BEGIN
        //                         RAISERROR('不同物料、仓库的物料不能合批,',16,1);
        //                        END
        //                        IF NOT EXISTS(SELECT a.LotNo FROM ICSInventoryLot a WHERE a.ExtensionID=(SELECT top 1 ExtensionID FROM ICSInventoryLot WHERE LotNo='{mode.CurrentLotNo}')  AND a.LotNo='{models.LotNo}')
        //                        BEGIN
        //                         RAISERROR('不同批次的物料不能合批',16,1);
        //                        END;	");
        //                sqlString.Append($@" DELETE FROM ICSInventoryLot WHERE LotNo='{mode.CurrentLotNo}';    ");
        //                sqlString.Append($@" DELETE FROM ICSWareHouseLotInfo WHERE LotNo='{mode.CurrentLotNo}';  ");

        //                sqlString.Append($@" DELETE FROM ICSWareHouseLotInfoLog WHERE LotNo='{mode.CurrentLotNo}';  ");

        //                quantity += mode.CurrentQuantity.ToDecimal();
        //            }

        //         sqlString.Append($@" UPDATE [dbo].[ICSWareHouseLotInfo] SET [Quantity] = Quantity+{quantity} Where [LotNo]='{models.LotNo}'; ");
        //         sqlString.Append($@" UPDATE [dbo].[ICSWareHouseLotInfoLog] SET [Quantity] = Quantity+{quantity} Where [LotNo]='{models.LotNo}'; ");
        //        }
        //        var count = SqlHelper.CmdExecuteNonQueryLi(sqlString.ToString());
        //        if (count <= 0)
        //            throw new Exception("操作失败");
        //    }
        //    catch (Exception ex)
        //    {
        //        msg = ex.Message;
        //    }
        //    return msg;
        //}

        //合批
        public string Combine(string LotNo, string ID)
        {
            string msg = "";
            string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
            string MUSER = NFine.Code.OperatorProvider.Provider.GetCurrent().UserCode;
            string sql = @"	select distinct LotNo,Quantity from ICSWareHouseLotInfo  WHERE ID IN (" + ID.TrimEnd(',') + ")";
            DataTable dt = Repository().FindTableBySql(sql.ToString());
            List<LotNoCombineHead> asn = new List<LotNoCombineHead>();
            LotNoCombineHead ass = new LotNoCombineHead();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (LotNo == dt.Rows[i]["LotNo"].ToString())
                {
                    continue;
                }
                LotNoCombineBody DetailList = new LotNoCombineBody();
                DetailList.CurrentLotNo = dt.Rows[i]["LotNo"].ToString();
                DetailList.CurrentQuantity = dt.Rows[i]["Quantity"].ToString();
                ass.detail.Add(DetailList);
            }
            ass.LotNo = LotNo;
            ass.User = MUSER;
            ass.WorkPoint = WorkPoint;
            ass.MTIME = System.DateTime.Now.ToString("s");
            asn.Add(ass);

            string input = JsonConvert.SerializeObject(asn);
            string APIURL = ConfigurationManager.ConnectionStrings["APIURL"].ConnectionString + "LOTMerge/Create";
            string result = HttpPost(APIURL, input);
            JObject Obj = (JObject)JsonConvert.DeserializeObject(result);//或者JObject jo = JObject.Parse(jsonText);
            string MessAge = Obj["Message"].ToString();
            string Success = Obj["Success"].ToString();
            if (Success.ToUpper() == "FALSE")
            {
                msg = MessAge;
            }
            return msg;
        }
        //验证条码是否存在占料
        public decimal CheckLotOccupy(string LotNO)
        {
            string WorkPoint = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
            string sql = @"	select ISNULL(LockQuantity,0) AS LockQuantity from ICSWareHouseLotInfo
                            where LotNo='{0}' AND WorkPoint='{1}'";
            sql = string.Format(sql, LotNO, WorkPoint);
            DataTable dt = SqlHelper.GetDataTableBySql(sql);
            decimal LotQTY = Convert.ToDecimal(dt.Rows[0]["LockQuantity"]);
            return LotQTY;
        }
    }
}