using DbCommon.BusinessCore.BaseCore;
using Newtonsoft.Json;
using ProjectManagementSystem.Common.Core;
using ProjectManagementSystem.Common.Extenions;
using ProjectManagementSystem.Common.Logger;
using ProjectManagementSystem.Common.WebApi;
using ProjectManagementSystem.Device.CommandCallback;
using ProjectManagementSystem.Device.Extenions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectManagementSystem.UI
{
    public partial class DebugApiCallFailedUI : UserControl, IDisplayUI
    {
        private ApiCallFailedManager apiCallFailedManager = new ApiCallFailedManager();

        public DebugApiCallFailedUI()
        {
            InitializeComponent();
        }

        public bool Init()
        {
            dataGridUI1.dataGridView1.CellClick += DataGridView1_CellClick;
            return true;
        }

        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        public void UpdateDisplay()
        {
            if (!this.Visible) return;

            var dataList = apiCallFailedManager.GetList().OrderBy(d => d.CreateTime).ToList();
            dataGridUI1.ShowDataGrid(dataList);
        }

        private async void button1_Click(object sender, EventArgs e)
        {

            try
            {
                (sender as Control).Enabled = false;

                var ret = await Task.Run(() =>
                {
                    return ReCallApi();
                });

                MessageBox.Show($"{ret}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            (sender as Control).Enabled = true;
        }

        private string ReCallApi()
        {
            string content = null;
            while (true)
            {
                var data = apiCallFailedManager.GetFirstOne();
                if(data == null)
                {
                    continue;
                }

                bool result = CustomerApi.LesApi(data.ApiName, data.Body, out content);
                if (result)
                {
                    apiCallFailedManager.Delete(data);
                }
                else
                {
                    break;
                }
            }

            return content;
        }
    }
}
