using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WSDDBBrowser.Core.Model;

namespace WSDDBBrowser.Core
{
    public class DBHelper:INotifyPropertyChanged
    {
        public static DBHelper Instance { get; } = new DBHelper();


        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 出错代码
        /// </summary>
        public string ErrorMsg { get; set; }

        public DBModel dBModel;

        
        public DBHelper()
        {

        }

        /// <summary>
        /// 从表获取数据
        /// </summary>
        public bool Init(string serverip, string userid, string password)
        {

            SqlConnection connection = new SqlConnection(
                $"data source={serverip};initial catalog=gmcjxt;user id={userid};password={password};MultipleActiveResultSets=True;App=EntityFramework"
                );
            try
            {
                dBModel = new DBModel(connection);
            }
            catch(Exception e)
            {
                ErrorMsg = e.Message;
                return false;
            }
            return true; 
        }


        bool IsContains(DateTime total_starttime, DateTime total_endtime, DateTime starttime, DateTime endtime, TimeSpan error)
        {
            if (starttime >= (total_starttime - error) && endtime <= (total_endtime + error))
                return true;
            else
                return false;
        }
        /// <summary>
        /// 通过订单号，时间查询
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public List<Process> GetProcessList(int stepNo, int machineNo, DateTime starttime, DateTime endtime, string orderNo)
        {
            List<g_sbProcess> sbProcesses;
            List<g_tgProcess> tgProcesses;
            try
            {
                if (string.IsNullOrEmpty(orderNo))
                    orderNo = "";

                sbProcesses = (from p in dBModel.sbProcesses
                                   where
                                   p.nJb == stepNo && p.nJt == machineNo &&
                                   (((p.tBeginTime > starttime) && (p.tBeginTime < endtime)) ||
                                   ((p.tEndTime > starttime) && (p.tEndTime < endtime)))
                                   && p.cOrderNo.Contains(orderNo) && p.bIsUpFin == true
                                   select p).ToList();

                tgProcesses = (from p in dBModel.tgProcesses
                                   where
                                   p.nJb == stepNo && p.nJt == machineNo &&
                                   (((p.tBeginTime > starttime) && (p.tBeginTime < endtime)) ||
                                   ((p.tEndTime > starttime) && (p.tEndTime < endtime)))
                                   && p.cOrderNo.Contains(orderNo) && p.bIsUpFin == true
                                   select p).ToList();
            }
            catch (Exception e)
            {
                throw e;
            }
            List<Process> Processes = new List<Process>();

            List<int> tgide = new List<int>();
            foreach (var sbProcess in sbProcesses)
            {
                Process process = new Process();
                process.HasSBData = true;
                process.SBID = sbProcess.ide;
                process.MachineNo = machineNo;
                process.StepNo = stepNo;
                process.OrderNo = sbProcess.cOrderNo;
                process.ProjectNo = sbProcess.cProjectNo;
                process.TechnologyNo = sbProcess.cTechnologyNo;
                process.BeginTime = (DateTime)sbProcess.tBeginTime;
                process.EndTime = (DateTime)sbProcess.tEndTime;
                process.TotalLen = (double)sbProcess.nTotalLen;

                //找测厚数据 时间段在 温度时间内的
                process.TGID = new List<int>();
                //process.TGID.AddRange(
                //    from p in tgProcesses
                //    where
                //    IsContains(
                //        process.BeginTime, process.EndTime,
                //        (DateTime)p.tBeginTime, (DateTime)p.tEndTime,
                //        TimeSpan.FromMinutes(5)
                //    )
                //    select p.ide
                //);
                process.TGID.AddRange(
                    from p in tgProcesses
                    where
                    p.nMasterId == sbProcess.nId
                    select p.ide
                );
                if (process.TGID.Count() > 0)
                    process.HasTGData = true;
                else
                    process.HasTGData = false;

                tgide.AddRange(process.TGID);

                Processes.Add(process);
            }

            //把测厚仪剩下的添加进去
            var tgProcesses2 = tgProcesses.FindAll(p => !tgide.Contains(p.ide));
            foreach (var tgProcess in tgProcesses2)
            {
                Process process = new Process();
                process.TGID = new List<int>();
                process.TGID.Add(tgProcess.ide);
                process.HasTGData = true;

                process.HasSBData = false;
                process.MachineNo = machineNo;
                process.StepNo = stepNo;
                process.OrderNo = tgProcess.cOrderNo;
                process.ProjectNo = tgProcess.cProjectNo;
                process.TechnologyNo = tgProcess.cTechnologyNo;
                process.BeginTime = (DateTime)tgProcess.tBeginTime;
                process.EndTime = (DateTime)tgProcess.tEndTime;
                process.TotalLen = (double)tgProcess.nTotalLen;

                Processes.Add(process);
            }

            

            return Processes;
        }


        public TGProcessPack GetTGProcessPack(int ide)
        {
            TGProcessPack processPack = new TGProcessPack();

            processPack.Process = (from n in dBModel.tgProcesses where n.ide == ide select n).ToList().First();

            var g_tgNumbers = (from n in dBModel.tgNumbers where n.nProcessId == ide orderby n.ide select n).ToList();
            processPack.Numbers = g_tgNumbers;

            var g_tgTechs = (from n in dBModel.tgTechs where n.nProcessId == ide orderby n.ide select n).ToList();
            processPack.Technologies = g_tgTechs;

            var g_tgRecords = (from n in dBModel.tgRecords where n.nProcessId == ide orderby n.ide select n).ToList();
            var lc_tgRecords = AutoMapper.Mapper.Map<List<g_tgRecord>, List<lc_tgRecord>>(g_tgRecords).ToList();

            processPack.ScanDatas = lc_tgRecords;
            return processPack;
        }
        public SBProcessPack GetSBProcessPack(int ide)
        {
            SBProcessPack processPack = new SBProcessPack();
            processPack.Process = (from n in dBModel.sbProcesses where n.ide == ide select n).ToList().First();

            var g_sbNumbers = (from n in dBModel.sbNumbers where n.nProcessId == ide orderby n.ide select n).ToList();
            processPack.Numbers = g_sbNumbers;

            var g_sbUsers = (from n in dBModel.sbUsers where n.nProcessId == ide orderby n.ide select n).ToList();
            processPack.Users = g_sbUsers;

            var g_sbTechs = (from n in dBModel.sbPTechs where n.nProcessId == ide orderby n.ide select n).ToList();
            processPack.Technologies = g_sbTechs;

            var g_sbRecords = (from n in dBModel.sbRecords where n.nProcessId == ide orderby n.ide select n).ToList();

            processPack.Records = g_sbRecords;
            return processPack;
        }
    }



    #region 链接表的关系
    /// <summary>
    /// 包装 DB_Profile， 组织 DB_Profile， DB_ScanData....
    /// </summary>
    public class TGProcessPack
    {
        public g_tgProcess Process;
        public List<g_tgTech> Technologies;
        public List<g_tgNumber> Numbers;
        public List<lc_tgRecord> ScanDatas;
    }
    /// <summary>
    /// 包装 DB_Profile， 组织 DB_Profile， DB_ScanData....
    /// </summary>
    public class SBProcessPack
    {
        public g_sbProcess Process;
        public List<g_sbPTech> Technologies;
        public List<g_sbNumber> Numbers;
        public List<g_sbUser> Users;
        public List<g_sbRecord> Records;
    }

    #endregion

    public class Process
    {
        /// <summary>
        /// 温度数据 id
        /// </summary>
        public int SBID { get; set; }

        /// <summary>
        /// 测厚仪数据 id
        /// </summary>
        public List<int> TGID { get; set; }

        /// <summary>
        /// 有温度数据
        /// </summary>
        public bool HasSBData { get; set; }
        
        /// <summary>
        /// 有测厚仪数据
        /// </summary>
        public bool HasTGData { get; set; }

        public int StepNo { get; set; }

        public int MachineNo { get; set; }

        public string OrderNo { get; set; }

        public string ProjectNo { get; set; }

        public string TechnologyNo { get; set; }

        public DateTime BeginTime { get; set; }

        public DateTime EndTime { get; set; }

        public double TotalLen { get; set; }
    }
}
