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 ProjectManagementSystem.Common.Logger;
using ProjectManagementSystem.Common.WebApi;
using Pms.DataLibrary.Models;
using ProjectManagementSystem.Common.Models;
using Pms.DataLibrary.Order;
using ProjectManagementSystem.Common.Extenions;

namespace ProjectManagementSystem.UI
{
    public partial class DebugUI : UserControl, IDisplayUI
    {
        private WareHouseManager wareHouseManager = new WareHouseManager();
        private LocationPropertyManager locationManager = new LocationPropertyManager();
        public DebugUI()
        {
            InitializeComponent();
        }

        public bool Init()
        {
            return true;
        }

        private bool InitUI()
        {
            var taskBookInfoList = PmsApi.GetTaskBookList();
            if (taskBookInfoList == null)
            {
                CLog.Instance.SystemLog.WriteWarn("获取任务模板失败，请检查AGVS系统是否启动！！！");
            }
            cmbTaskTemplate.DataSource = taskBookInfoList?.Select(d => d.Name).ToList();

            var wareHouseInfoList = PmsApi.GetWarehouseListInfo(string.Empty);
            if (wareHouseInfoList != null)
            {
                cmbLocationCode1.DataSource = wareHouseInfoList.Select(d => d.WareHouseID).ToList();
                cmbLocationCode2.DataSource = wareHouseInfoList.Select(d => d.WareHouseID).ToList();
            }

            var taskDataList = PmsApi.GetTaskList();
            if (taskDataList != null)
            {
                cmbParentTaskId.DataSource = taskDataList.Select(d => d.TaskID).ToList();
            }

            DataTable dt = wareHouseManager.QueryWareHouse();
            if (dt != null
                && dt.Rows.Count > 0)
            {
                this.cmbWareHouseCode.ValueMember = "WareHouseCode";
                this.cmbWareHouseCode.DisplayMember = "WareHouseName";
                this.cmbWareHouseCode.DataSource = dt;
            }

            dt = wareHouseManager.QueryWareHouse();
            if (dt != null
                && dt.Rows.Count > 0)
            {
                this.cmbTargetWareHouseCode.ValueMember = "WareHouseCode";
                this.cmbTargetWareHouseCode.DisplayMember = "WareHouseName";
                this.cmbTargetWareHouseCode.DataSource = dt;
            }

            return true;
        }

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

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

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

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

            string[] posArr = ($"{upLocation},{downLocation}").ToValueArray<string>();
            if (posArr == null
                || posArr.Length == 0)
            {
                ShowErrMsg("任务点转换失败");
                return;
            }

            foreach (var item in posArr)
            {
                var wareHouseInfoList = PmsApi.GetWarehouseListInfo(item);
                if (wareHouseInfoList == null
                    || wareHouseInfoList.Count == 0)
                {
                    ShowErrMsg($"PMS中没有库位配置：{item}");
                    return;
                }
            }

            var taskDataList = PmsApi.GetTaskList();
            if (taskDataList == null)
            {
                ShowErrMsg("获取当前任务列表失败");
                return;
            }

            ;
            int count = taskDataList
                .Where(d =>
                    {
                        foreach (var item in posArr)
                        {
                            if (d.AllWarehouse.Contains(item))
                            {
                                return true;
                            }
                        }
                        return false;
                    })
                .Count();

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

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

            try
            {
                MidTaskInfoEx data = new MidTaskInfoEx();
                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 = PmsApi.TaskAdd(data);
                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)
        {
            InitUI();
        }

        private void cmbWareHouseCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cmb = sender as ComboBox;
            if (cmb == null)
            {
                return;
            }

            string wHouse = cmb.SelectedValue.ToString();
            var nameList = locationManager.QueryDataList(wHouse)?.Select(d => d.LocationCode).ToList();
            nameList.Add(string.Empty);
            cmbLocationCode.DataSource = nameList;

            cmbLocationCode.SelectedIndex = cmbLocationCode.Items.Count - 1;
        }

        private void cmbTargetWareHouseCode_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cmb = sender as ComboBox;
            if (cmb == null)
            {
                return;
            }

            string wHouse = cmb.SelectedValue.ToString();
            var nameList = locationManager.QueryDataList(wHouse)?.Select(d => d.LocationCode).ToList();
            nameList.Add(string.Empty);
            cmbTargetLocationCode.DataSource = nameList;

            cmbTargetLocationCode.SelectedIndex = cmbTargetLocationCode.Items.Count - 1;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                PmsTaskInfo data = new PmsTaskInfo();
                data.WareHouseCode = cmbWareHouseCode.SelectedValue.ToString();
                data.LocationCode = cmbLocationCode.Text;
                data.TargetWareHouseCode = cmbTargetWareHouseCode.SelectedValue.ToString();
                data.TargetLocationCode = cmbTargetLocationCode.Text;
                data.MaterialId = textBoxMaterialID.Text;

                var result = PmsApi.CustomApiPost("TaskAdd", null, data);
                if (result?.code == 20000)
                {
                    ShowMsg("添加任务成功");
                }
                else
                {
                    ShowErrMsg($"添加任务失败，{result?.message}");
                }
            }
            catch (Exception ex)
            {
                ShowErrMsg($"添加任务发生异常：{ex.Message}");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
        }
    }
}
