using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto.taskType;
using SlnMesnac.WPF.Library;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TouchSocket.Core;
using static MaterialDesignThemes.Wpf.Theme.ToolBar;

namespace SlnMesnac.WPF.Page
{
    /// <summary>
    /// CreateMoveWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CreateMoveWindow : Window
    {
        private ISqlSugarClient? SqlSugarClient;

        public CreateMoveWindow()
        {
            InitializeComponent();
            SqlSugarClient = App.ServiceProvider.GetService<ISqlSugarClient>();
            LoadLocations();  // 初始化 ComboBox 选项
        }

        // 加载地点选项（3001-3024）
        private void LoadLocations()
        {
            for (int i = 301; i <= 312; i++)
            {
                this.StartComboBox.Items.Add(i.ToString()+"A");
                this.StartComboBox.Items.Add(i.ToString() + "B");
                EndComboBox.Items.Add(i.ToString()+"A");
                EndComboBox.Items.Add(i.ToString() + "B");
            }
            StartComboBox.Items.Add("异常库位3066");
            EndComboBox.Items.Add("异常库位3066");
        }

        // 确认按钮点击事件
        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            string startCode = StartComboBox.SelectedItem?.ToString();
            string endCode = EndComboBox.SelectedItem?.ToString();

            if(SqlSugarClient == null)
            {
                MessageBox.Show("SqlSugarClient为空！");
                return;
            }

            if (string.IsNullOrEmpty(startCode) || string.IsNullOrEmpty(endCode))
            {
                MessageBox.Show("请选择起点和终点！");
                return;
            }
            if (startCode == endCode)
            {
                MessageBox.Show("起点和终点不能相同！");
                return;
            }

            if (startCode == "异常库位3066")
            {
                startCode = "3066";
            }
            if (endCode == "异常库位3066")
            {
                endCode = "3066";
            }

            WmsBaseLocation? startLocation = SqlSugarClient.Queryable<WmsBaseLocation>().Where(it => it.LocationCode == startCode).First();
            WmsBaseLocation? endLocation = SqlSugarClient.Queryable<WmsBaseLocation>().Where(it => it.LocationCode == endCode).First();
            WmsPalletInfo? wmsPalletInfo = SqlSugarClient.Queryable<WmsPalletInfo>().InnerJoin<WmsBaseLocation>((x,y) => x.Amount == 0 && y.LocationCode == startCode).First();

            if (wmsPalletInfo == null) {
                MessageBox.Show("起点库位托盘未清空,无法移库！");
                return;
            }

            if (startLocation.LocationStatus != 0)
            {
                MessageBox.Show("起点库位不可用,状态被锁定！");
                return;
            }
            
            if (endLocation.LocationStatus != 0)
            {
                MessageBox.Show("终点库位不可用,状态被锁定！");
                return;
            }
            
            if (string.IsNullOrEmpty(startLocation.ContainerCode))
            {
                MessageBox.Show("起点库位无托盘，请检查库存！");
                return;
            }
            
            if (!string.IsNullOrEmpty(endLocation.ContainerCode))
            {
                MessageBox.Show($"终点库位已有托盘:{endLocation.ContainerCode}，禁止移库，请检查库存！");
                return;
            }

            try
            {
                WcsTask task = new WcsTask();
                task.TaskType = StaticTaskType.MoveLocationTask;
                task.CurrPointNo = startLocation.AgvPositionCode;
                task.EndPointNo = endLocation.AgvPositionCode;
                task.TaskStatus = 0;
                task.CreatedTime = DateTime.Now;
                task.CreatedBy = "wcs";
                task.TaskName = "1-12机台移库任务";
                task.PalletInfoCode = startLocation.ContainerCode;
                SqlSugarClient.AsTenant().BeginTran();
                int id = SqlSugarClient.Insertable(task).ExecuteReturnIdentity();
                WcsTaskLog wcsTaskLog = CoreMapper.Map<WcsTaskLog>(task);
                wcsTaskLog.Id = id;
                //锁定库位
                startLocation.LocationStatus = 1;
                endLocation.LocationStatus = 1;
                SqlSugarClient.Updateable(startLocation).ExecuteCommand();
                SqlSugarClient.Updateable(endLocation).ExecuteCommand();
                SqlSugarClient.Insertable(wcsTaskLog).ExecuteCommand();
                SqlSugarClient.AsTenant().CommitTran();
                MessageBox.Show($"生成{task.TaskName},起点:{task.CurrPointNo},终点:{task.EndPointNo}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成移库任务提交事务异常:{ex.Message}");
                SqlSugarClient.AsTenant().RollbackTran();
            }
            this.Close();
        }
    }
}