using DbCommon.BusinessCore.BaseCore;
using Pms.DataLibrary.Models;
using Pms.DataLibrary.Order;
using ProjectManagementSystem.Common.Extenions;
using ProjectManagementSystem.Common.Models;
using ProjectManagementSystem.Common.Service;
using ProjectManagementSystem.Common.WebApi;
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 DebugExceptionTaskUI : UserControl, IDisplayUI
    {
        private MaterialBindingManager materialBindingManager;

        public DebugExceptionTaskUI()
        {
            InitializeComponent();
        }

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

        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string taskId = dataGridUI1.GetCurrentColValue("TaskID");
            if (string.IsNullOrEmpty(taskId)) return;

            var stepInfoList = PmsApi.GetHistoryStepList(taskId);
            if (stepInfoList == null) return;

            var posArray = stepInfoList
                .Where(d => !string.IsNullOrEmpty(d.WareHouseID))
                .OrderBy(d => d.StepID)
                .Select(d => d.WareHouseID)
                .ToArray();
            //comboBox2.Items.AddRange(posArray);

            comboBox1.Text = taskId;
            comboBox2.Text = posArray.First();
            comboBox3.Text = posArray.Last();

        }

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

            string taskId = dataGridUI1.GetCurrentColValue("TaskID");
            string taskId_StepList = dataGridUI2.GetCurrentColValue("TaskID");
            
            if(!string.IsNullOrEmpty(taskId_StepList)
                && taskId == taskId_StepList)
            {
                return;
            }

            if (string.IsNullOrEmpty(taskId))
            {
                dataGridUI2.ShowDataGrid<StepData>(null);
                return;
            }

            var stepInfoList = PmsApi.GetHistoryStepList(taskId);
            if (stepInfoList == null) return;

            dataGridUI2.ShowDataGrid(stepInfoList.OrderBy(d => d.StepID).ToList());
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var startTime = DateTime.Now.AddDays(-1).Date;
                var endTime = DateTime.Now.AddDays(1).Date;

                if (endTime <= startTime)
                {
                    MessageBox.Show("结束时间必须晚于开始时间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                (sender as Control).Enabled = false;
                var lists = await Task.Run(() =>
                {
                    var taskDataList = PmsApi.GetHistoryTaskList(startTime, endTime);
                    if (taskDataList == null) return taskDataList;

                    taskDataList = taskDataList.Where(d => d.TaskState != ETaskState.Finished).ToList();
                    foreach (var item in taskDataList)
                    {
                        item.AllWarehouse = item.AllWarehouse.ToShortPosString();
                    }

                    return taskDataList;
                });

                if (lists == null) return;
                dataGridUI1.ShowDataGrid(lists);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            (sender as Control).Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dialog = new SaveFileDialog())
            {
                dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                dialog.FileName = string.Format("历史数据_{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss"));
                dialog.Filter = "Excel文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
                dialog.ValidateNames = true;
                dialog.CheckPathExists = true;
                dialog.AddExtension = true;
                DialogResult dialogResult = dialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    try
                    {
                        var dataList = dataGridUI1.GetDataTable();

                        Common.Config.ExcelConfig.Instance.SaveExcel(dialog.FileName, dataList);
                        MessageBox.Show("导出成功！");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }


        private async void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string taskId = comboBox1.Text;
                string currentPos = comboBox2.Text;
                if (string.IsNullOrEmpty(taskId) || string.IsNullOrEmpty(currentPos)) return;


                string allWarehouse = dataGridUI1.GetCurrentColValue("AllWarehouse");

                string text = $"确定要{(sender as Control).Text} {taskId}？（{currentPos}）";
                var dialogResult = MessageBox.Show(text, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (dialogResult != DialogResult.OK)
                {
                    return;
                }
                
                (sender as Control).Enabled = false;
                var ret = await Task.Run(() =>
                {
                    return AgvCallback(taskId, currentPos, "outbin");
                });

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

            (sender as Control).Enabled = true;
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string taskId = comboBox1.Text;
                string endPos = comboBox3.Text;
                if (string.IsNullOrEmpty(taskId) || string.IsNullOrEmpty(endPos)) return;


                string allWarehouse = dataGridUI1.GetCurrentColValue("AllWarehouse");

                string text = $"确定要{(sender as Control).Text} {taskId}？（{allWarehouse}）";
                var dialogResult = MessageBox.Show(text, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (dialogResult != DialogResult.OK)
                {
                    return;
                }

                (sender as Control).Enabled = false;
                var ret = await Task.Run(() =>
                {
                    return AgvCallback(taskId, endPos, "end");
                });

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

            (sender as Control).Enabled = true;
        }

        private (bool, string) AgvCallback(string taskId, string currentPosition, string method)
        {
            var t = PmsTaskService.Instance.GetTaskState(taskId);
            if (t == null)
            {
                return (false, "获取任务状态失败");
            }

            t.currentPositionCode = currentPosition;
            t.method = method;
            bool result = CustomerApi.AgvCallback(t, out string content);

            return (true, $"任务状态上报{result.ToChineseString()} {content}");
        }

        private async void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string taskId = comboBox1.Text;
                string startPos = comboBox2.Text;
                string endPos = comboBox3.Text;
                if (string.IsNullOrEmpty(taskId) || string.IsNullOrEmpty(startPos) || string.IsNullOrEmpty(endPos)) return;

                string allWarehouse = dataGridUI1.GetCurrentColValue("AllWarehouse");

                string text = $"确定要{(sender as Control).Text} {taskId}？（{allWarehouse}）";
                var dialogResult = MessageBox.Show(text, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (dialogResult != DialogResult.OK)
                {
                    return;
                }
                (sender as Control).Enabled = false;

                var ret = await Task.Run(() =>
                {
                    return ReTask(taskId, startPos, endPos);
                });

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

            (sender as Control).Enabled = true;
        }

        private (bool, string) ReTask(string taskId, string startPos, string endPos)
        {
            var mData = materialBindingManager.GetById(taskId);
            if (mData == null)
            {
                return (false, "获取物料信息失败");
            }

            PmsTaskInfoDto data = new PmsTaskInfoDto();
            data.TaskID = $"{taskId};{DateTime.Now.ToString("yyyyMMddHHmmssfffffff")}";
            data.LocationCode = startPos;
            data.TargetLocationCode = endPos;

            mData.TaskID = data.TaskID;
            var result = materialBindingManager.Save(mData);
            if (!result)
            {
                return (false, "保存物料信息失败");
            }

            var result2 = PmsTaskService.Instance.TaskAddNoCheck(data);

            return (true, result2.message);
        }

    }
}
