using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DbCommon.BusinessCore.BaseCore;
using DbCommon.Enties.DbModels;
using DbCommon.Function;
using PmsSecondaryPackaging.Interface.Service;
using PmsSecondaryPackaging.Interface.Model.TaskBook;
using ProjectManagementSystem.Common.Log;
using Newtonsoft.Json;
using PmsSecondaryPackaging.Interface.Model.WareHouse;
using PmsSecondaryPackaging.SystemConfig.Service;
using DbCommon.Extenions;

namespace ProjectManagementSystem.UI
{
    public partial class DebugUI : UserControl, IDisplayUI
    {
        public InterfaceService interfaceService { get; set; } = new InterfaceService();
        CConfigManager cConfigManager = new CConfigManager();

        public DebugUI()
        {
            InitializeComponent();
        }

        public bool Init()
        {
            if (!interfaceService.GetTaskBookList(out List<TaskBookInfoModel> taskBookInfoList, out string msg))
            {
                CLog.Instance.GetLog("System").WriteWarn("获取任务模板失败，请检查AGVS系统是否启动！！！");
            }
            cmbTaskTemplate.DataSource = taskBookInfoList?.Select(d => d.Name).ToList();

            if (interfaceService.GetWarehouseListInfo(null, out List<WareHouseInfoModel> wareHouseInfoList, out msg))
            {
                cmbLocationCode.DataSource = wareHouseInfoList.Select(d => d.WareHouseID).ToList();
            }

            if (interfaceService.GetTaskDataList(out List<TaskDetailInfoModel> taskDetailInfoList, out string Message))
            {
                cmbParentTaskId.DataSource = taskDetailInfoList.Select(d => d.TaskID).ToList();
            }

            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string upLocation = cmbLocationCode.Text.Trim();
            string taskTemplate = cmbTaskTemplate.Text.Trim();
            string parentTaskId = cmbParentTaskId.Text.Trim();

            if (string.IsNullOrEmpty(upLocation)
                || string.IsNullOrEmpty(taskTemplate))
            {
                ShowErrMsg("任务点或任务模板检查异常");
                return;
            }

            if (upLocation.Contains(" "))
            {
                ShowErrMsg("任务点不能包含空格");
                return;
            }

            if (upLocation.Contains("，"))
            {
                ShowErrMsg("任务点不能包含中文状态的逗号");
                return;
            }

            string[] posArr = Tools.StringToPosArray(upLocation);
            if(posArr == null
                || posArr.Length == 0)
            {
                ShowErrMsg("任务点转换失败");
                return;
            }

            foreach (var item in posArr)
            {
                if (!interfaceService.GetWarehouseListInfo(item, out List<WareHouseInfoModel> wareHouseInfoList, out string msg)
                    || wareHouseInfoList== null 
                    || wareHouseInfoList.Count == 0)
                {
                    ShowErrMsg($"PMS中没有库位配置：{item}");
                    return;
                }
            }

            if (!interfaceService.GetTaskDataList(out List<TaskDetailInfoModel> taskDetailInfoList, out string Message))
            {
                ShowErrMsg("获取当前任务列表失败");
                return;
            }
            
            ;
            int count = taskDetailInfoList
                .Where(d => 
                    {
                        foreach (var item in posArr)
                        {
                            if(d.AllWarehouse.Contains(item))
                            {
                                return true;
                            }
                        }
                        return false;
                    })
                .Count();

            if (count > 0)
            {
                ShowErrMsg("有正在执行的任务");
                return;
            }

            string text = $"确定要生成此任务？任务点：{upLocation}，任务簿：{taskTemplate}，父任务ID：{parentTaskId}";
            var dialogResult = MessageBox.Show(text, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            try
            {
                TaskAddInfoModel data = new TaskAddInfoModel();
                data.TaskID = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                data.TemplateName = taskTemplate;
                data.AgvId = 0;
                data.AgvType = "0";

                for (int i = 0; i < posArr.Length; i++)
                {
                    data.ParametersDic.Add($"U{i+1}", posArr[i]);
                }

                data.Priority = 0;
                data.ParentTaskId = parentTaskId;
                bool result = interfaceService.TaskAdd(data, out Message);
                CLog.Instance.GetLog("Task").WriteInfo($"{data.TaskID} {data.ParentTaskId} {data.TemplateName} {data.Parameters} 调试任务添加{result.ToChineseString()}");

                if (result)
                {
                    ShowMsg("添加任务成功");
                }
                else
                {
                    ShowErrMsg("添加任务失败");
                }
            }
            catch (Exception ex)
            {
                ShowErrMsg($"添加任务发生异常：{ex.Message}");
            }
        }

        private void ShowMsg(string text)
        {
            MessageBox.Show(text, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void ShowErrMsg(string text)
        {
            MessageBox.Show(text, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public void UpdateDisplay()
        {
        }

        private void 更新数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Init();
        }
    }
}
