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.Enties.DbModels;
using ProjectManagementSystem.Common.Function;
using DbCommon.BusinessCore.BaseCore;
using ProjectManagementSystem.Common.Config;
using ProjectManagementSystem.Common.Models;
using ProjectManagementSystem.Common.Logger;
using ProjectManagementSystem.Common.WebApi;
using ProjectManagementSystem.Common.Extenions;
using Pms.DataLibrary.Order;

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

        public bool Init()
        {
            areaUI1.OnLocationSelected += AreaUI1_OnLocationSelected;

            if (!areaUI1.Init()
                || !InitTaskUI())
            {
                return false;
            }

            return true;
        }

        public void UpdateDisplay()
        {
            areaUI1.UpdateDisplay();
        }

        private void AreaUI1_OnLocationSelected(object arg1, LocationProperty arg2)
        {
            UpdateUpMaterial(arg2);
        }

        public bool InitTaskUI()
        {
            try
            {
                locationManager = new LocationPropertyManager();
                wareHouseManager = new WareHouseManager();


                string filter = AppSetting.TryGetValue<string>("WareHouseFilter1");
                DataTable dt = null;
                if (string.IsNullOrEmpty(filter))
                {
                    dt = locationManager.QueryAreaDistinct();
                    //dt = wareHouseManager.QueryWareHouse();
                }
                else if (filter.Contains("|"))
                {
                    var filters = filter.Split(new char[] { '|' });
                    dt = locationManager.QueryAreaDistinct(filters);
                    //dt = wareHouseManager.QueryWareHouse(filters);
                }
                else
                {
                    //没有分割符时，使用模糊查询
                    dt = locationManager.QueryAreaDistinct(filter);
                    //dt = wareHouseManager.QueryWareHouse(filter);
                }

                if (dt == null)
                {
                    return false;
                }

                //this.comboBox1.ValueMember = "WareHouseCode";
                //this.comboBox1.DisplayMember = "WareHouseName";
                this.comboBox1.ValueMember = "Area";
                this.comboBox1.DisplayMember = "Area";
                this.comboBox1.DataSource = dt;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("连接数据库"))
                {
                    MessageBox.Show("连接数据库失败，请检查网络通讯！");
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }

                return false;
            }

            InitTaskButton();
            ClearLabText();
            return true;
        }

        private void InitTaskButton()
        {
            var taskButtonArray = AppSetting.TryGetValue<string>("TaskButton").ToValueArray<string>();

            foreach (var item in this.panel4.Controls)
            {
                var btn = item as Button;
                if (btn == null)
                {
                    continue;
                }

                btn.Visible = taskButtonArray.Contains(btn.Text) ? true : false;
            }
        }

        private void ClearLabText()
        {
            labUpArea.Text = string.Empty;
            labUpWareHouse.Text = string.Empty;
            labUpLocation.Text = string.Empty;
            labUpMaterial.Text = string.Empty;

            //labFilled.Text = string.Empty;
            //labEmpty.Text = string.Empty;
            //labLocked.Text = string.Empty;
            //labLineCall.Text = string.Empty;

            //labFilled.AutoSize = false;
            //labEmpty.AutoSize = false;
            //labLocked.AutoSize = false;
            //labLineCall.AutoSize = false;

            //labFilled.BackColor = ColorSetting.Instance.GetColor(LocationStatus.Filled);
            //labEmpty.BackColor = ColorSetting.Instance.GetColor(LocationStatus.Empty);
            //labLocked.BackColor = ColorSetting.Instance.GetColor(LocationStatus.Locked);
            //labLineCall.BackColor = ColorSetting.Instance.GetColor(LocationStatus.LineCall);
        }

        public void UpdateUpMaterial(LocationProperty row)
        {
            labUpArea.Text = row.Area;
            labUpWareHouse.Text = row.WareHouseCode;
            labUpLocation.Text = row.LocationCode;
            labUpMaterial.Text = row.MaterialId;
        }


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

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            areaUI1.CurrentWareHouseCode = comboBox1.SelectedValue.ToString();
        }

        private LocationProperty GetCheckLocation(bool checkLocked = true)
        {
            string location = labUpLocation.Text;
            if (string.IsNullOrEmpty(location))
            {
                ShowErrMsg("叫料点检查异常");
                return null;
            }

            var ulocationData = locationManager.GetById(location);
            if (ulocationData == null)
            {
                ShowErrMsg("查询叫料点库位数据失败");
                return null;
            }

            if (checkLocked
                && ulocationData.Status == LocationStatus.Locked)
            {
                ShowErrMsg("叫料点库位已锁定");
                return null;
            }

            return ulocationData;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var locationData = GetCheckLocation();
            if (locationData == null) return;

            var wData = wareHouseManager.GetById(locationData.WareHouseCode);
            if (string.IsNullOrEmpty(wData?.SourceWareHouseCode))
            {
                ShowErrMsg("该位置不能叫料");
                return;
            }

            using (Forms.FormPmsTaskInfo setting = new Forms.FormPmsTaskInfo())
            {
                setting.Init(sender, locationData);
                setting.ShowDialog();
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            var locationData = GetCheckLocation();
            if (locationData == null) return;

            var wData = wareHouseManager.GetById(locationData.WareHouseCode);
            if (string.IsNullOrEmpty(wData?.TargetWareHouseCode))
            {
                ShowErrMsg("该位置不能转运");
                return;
            }

            using (Forms.FormPmsTaskInfo setting = new Forms.FormPmsTaskInfo())
            {
                setting.Init(sender, locationData);
                setting.ShowDialog();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var locationData = GetCheckLocation(false);
            if (locationData == null) return;

            var wData = wareHouseManager.GetById(locationData.WareHouseCode);
            if (string.IsNullOrEmpty(wData?.SourceWareHouseCode))
            {
                ShowErrMsg("该位置不能叫料");
                return;
            }

            using (Forms.FormPmsTaskInfo setting = new Forms.FormPmsTaskInfo())
            {
                setting.Init(sender, locationData);
                setting.ShowDialog();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var locationData = GetCheckLocation(false);
            if (locationData == null) return;

            var wData = wareHouseManager.GetById(locationData.WareHouseCode);
            if (string.IsNullOrEmpty(wData?.TargetWareHouseCode))
            {
                ShowErrMsg("该位置不能转运");
                return;
            }

            using (Forms.FormPmsTaskInfo setting = new Forms.FormPmsTaskInfo())
            {
                setting.Init(sender, locationData);
                setting.ShowDialog();
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            var locationData = GetCheckLocation(false);
            if (locationData == null) return;

            try
            {

                string text = $"确定要手动放行AGV？ 库位：{locationData.LocationCode}";
                var dialogResult = MessageBox.Show(text, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (dialogResult != DialogResult.OK)
                {
                    return;
                }

                var result = PmsApi.CustomApiPost("ReleaseAgv", null, new { LocationCode = locationData.LocationCode });
                if (result?.code == 20000)
                {
                    ShowMsg($"操作成功，{result?.message}");
                }
                else
                {
                    ShowErrMsg($"操作失败，{result?.message}");
                }
            }
            catch (Exception ex)
            {
                ShowErrMsg($"操作异常:{ex.Message}");
            }
        }
    }
}
