using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Configuration.ConfigurationManager;
using static System.Windows.Forms.LinkLabel;


/// <summary>
/// 
/// </summary>
namespace SYNC_SAP_MES
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FormSAP : Form
    {
        /// <summary>
        /// 
        /// </summary>
        static string Curr_OrderNo = "";

        static string Split_OrderNo = "";
        static string Split_Order = "";
        /// <summary>
        /// 
        /// </summary>
        public FormSAP()
        {
            InitializeComponent();
            PP.ConnectionString = AppSettings["ConnectionString"];
            timer_OnLine_Show.Enabled = true;
            dtPicker_SyncDate.Value = DateTime.Now;
        }
        /// <summary>
        /// 显示通讯状态
        /// </summary>
        private void Show_OnLineState()
        {
            //状态显示
            OnLineStatus_Check();
            OnLineState_C(pb_OnLine_Sql, PP.OnLine_Sql);
            OnLineState_C(pb_OnLine_SAP, PP.OnLine_SAP);
        }
        /// <summary>
        /// 显示通讯状态
        /// </summary>
        /// <param name="pb"></param>
        /// <param name="onLine"></param>
        private void OnLineState_C(PictureBox pb, bool onLine)
        {
            pb.Image = onLine ? global::SYNC_SAP_MES.Properties.Resources.连接
                    : global::SYNC_SAP_MES.Properties.Resources.断开连接;
        }
        private static bool Ping(string ip)
        {
            return new Ping().Send(ip).Status == IPStatus.Success ? true : false;
        }
        public static void OnLineStatus_Check()
        {
            try
            {
                PP.OnLine_Sql = SqlOperation.ExecuteSql("select getdate()", out DataTable dt, out string error);
            }
            catch (Exception err)
            {
                PP.OnLine_Sql = false;
            }

            try
            {
                //PP.OnLine_SAP = READ_SAP.GetMCode().Rows.Count > 0 ? true : false;
                PP.OnLine_SAP = Ping("mes4api.weichai.com");
            }
            catch (Exception err)
            {
                PP.OnLine_SAP = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_OnLine_Show_Tick(object sender, EventArgs e)
        {
            timer_OnLine_Show.Enabled = false;
            Show_OnLineState();
            if (!chk_syncModel.Checked && DateTime.Now.Date > dtPicker_SyncDate.Value.Date)
            {
                dtPicker_SyncDate.Value = DateTime.Now;
                SyncFunc_From_SAP.SyncDate = dtPicker_SyncDate.Value.ToString("yyyy-MM-dd");
            }
            timer_OnLine_Show.Enabled = true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ManualSync_Click(object sender, EventArgs e)
        {
            if (SyncFunc_From_SAP.IsSyncing)
            {
                PP.main.ShowError("您正在同步计划数据，不能重复操作！");
                return;
            }

            if (MessageBox.Show("确认手动同步计划数据吗？", "确认提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                SyncFunc_From_SAP.SyncDataOperationTask("手动同步");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private int count = 0;
        /// <summary>
        /// 
        /// </summary>
        public void ReInit()
        {
            count = 0;

            if (lb_ErrCount.InvokeRequired)
            {
                lb_ErrCount.Invoke(new Action(delegate ()
                {
                    lb_ErrCount.Text = "消息数量：" + 0.ToString();
                }));
            }
            else
            {
                lb_ErrCount.Text = "消息数量：" + 0.ToString();
            }

            if (txt_Err.InvokeRequired)
            {
                txt_Err.Invoke(new Action(delegate ()
                {
                    txt_Err.Clear();
                }));
            }
            else
            {
                txt_Err.Clear();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="s"></param>
        public void ShowError(string s)
        {
            count++;
            if (count > 3000) ReInit();

            if (lb_ErrCount.InvokeRequired)
            {
                lb_ErrCount.Invoke(new Action(delegate ()
                {
                    lb_ErrCount.Text = "消息数量：" + count.ToString();
                }));
            }
            else
            {
                lb_ErrCount.Text = "消息数量：" + count.ToString();
            }


            if (txt_Err.InvokeRequired)
            {
                txt_Err.Invoke(new Action(delegate ()
                {
                    txt_Err.AppendText(count.ToString("000000") + " [ " + DateTime.Now.ToString("G") + " ]  " + s + "\r\n");
                    txt_Err.ScrollToCaret();
                    // SlMesDbIterface.LogRecord.Insert_Log(SlMesDbIterface.LogRecord.Type_Log.Tip, s);
                }));
            }
            else
            {
                txt_Err.AppendText(count.ToString("000000") + " [ " + DateTime.Now.ToString("G") + " ]  " + s + "\r\n");
                txt_Err.ScrollToCaret();
                // SlMesDbIterface.LogRecord.Insert_Log(SlMesDbIterface.LogRecord.Type_Log.Tip, s);
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ManualCheck_Click(object sender, EventArgs e)
        {
            SyncFunc_From_SAP.OnLineStatus_Check();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Refresh_MesPlan_Click(object sender, EventArgs e)
        {
            DateTime SearchDate= dtPicker_MES.Value;
            //Sql_Biz_SAP.Get_MesPlan(SearchDate, out DataTable table_Plan);
            ////Sql_Biz_SAP.Get_MesSpiltPlan(DateTime.Parse("2024-01-04"), out DataTable table_Plan);
            //dgv_MesPlan.DataSource = table_Plan;

            //var dateDay = dtp_yyyyMMdd.Value;
            //var line = txt_Line.Text;
            //var table = READ_SAP.GetPlan(dateDay, line);
            //dgv_SAPPlan.DataSource = table;
            //label_Count_Plan.Text = $"数量：{table.Rows.Count}";
            //if (cb_SaveFile.Checked)
            //{
            //    var str = JsonConvert.SerializeObject(table);
            //    File.WriteAllText("Plan.json", str);
            //}

            //dgv_SpiltPlan.DataSource=null;
            //dgv_MesOrderNo_BOM.DataSource = null;
        }

        private void FormSAP_Load(object sender, EventArgs e)
        {
            SyncFunc_From_SAP.SyncTask_SAP();
        }

        private void btn_ManualSync_Plan_Click(object sender, EventArgs e)
        {

        }

        private void btn_ManualSync_PlanBOM_Click(object sender, EventArgs e)
        {
            //var dlg = new D_Sure();
            //if (dlg.ShowDialog() == DialogResult.OK)
            //{
            //    //3.同步订单BOM
            //    var success_BOM = SyncFunc_From_SAP.Move_SAP_To_MES_Order_BOM(Curr_OrderNo);
            //    PP.main.ShowError($"【手动强制】{Curr_OrderNo}订单BOM同步完成！\r\n");
            //    MessageBox.Show("【手动强制】订单BOM同步成功！");
            //}

        }


        private void button3_Click_1(object sender, EventArgs e)
        {
            DateTime startdate = DateTime.Parse("2024-06-11");
            //READ_SAP.GetPlan_Test(startdate, "ZP02");
        }


        private void btn_Query_Click(object sender, EventArgs e)
        {
            DateTime SearchDate = dtPicker_ProductDate.Value;
            var key_OrderNum=this.txt_OrderNum.Text.Trim();
            Sql_Biz_SAP.Get_Mes_ExcutePlan(SearchDate, key_OrderNum, out DataTable table_ExcutePlan);
            //Sql_Biz_SAP.Get_MesSpiltPlan(DateTime.Parse("2024-01-04"), out DataTable table_Plan);
            dgv_ExcutePlan.DataSource = table_ExcutePlan;

        }



        private void FormSAP_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确认退出计划同步程序吗？", "操作确认", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
        }

        private void chk_syncModel_CheckedChanged(object sender, EventArgs e)
        {
            btn_ManualSync.Enabled= chk_syncModel.Checked;
        }

        private void dtPicker_SyncDate_ValueChanged(object sender, EventArgs e)
        {
            SyncFunc_From_SAP.SyncDate=dtPicker_SyncDate.Value.ToString("yyyy-MM-dd");
        }
    }
}
