using Aitex.Core.RT.DBCore;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.OperationCenter;
using Aitex.Core.RT.Routine;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Math;
using DocumentFormat.OpenXml.Office.Word;
using DocumentFormat.OpenXml.Wordprocessing;
using MECF.Framework.Common.DataCenter;
using MECF.Framework.Common.OperationCenter;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Xml.Linq;

namespace MECF.Framework.UI.Client.TrayThickness.HistoryData
{
    public class HistoryCoatingSqlHelp
    {
        private List<string> TrayTabList = new List<string>()
        {
            "tray_number",
            "tray_inner_number",
            "ring_inner_number",
            "ring_outer_number"
        };
        public List<TrayCoatingThickness> QueryUpdateAll_Tray()
        {
            string cmd = $"select * from tray_thickness_main order by create_time desc ";
            return QueryTrayCoatingList(cmd);
        }
        public List<TrayCoatingThickness> QueryUpdateTime_Tray(string starTime, string endTime)
        {
            string cmd = $"select * from tray_thickness_main where create_time between '{starTime}' and '{endTime}' order by create_time desc";
            return QueryTrayCoatingList(cmd);
        }
        public List<CoatingData> QueryUnitName_Tray(string name, string starTime="", string endTime="")
        {
            string time = $"and create_time between '{starTime}' and '{endTime}'";
            string cmd = $"select * from tray_thickness_main where tray_number = '{name}' {time} order by create_time desc";
            return QueryTrayBase(cmd, true);
        }

        /// <summary>
        /// Tray环交叉使用记录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="starTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public List<TrayCoatingThickness> QueryEntiretyTray(string name, string starTime = "", string endTime = "")
        {

            //根据TrayID获取对应内外编号
            List<TrayCoatingThickness> trayCoatingList = new List<TrayCoatingThickness>();
            List<string> rowName = new List<string>();
            string cmdAllName = "select *  from tray_thickness_data where " +
                        $"tray_number='{name}' " +
                        $"or tray_inner_number = '{name}' " +
                        $"or ring_inner_number = '{name}'  " +
                        $"or ring_outer_number = '{name}'";

            var dtAll = QueryDataClient.Instance.Service.QueryData(cmdAllName);
            if (dtAll !=null && dtAll.Rows.Count != 0)
            {
                for (int i = 0; i < dtAll.Rows.Count; i++)
                {
                    for (int j = 0; j < TrayTabList.Count; j++)
                    {
                        string value = dtAll.Rows[i][TrayTabList[j]].ToString();
                        if (!rowName.Contains(value))
                            rowName.Add(value);
                    }
                }
            }
            string cmdName1 = "";
            for (int i = 0; i < rowName.Count; i++)
            {
                if (i == rowName.Count - 1)
                    cmdName1 += $"tray_number = '{rowName[i]}' ";
                else
                    cmdName1 += $"tray_number = '{rowName[i]}' or ";
            }
            string time = $"and create_time between '{starTime}' and '{endTime}'";
            string cmdName = $"select * from tray_thickness_main where {cmdName1} {time} order by create_time desc";
            trayCoatingList = QueryTrayCoatingList(cmdName);
            return trayCoatingList;
        }




        public List<PMCoatingThickness> QueryUpdateAll_PM()
        {
            string cmd = $"select * from pm_thickness_main order by create_time desc ";
            return QueryPMCoatingList(cmd);
        }
        public List<PMCoatingThickness> QueryUpdateTime_PM(string starTime, string endTime)
        {
            string cmd = $"select * from pm_thickness_main where create_time between '{starTime}' and '{endTime}' order by create_time desc";
            return QueryPMCoatingList(cmd);
        }
        public List<PMCoatingThickness> QueryUnitName_PM(string name, string starTime = "", string endTime = "")
        {
            string time = $"and create_time between '{starTime}' and '{endTime}'";
            string cmd = $"select * from pm_thickness_main where pm_cycle = '{name}' {time} order by create_time desc";
            return QueryPMCoatingList(cmd);
        }

        private List<CoatingData> QueryTrayBase(string cmd, bool isNum = false)
        {
            List<CoatingData> coatingDataList = new List<CoatingData>();
            try
            {
                var dt = QueryDataClient.Instance.Service.QueryData(cmd);//只能界面用
                if (dt == null || dt.Rows.Count == 0)
                    return null;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i].ItemArray.Length != 0)
                    {
                        CoatingData coatingData = new CoatingData()
                        {
                            SerialNumber = dt.Rows[i]["tray_number"].ToString(),
                            MAX = dt.Rows[i]["tray_max_thickness"].ToString(),
                            PmOwned = dt.Rows[i]["pm_number"].ToString(),
                            Current = dt.Rows[i]["tray_coating_thickness"].ToString(),
                            CreatTime = dt.Rows[i]["create_time"].ToString(),
                            Caption = dt.Rows[i]["tray_label"].ToString(),
                            Index = $"Tray {i / 4 + 1}"
                        };
                        if (isNum)
                        {
                            coatingData.Index = (i + 1).ToString();
                        }
                        coatingDataList.Add(coatingData);
                    }
                    else
                        coatingDataList.Add(new CoatingData());
                }
            }
            catch (Exception)
            {
                return null;
            }
            return coatingDataList;
        }

        private List<TrayCoatingThickness> QueryTrayCoatingList(string cmd)
        {
            List<TrayCoatingThickness> trayCoatingList = new List<TrayCoatingThickness>();
            try
            {
                TrayCoatingThickness trayCoatingThickness = new TrayCoatingThickness();
                var dt = QueryDataClient.Instance.Service.QueryData(cmd);//只能界面用
                if (dt == null || dt.Rows.Count == 0)
                    return null;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                   
                        CoatingData coatingData = new CoatingData()
                        {
                            SerialNumber = dt.Rows[i]["tray_number"].ToString(),
                            MAX = dt.Rows[i]["tray_max_thickness"].ToString(),
                            PmOwned = dt.Rows[i]["pm_number"].ToString(),
                            Current = dt.Rows[i]["tray_coating_thickness"].ToString(),
                            CreatTime = dt.Rows[i]["create_time"].ToString(),
                            Caption = dt.Rows[i]["tray_label"].ToString(),
                            Index = $"Tray {i / 4 + 1}"
                        };
                        switch (coatingData.Caption)
                        {
                            case "石墨托盘":
                                trayCoatingThickness.Tray = coatingData;
                                break;
                            case "内部托架":
                                trayCoatingThickness.TrayInner = coatingData;
                            break;
                            case "中间托架":
                                trayCoatingThickness.RingInner = coatingData;
                            break;
                            case "外部托架":
                                trayCoatingThickness.RingOuter = coatingData;
                            break;
                            default:
                                break;
                        }
                    if ((i % 4) == 3)//Tray是4个数据为一个循环
                    { 
                        trayCoatingList.Add(trayCoatingThickness);
                        trayCoatingThickness = new TrayCoatingThickness();
                    }
                    


                }
                    
                
            }
            catch (Exception)
            {
                return null;
            }
            return trayCoatingList;
        }
        
        private List<PMCoatingThickness> QueryPMCoatingList(string cmd)
        {
            List<PMCoatingThickness> pmCoatingList = new List<PMCoatingThickness>();
            try
            {
                PMCoatingThickness pmCoatingThickness = new PMCoatingThickness();
                var dt = QueryDataClient.Instance.Service.QueryData(cmd);//只能界面用
                if (dt == null || dt.Rows.Count == 0)
                    return null;

                for (int i = 0; i < dt.Rows.Count; i++)
                {

                    CoatingData coatingData = new CoatingData()
                    {
                        SerialNumber = dt.Rows[i]["pm_cycle"].ToString(),
                        MAX = dt.Rows[i]["pm_max_thickness"].ToString(),
                        PmOwned = dt.Rows[i]["pm_number"].ToString(),
                        Current = dt.Rows[i]["pm_coating_thickness"].ToString(),
                        CreatTime = dt.Rows[i]["create_time"].ToString(),
                        Caption = dt.Rows[i]["pm_label"].ToString(),
                        Index = $"{i + 1}"
                    };
                    if (coatingData.Caption.Contains("小周期"))
                        pmCoatingThickness.MinorCycle = coatingData;
                    else
                        pmCoatingThickness.MajorCycle = coatingData;
                    
                    
                    if ((i % 2) == 1)//MP是2个数据为一个循环
                    {
                        pmCoatingList.Add(pmCoatingThickness);
                        pmCoatingThickness = new PMCoatingThickness();
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
            return pmCoatingList;
        }
        public bool GrowTray(string tray_guid, double GrowthRate, double Seconds)//Tray更新增长厚度
        {
            //
            try
            {
                string tray_numbers = "";
                string sSql = $"select * from tray_thickness_data where tray_guid like '{tray_guid}'";
                DataSet ds = DB.ExecuteDataSet(sSql);
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                    return false;
                
               
                tray_numbers = "'" + ds.Tables[0].Rows[0]["tray_number"].ToString() + "','" + ds.Tables[0].Rows[0]["tray_inner_number"].ToString() + "','" + 
                    ds.Tables[0].Rows[0]["ring_inner_number"].ToString() + "','" + ds.Tables[0].Rows[0]["ring_outer_number"].ToString() + "'";

                string growthValue = (GrowthRate * Seconds / 3600).ToString("0.000"); //μm
                string[] gCmd = { $"update tray_thickness_main set tray_coating_thickness = tray_coating_thickness + {growthValue} " +
                        $"where create_time = (select create_time FROM tray_thickness_main where tray_number in ({tray_numbers})  " +
                        $"ORDER BY  create_time DESC LIMIT 1 ) " };

                List<string> coatingNameList = new List<string>();
                coatingNameList.Add(ds.Tables[0].Rows[0]["tray_number"].ToString());
                coatingNameList.Add(ds.Tables[0].Rows[0]["tray_inner_number"].ToString());
                coatingNameList.Add(ds.Tables[0].Rows[0]["ring_inner_number"].ToString());
                coatingNameList.Add(ds.Tables[0].Rows[0]["ring_outer_number"].ToString());

                foreach (string name in coatingNameList)
                {
                    OP.DoOperation("GEM_GrowCoating",
                       name, growthValue);
                }

                return DB.ExcuteTransAction(gCmd.ToList());

            }
            catch (Exception ex)
            {
                LOG.Write($"GrowTray { ex}");
                return false;
            }
        }

        public bool GrowPM(string pmName, double GrowthRate, double Seconds)//PM更新增长厚度
        {
            try
            {
                string pm_Cmd = "";
                string sSql = $"select * from pm_thickness_data where pm_guid like '{pmName}' ";
                DataSet ds = DB.ExecuteDataSet(sSql);
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                    return false;

                pm_Cmd = $"'{ds.Tables[0].Rows[0]["pm_minor_cycle"].ToString()}','{ds.Tables[0].Rows[0]["pm_major_cycle"].ToString()}'";


                //
                string growthValue = (GrowthRate * Seconds / 3600).ToString("0.00"); //μm
                string[] gCmd = { $"update pm_thickness_main set pm_coating_thickness = pm_coating_thickness + {growthValue} " +
                                  $"where create_time = (select create_time FROM pm_thickness_main where pm_cycle in ({pm_Cmd})  " +
                                  $"ORDER BY  create_time DESC LIMIT 1 ) " };

                return DB.ExcuteTransAction(gCmd.ToList());

            }
            catch (Exception ex)
            {
                LOG.Write($"GrowPM {ex}");
                return false;
            }
        }

        public bool GrowPMForMaintenance(string pmName, double GrowthRate, double Seconds)//PM更新增长厚度
        {
            try
            {
                string growthValue = (GrowthRate * Seconds / 3600).ToString("0.00"); //μm
                string gCmd = $"update pm_thickness_data2 set thickness = thickness + {growthValue} " +
                              $"where pm_name = '{pmName}';";

                return DB.ExecuteNonQuery(gCmd) == 1;

            }
            catch (Exception ex)
            {
                LOG.Write($"GrowPM {ex}");
                return false;
            }
        }

        public bool CheckExceedTray(string tray_guid,string pmName, out string infor)
        {
            infor = "";
            try
            {
                string sSql = $"select * from tray_thickness_data where tray_guid like '{tray_guid}'";
                DataSet ds = DB.ExecuteDataSet(sSql);
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                    return false;

                string cmd = "select tray_coating_thickness , tray_max_thickness,tray_label from tray_thickness_main where ";
                cmd += $"tray_number='{ds.Tables[0].Rows[0]["tray_number"].ToString()}' " +
                    $"or tray_number = '{ds.Tables[0].Rows[0]["tray_inner_number"].ToString()}' " +
                    $"OR tray_number = '{ds.Tables[0].Rows[0]["ring_inner_number"].ToString()}'    " +
                    $"or tray_number = '{ds.Tables[0].Rows[0]["ring_outer_number"].ToString()}'";
                    
                string timeCmd = $" ORDER  BY  create_time DESC LIMIT 4";
                
                ds = DB.ExecuteDataSet(cmd+ timeCmd);

                if (ds == null || ds.Tables[0].Rows.Count == 0)
                    return false;

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    double coating = double.Parse( ds.Tables[0].Rows[i]["tray_coating_thickness"].ToString());
                    double max =double.Parse(ds.Tables[0].Rows[i]["tray_max_thickness"].ToString());

                    if (coating>max)
                    {
                        string lab = ds.Tables[0].Rows[i]["tray_label"].ToString();
                        infor = $"{pmName}腔体 Tray {lab}  MAX={max}  Coating={coating}";
                        return true;
                    }  
                }
            }
            catch (Exception ex)
            {
                LOG.Write($"HistoryCoatingSqlHelp.CheckExceedTray error {ex}");
                return false;
            }
            
            return false;
        }

        public bool CheckExceedPM(string pmId, out string infor)
        {
            infor = "";
            try
            {
                string sSql = $"select * from pm_thickness_data where pm_guid like '{pmId}'";
                DataSet ds = DB.ExecuteDataSet(sSql);
                if (ds == null || ds.Tables[0].Rows.Count == 0)
                    return false;


                string cmd = "select pm_coating_thickness , pm_max_thickness,pm_label from pm_thickness_main where ";
                cmd += $"pm_cycle='{ds.Tables[0].Rows[0]["pm_minor_cycle"].ToString()}' " +
                           $"or pm_cycle = '{ds.Tables[0].Rows[0]["pm_major_cycle"].ToString()}'";
                
                string timeCmd = $" ORDER  BY  create_time DESC LIMIT 2";

                ds = DB.ExecuteDataSet(cmd + timeCmd);

                if (ds == null || ds.Tables[0].Rows.Count == 0)
                    return false;

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    double coating = double.Parse(ds.Tables[0].Rows[i]["pm_coating_thickness"].ToString());
                    double max = double.Parse(ds.Tables[0].Rows[i]["pm_max_thickness"].ToString());

                    if (coating > max)
                    {
                        string lab = ds.Tables[0].Rows[i]["pm_label"].ToString();
                        infor = $"{lab}  MAX={max}  Coating={coating}";
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.Write($"HistoryCoatingSqlHelp.CheckExceedPM error {ex}");
                return false;
            }

            return false;
        }
    }
}
