using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DbCommon.Enties.DbModels;
using System.Drawing.Drawing2D;
using DbCommon.BusinessCore.BaseCore;
using ProjectManagementSystem.Common.Function;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.WebApi;
using Pms.DataLibrary.Order;
using ProjectManagementSystem.Common.Extenions;
using ProjectManagementSystem.Common.Service;

namespace ProjectManagementSystem.UI
{
    public partial class LocationUI : UserControl
    {
        private LocationPropertyManager locationPropertyManager;

        private Point m_point;
        public LocationProperty LocationProperty { get; set; }
        public bool Moveable { get; set; }
        public bool StationSelected { get; set; }

        public LocationUI()
        {
            InitializeComponent();
            this.button1.Click += Button1_Click;
            this.button1.MouseDown += Button1_MouseDown;
            this.button1.MouseMove += Button1_MouseMove;
            this.button1.MouseUp += Button1_MouseUp;
        }

        private void Button1_MouseUp(object sender, MouseEventArgs e)
        {
            if (Moveable
                && e.Button == MouseButtons.Left)
            {
                var buttonPropertyDict = ExcelConfig.Instance.ButtonPropertyDict;
                if (buttonPropertyDict.ContainsKey(LocationProperty.LocationCode))
                {
                    buttonPropertyDict[LocationProperty.LocationCode].LocationX = this.Location.X;
                    buttonPropertyDict[LocationProperty.LocationCode].LocationY = this.Location.Y;
                }
            }
        }

        private void Button1_MouseMove(object sender, MouseEventArgs e)
        {
            if (Moveable
                && e.Button == MouseButtons.Left)
            {
                int pos_x = this.Location.X + (e.X - m_point.X);
                int pos_y = this.Location.Y + (e.Y - m_point.Y);
                this.Location = new Point(pos_x, pos_y);
            }
        }

        private void Button1_MouseDown(object sender, MouseEventArgs e)
        {
            if (Moveable
                && e.Button == MouseButtons.Left)
            {
                m_point = e.Location;
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            this.OnClick(new EventArgs());

            ClickChangeStatus();
        }

        public void Display()
        {
            this.button1.Text = $"{ LocationProperty.LocationCode}{Environment.NewLine}{LocationProperty.MaterialId}";
            this.button1.BackColor = LocationProperty.Status.ToColor();

            //this.button1.ForeColor = StationSelected ? Color.Transparent : Color.Black;
            this.button1.FlatAppearance.BorderSize = StationSelected ? 2 : 0;
            //this.button1.FlatAppearance.BorderColor = StationSelected ? Color.Black : Color.DarkGray;
        }

        private void ClickChangeStatus()
        {
            if (!AppSetting.TryGetValue<bool>("StationClickChangeStatus"))
            {
                return;
            }

            LocationStatus status = LocationProperty.Status;
            switch (status)
            {
                case LocationStatus.Filled:
                    status = LocationStatus.Empty;
                    break;
                case LocationStatus.Empty:
                    status = LocationStatus.Filled;
                    break;
                case LocationStatus.Locked:
                    MessageBox.Show("状态为锁定，不能修改（需要强制修改请使用WMS）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                default:
                    return;
            }

            UpdateLocation(LocationProperty.LocationCode, d =>
            {
                d.Status = status;
            });
        }

        private bool LockedCheck()
        {
            if (this.LocationProperty.Status == LocationStatus.Locked)
            {
                var taskDataList = PmsApi.GetTaskList();
                if (taskDataList == null)
                {
                    MessageBox.Show("获取所有任务失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return true;
                }
                //var taskFind = taskDataList.FirstOrDefault(d => d.AllWarehouse.Contains(LocationProperty.LocationCode));
                //if(taskFind == null)
                //{
                //    return false;
                //}

                var result = PmsTaskService.Instance.LocationHasTask(LocationProperty.LocationCode);
                if (!result)
                {
                    return false;
                }

                string msg = string.Format("状态为锁定，不能修改（需要强制修改请使用WMS）");
                MessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return true;
            }
            return false;
        }

        private void UpdateLocation(string location, Action<LocationProperty> action)
        {
            if (LockedCheck()) return;

            string text = $"确定要修改状态？？？ {location}";
            var dialogResult = MessageBox.Show(text, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            if(locationPropertyManager == null)
            {
                locationPropertyManager = new LocationPropertyManager();
            }

            var locationData = locationPropertyManager.GetById(location);

            if(locationData != null)
            {
                action(locationData);
                var result = locationPropertyManager.Update(locationData);

                Common.Logger.CLog.Instance.TaskLog.WriteInfo($"修改库位状态{result.ToChineseString()}：{locationData.LocationCode}，状态：{locationData.Status}，物料：{locationData.MaterialId}");
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            UpdateLocation(LocationProperty.LocationCode, d =>
            {
                d.Status = LocationStatus.Filled;
                d.MaterialId = string.Empty;
            });
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            UpdateLocation(LocationProperty.LocationCode, d => 
            {
                d.Status = LocationStatus.Empty;
                d.MaterialId = string.Empty;
                d.BatchNumber = string.Empty;
            } );
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            UpdateLocation(LocationProperty.LocationCode, d =>
            {
                d.Status = LocationStatus.Locked;
            });
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            UpdateLocation(LocationProperty.LocationCode, d =>
            {
                d.Status = LocationStatus.Filled;
            });
        }

        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            using (Forms.FormSetting setting = new Forms.FormSetting())
            {
                setting.LocationProperty = this.LocationProperty;
                setting.Init();
                setting.UpdateDisplay();
                setting.ShowDialog();
            }
        }
    }
}
