using MESClassLibrary.BLL.Log;
using MESClassLibrary.EFModel;
using MESClassLibrary.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using MESClassLibrary.DAL.BasicInfo;

namespace MESClassLibrary.BLL.BasicInfo
{
    public class InjectionPlanBLL
    {
        BBMPTEntities ef = new BBMPTEntities();
        BasicBLL<tb_InjectionPlan> db = new BasicBLL<tb_InjectionPlan>();
        InjectionPlanDAL dal = new InjectionPlanDAL();

        /// <summary>
        /// 新增信息
        /// </summary>
        /// <param name="md"></param>
        /// <returns></returns>
        public bool AddInfo(tb_InjectionPlan md)
        {
            try
            {
                return db.AddInfo(md);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return false;
            }

        }
        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="md"></param>
        /// <returns></returns>
        public bool UpdateInfo(tb_InjectionPlan md)
        {
            try
            {

                //初始化要更新的字段
                string[] proNames = new string[8];
                proNames[0] = "StationID";
                proNames[1] = "BeginTime";
                proNames[2] = "StockNo";
                proNames[3] = "PlanCount";
                proNames[4] = "EndTime";
                proNames[5] = "PlanDate";
                proNames[6] = "RealCycle";
                proNames[7] = "PartNo";



                //必填字段初始化,如果不需要更新必填字段则设置为空即可,时间类型无需初始化
                //如果没有初始化必填字段,更新会报错


                return db.UpdateInfo(md, proNames);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return false;
            }

        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="md"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public bool DeleteInfo(tb_InjectionPlan md)
        {
            try
            {
                return db.DelInfo(md);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return false;
            }

        }

        /// <summary>
        /// 查询全部信息分页
        /// </summary>
        /// <returns></returns>
        public string SearchInfoAll(string page, string pagesize, string stationID, string stockNo)
        {
            try
            {

                string jsonStr = "[]";
                int total = 0;//总行数
                List<tb_InjectionPlan> list = db.SearchAllInfo().Where(p => p.IsFinish != 1).ToList();
                if (!String.IsNullOrEmpty(stationID))
                {
                    list = list.Where(p => p.StationID.Equals(stationID)).ToList();
                }
                if (!String.IsNullOrEmpty(stockNo))
                {
                    list = list.Where(p => p.StockNo.Contains(stockNo)).ToList();
                }

                list = list.OrderBy(p => p.BeginTime).ToList();

                List<InjectionPlanModel> modelList = new List<InjectionPlanModel>();
                if (list.Count > 0)
                {
                    total = list.Count;

                    int Skipcount = (Convert.ToInt32(page) - 1) * Convert.ToInt32(pagesize);
                    list = list.Skip(Skipcount).Take(Convert.ToInt32(pagesize)).ToList();


                    #region 联查
                    BasicBLL<tb_Product> product_db = new BasicBLL<tb_Product>();
                    var product_list = product_db.SearchAllInfo();

                    BasicBLL<tb_Station> station_db = new BasicBLL<tb_Station>();
                    var station_list = station_db.SearchAllInfo();

                    foreach (var item in list)
                    {
                        InjectionPlanModel dm = Tool.Mapper<InjectionPlanModel, tb_InjectionPlan>(item);
                        var product_info = product_list.FirstOrDefault(p => p.StockNo == item.StockNo);
                        if (product_info != null)
                        {
                            dm.PartNo = product_info.PartNo;
                            dm.ProductName = product_info.ProductName;
                        }

                        var station_info = station_list.FirstOrDefault(p => p.StationID == item.StationID);
                        if (station_info != null)
                        {
                            dm.StationNo = station_info.StationNo;
                        }

                        modelList.Add(dm);
                    }
                    #endregion



                    JsonDataModel<InjectionPlanModel> md = new JsonDataModel<InjectionPlanModel>();
                    md.total = total.ToString();
                    md.rows = modelList;
                    jsonStr = JSONTools.ScriptSerialize(md);
                }
                return jsonStr;
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return null;
            }

        }

        public string SearchInfoAll2(string page, string pagesize, string stationID, string stockNo, string StartTime, string EndTime)
        {
            try
            {

                string jsonStr = "[]";
                int total = 0;//总行数

                total = dal.SearchByTimeCount(stationID, stockNo, StartTime, EndTime);
                DataTable dt = dal.SearchByTime(Convert.ToInt32(page), Convert.ToInt32(pagesize), stationID, stockNo, StartTime, EndTime);

                List<tb_InjectionPlan> list = Tool.ConvertTo<tb_InjectionPlan>(dt).ToList();

                //List<tb_InjectionPlan> list = ef.tb_InjectionPlan.Where(p => DateTime.Parse(p.BeginTime) >= stime && DateTime.Parse(p.EndTime) <= etime).ToList();


                if (!String.IsNullOrEmpty(stationID))
                {
                    list = list.Where(p => p.StationID.Equals(stationID)).ToList();
                }
                if (!String.IsNullOrEmpty(stockNo))
                {
                    list = list.Where(p => p.StockNo.Contains(stockNo)).ToList();
                }

                list = list.OrderBy(p => p.BeginTime).ToList();

                List<InjectionPlanModel> modelList = new List<InjectionPlanModel>();
                if (list.Count > 0)
                {
                    total = list.Count;

                    int Skipcount = (Convert.ToInt32(page) - 1) * Convert.ToInt32(pagesize);
                    list = list.Skip(Skipcount).Take(Convert.ToInt32(pagesize)).ToList();


                    #region 联查
                    BasicBLL<tb_Product> product_db = new BasicBLL<tb_Product>();
                    var product_list = product_db.SearchAllInfo();

                    BasicBLL<tb_Station> station_db = new BasicBLL<tb_Station>();
                    var station_list = station_db.SearchAllInfo();

                    foreach (var item in list)
                    {
                        InjectionPlanModel dm = Tool.Mapper<InjectionPlanModel, tb_InjectionPlan>(item);
                        var product_info = product_list.FirstOrDefault(p => p.StockNo == item.StockNo);
                        if (product_info != null)
                        {
                            dm.PartNo = product_info.PartNo;
                            dm.ProductName = product_info.ProductName;
                        }

                        var station_info = station_list.FirstOrDefault(p => p.StationID == item.StationID);
                        if (station_info != null)
                        {
                            dm.StationNo = station_info.StationNo;
                        }

                        modelList.Add(dm);
                    }
                    #endregion



                    JsonDataModel<InjectionPlanModel> md = new JsonDataModel<InjectionPlanModel>();
                    md.total = total.ToString();
                    md.rows = modelList;
                    jsonStr = JSONTools.ScriptSerialize(md);
                }
                return jsonStr;
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return null;
            }

        }
        public bool UpdateInfo2(tb_InjectionPlan md)
        {
            try
            {

                //初始化要更新的字段
                string[] proNames = new string[3];
                proNames[0] = "workClass";
                proNames[1] = "JK_Weight";
                proNames[2] = "Waste_Weight";

                //必填字段初始化,如果不需要更新必填字段则设置为空即可,时间类型无需初始化
                //如果没有初始化必填字段,更新会报错


                return db.UpdateInfo(md, proNames);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return false;
            }

        }

        /// <summary>
        /// 查询全部信息
        /// </summary>
        /// <returns></returns>
        public List<tb_InjectionPlan> SearchAll()
        {
            try
            {
                var s_list = db.SearchAllInfo().ToList();
                return s_list;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 根据ID查询信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public tb_InjectionPlan SearchInfoByID(string id)
        {
            try
            {
                return db.SearchInfoByID(id);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return null;
            }

        }

        public String GetEndTime(tb_InjectionPlan md)
        {
            try
            {
                BasicBLL<tb_Plastic> Plastic_db = new BasicBLL<tb_Plastic>();

                var info = from c in Plastic_db.SearchAllInfo()
                           where c.StockNo == md.StockNo && c.StationID == md.StationID && c.IsBackup == 1
                           select c.CycleTime;

                if (info.FirstOrDefault() != null)
                {
                    double seconds = Convert.ToDouble(info.FirstOrDefault().Value) * Convert.ToDouble(md.PlanCount);
                    return Convert.ToDateTime(md.BeginTime).AddSeconds(seconds).ToString("yyyy-MM-dd HH:mm:ss");
                }
                return md.BeginTime;
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return null;
            }

        }

        public DataTable SearchInfoByName(string StationID)
        {
            try
            {
                return dal.SearchPlanByStation(StationID);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return null;
            }
        }
        public DataTable NextSearchInfoByName(string StationID)
        {
            try
            {
                return dal.NextSearchPlanByStation(StationID);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return null;
            }
        }

        public bool UpdateFinish(InjectionPlanModel md)
        {
            InjectionPlanDAL dal = new InjectionPlanDAL();
            try
            {
                return dal.UpdateFinish(md);
            }
            catch (Exception ex)
            {
                LogErrBLL.AddInfo(ex.ToString(), MethodBase.GetCurrentMethod());
                return false;
            }
        }


        public string GetStartTime(string StationID)
        {

            var bf = db.SearchInfoByKey("StationID", StationID).OrderByDescending(p => p.EndTime).FirstOrDefault();
            if (bf != null)
            {
                return bf.EndTime;
            }

            return "";

        }
    }
}