using NFine.Code;
using NFine.Data.Extensions;
using NFine.Domain.Entity.ProductManage;
using NFine.Domain.IRepository.ProductManage;
using NFine.Repository.ProductManage;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace NFine.Application.ProductManage
{
    public class PreSellApp
    {
        private IICSProductRepository servicePro = new MaintainRepository();
        private IICSProductPreSellRepository service = new PreSellRepository();
        private IICSProductPreSellDetailRepository serviceD = new PreSellDetailRepository();

        public List<ICSProductPreSellEntity> GetList(string keyword = "")
        {
            string username = NFine.Code.OperatorProvider.Provider.GetCurrent().UserName;
            string userID = NFine.Code.OperatorProvider.Provider.GetCurrent().UserId;
            string location = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
            var expression = ExtLinq.True<ICSProductPreSellEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.PreSellNo.Contains(keyword));
            }
            if (username != "超级管理员")
            {
                expression = expression.And(t => t.F_CreatorUserId == userID);

                expression = expression.And(t => t.F_Location == location);
            }

            return service.IQueryable(expression).OrderBy(t => t.PreSellNo).ToList();
        }

        public List<ICSProductPreSellEntity> GetListZS(Pagination pagination, string keyword, string keyword2)
        {
            string username = NFine.Code.OperatorProvider.Provider.GetCurrent().UserName;
            string userID = NFine.Code.OperatorProvider.Provider.GetCurrent().UserId;
            string location = NFine.Code.OperatorProvider.Provider.GetCurrent().Location;
            var expression = ExtLinq.True<ICSProductPreSellEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.PreSellNo.Contains(keyword));
            }
            if (!string.IsNullOrEmpty(keyword2))
            {
                expression = expression.And(t => t.CustomerName.Contains(keyword2));
            }
            if (username != "超级管理员")
            {
                expression = expression.And(t => t.F_CreatorUserId == userID);

                expression = expression.And(t => t.F_Location == location);
            }
            return service.FindList(expression, pagination);
        }

        public ICSProductPreSellEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }

        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }

        public void SubmitForm(List<ICSProductEntity> productList, ICSProductPreSellEntity ppsEntity, List<ICSProductPreSellDetailEntity> ppsdList)
        {
            if (ppsdList.Count <= 0)
                throw new Exception("Please select the product you want to buy");

            if (productList.Count >= 2)
            {
                ICSProductEntity model = productList[0];
                for (int i = 0; i < productList.Count; i++)
                {
                    if (i != 0)
                    {
                        if (model.Other != productList[i].Other)
                        {
                            throw new Exception("Orders can only choose one type of diamond(Rough/Polished).");
                        }
                    }
                }
            }

            string sql = @"SELECT TOP 1 c.ProductSN,c.Other FROM ICSProductPreSellDetail a
                        LEFT JOIN ICSProductPreSell b ON a.PreSell_Id = b.F_Id
                        LEFT JOIN ICSProduct c ON c.F_Id = a.Product_Id
                        WHERE b.F_Id = '{0}'
                        ORDER BY a.PreSellTime";
            sql = string.Format(sql, ppsdList[0].PreSell_Id);
            DataTable d = SqlHelper.GetDataTableBySql(sql);
            if (d != null && d.Rows.Count > 0)
            {
                string other = d.Rows[0]["Other"].ToString();
                if (!string.IsNullOrEmpty(other))
                {
                    foreach (ICSProductEntity item in productList)
                    {
                        if (other != item.Other)
                        {
                            throw new Exception("Orders can only choose one type of diamond(Rough/Polished).");
                        }
                    }
                }
            }

            if (ppsEntity != null)
            {
                if (ppsEntity.PreSellNo.Length <= 0)
                {
                    throw new Exception("New order number can not be empty");
                }
                else
                {
                    string strSql = @"SELECT PreSellNo FROM ICSProductPreSell WHERE PreSellNo = '{0}'";
                    strSql = string.Format(strSql, ppsEntity.PreSellNo);
                    DataTable dt = SqlHelper.GetDataTableBySql(strSql);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        //if (!string.IsNullOrEmpty(dt.Rows[0]["PreSellNo"].ToString()))
                        //{
                        throw new Exception("Order number already exists");
                        //}
                        //else
                        //{
                        //    service.Insert(ppsEntity);
                        //}
                    }
                    else
                    {
                        service.Insert(ppsEntity);
                    }
                }
            }
            foreach (ICSProductPreSellDetailEntity model in ppsdList)
            {
                string strSql = @"SELECT * FROM ICSProductPreSellDetail 
                                  WHERE PreSell_Id = '{0}' AND Product_Id = '{1}'";
                strSql = string.Format(strSql, model.PreSell_Id, model.Product_Id);
                DataTable dt = SqlHelper.GetDataTableBySql(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    throw new Exception("Data already exists");
                }
                else
                {
                    model.Create();
                    serviceD.Insert(model);
                }
            }
            foreach (ICSProductEntity model in productList)
            {
                model.Modify(model.F_Id);
                servicePro.Update(model);
            }
        }

        public void UpdateForm(ICSProductPreSellEntity ppsEntity)
        {
            service.Update(ppsEntity);
        }

        public void UpdateForm(List<ICSProductPreSellEntity> ppsList, List<ICSProductEntity> productList, string preSellId)
        {
            //if (ppsList.Count <= 0)
            //{
            //    throw new Exception("No order, please choose the order first.");
            //}
            //if (productList.Count <= 0)
            //{
            //    throw new Exception("There is no product information in the order and it cannot be confirmed.");
            //}
            //foreach (ICSProductPreSellEntity entity in ppsList)
            //{
            //    service.Update(entity);
            //}
            //foreach (ICSProductEntity model in productList)
            //{
            //    model.Modify(model.F_Id);
            //    servicePro.Update(model);
            //}
            //string sql = @"DELETE FROM ICSProductPreSellDetail WHERE F_Id IN
            //               (
	           //                SELECT b.F_Id FROM ICSProductPreSell a
	           //                LEFT JOIN ICSProductPreSellDetail b ON a.F_Id = b.PreSell_Id
	           //                WHERE b.PreSell_Id <> '{0}' AND b.Product_SN IN
	           //                (
		          //                 SELECT b.Product_SN FROM ICSProductPreSell a
		          //                 LEFT JOIN ICSProductPreSellDetail b ON a.F_Id = b.PreSell_Id
		          //                 WHERE b.PreSell_Id = '{0}'
	           //                )
            //               )";
            //sql = string.Format(sql, preSellId);
            //DbHelper.ExecuteSqlCommand(sql);
        }

        public void UpdateFormC(List<ICSProductPreSellEntity> ppsList, List<ICSProductEntity> productList)
        {
            if (ppsList.Count <= 0)
            {
                throw new Exception("No order, please choose the order first.");
            }
            if (productList.Count <= 0)
            {
                throw new Exception("There is no product information in the order and it cannot be confirmed.");
            }
            foreach (ICSProductPreSellEntity entity in ppsList)
            {
                service.Update(entity);
            }
            foreach (ICSProductEntity model in productList)
            {
                model.Modify(model.F_Id);
                servicePro.Update(model);
            }
        }

        public string GetExpiredDays(string typeName)
        {
            string ExpiredDays = "0";
            string sql = @"SELECT a.F_ItemCode FROM Sys_ItemsDetail a 
                            LEFT JOIN Sys_Items b ON a.F_ItemId = b.F_Id
                            WHERE b.F_EnCode = '{0}'";
            sql = string.Format(sql, typeName);

            DataTable dt = SqlHelper.GetDataTableBySql(sql);
            if (dt != null && dt.Rows.Count > 0)
                ExpiredDays = dt.Rows[0]["F_ItemCode"].ToString();
            return ExpiredDays;
        }

        public string GetPreSellNo(string presellDetialID)
        {
            string PreSellNo = string.Empty;
            string sql = @"SELECT a.PreSellNo
                            FROM ICSProductPreSell a
                            LEFT JOIN ICSProductPreSellDetail b ON a.F_Id = b.PreSell_Id
                            WHERE b.F_Id='{0}'";
            sql = string.Format(sql, presellDetialID);

            DataTable dt = SqlHelper.GetDataTableBySql(sql);
            if (dt != null && dt.Rows.Count > 0)
                PreSellNo = dt.Rows[0]["PreSellNo"].ToString();
            return PreSellNo;
            //return service.IQueryable(expression).OrderBy(t => t.PreSellTime).ToList();
        }

        public List<string> GetProductID(string preSellId)
        {
            List<string> PIDs = null;
            string sql = @"SELECT c.F_Id FROM ICSProductPreSell a
                           LEFT JOIN ICSProductPreSellDetail b ON a.F_Id = b.PreSell_Id
                           LEFT JOIN ICSProduct c ON b.Product_SN = c.ProductSN
                           WHERE a.F_Id = '{0}'";
            sql = string.Format(sql, preSellId);
            DataTable dt = SqlHelper.GetDataTableBySql(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                PIDs = new List<string>();
                foreach (DataRow row in dt.Rows)
                {
                    string pid = row["F_Id"].ToString();
                    PIDs.Add(pid);
                }
            }
            return PIDs;
        }

        public string GetOrderNo(string orderNoHead)
        {
            string sql = @"SELECT * FROM ICSProductPreSell WHERE PreSellNo LIKE '{0}%'";
            sql = string.Format(sql, orderNoHead);
            DataTable dt = SqlHelper.GetDataTableBySql(sql);
            if (dt != null && dt.Rows.Count > 0)
                return dt.Rows[0]["PreSellNo"].ToString();
            else
                return "";
        }

        public DataTable GetSOMain(string keyword)
        {
            if (NFine.Code.OperatorProvider.Provider.GetCurrent().UserName == "超级管理员"
                || (NFine.Code.OperatorProvider.Provider.GetCurrent().UserName != "超级管理员" &&
                NFine.Code.OperatorProvider.Provider.GetCurrent().Location.ToUpper() == "SH")
                )
            {
                DataTable dt = new DataTable();
                string sql = @"SELECT cSOCode,dDate,cBusType,cSTName,cCusName,cDepName,iTaxRate,cexch_name,iExchRate,cMemo 
                           FROM WMS_ZHENGSHI.dbo.SO_SOMain WHERE 1=1";
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql = sql + " AND cSOCode = '{0}'";
                    sql = string.Format(sql, keyword);
                }
                dt = SqlHelper.GetDataTableBySql(sql);
                return dt;
            }
            else
                return null;
        }
    }
}