using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS.BLL.DbModels;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
using WCS.DAL.Db;
using WCS.DAL.DbModels;
using WCS.Model;
using WCS.Model.ApiModel.AGV;
using WCS.Model.ApiModel.PDAMatBind;

namespace WCS.BLL.Services.Service
{
    public class PDAMatBindService : IPDAMatBindService
    {
        public async Task<ResponseCommon> callEmptyShelf(BindMatDetailRequest request)
        {
            try
            {
                #region 参数校验
                //判断参数
                if (request.LocationId == 0 || string.IsNullOrEmpty(request.LocationCode))
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = "工位或工位编码为空！\r\n请重新扫工位码",
                        Data = null,
                    };
                }
                #endregion

                #region 数据校验
                //获取是否存在当前工位
                var endLocation = await DbHelp.db.Queryable<LocationInfo>()
                                              .Where(t => t.Id == request.LocationId)
                                              .Where(t => t.IsEnable == true)
                                              .FirstAsync();
                if (endLocation == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"工位[{request.LocationCode}]不存在或已被禁用!\r\n请联系系统管理人员维护工位信息！",
                        Data = null,
                    };
                }

                //获取当前工位的货架
                var shelf = await DbHelp.db.Queryable<ShelfInfo>()
                                           .Where(t => (t.CurrentLocationId == endLocation.Id)
                                                     || (t.DestinationLocationId == endLocation.Id && t.TransStatus == TransStatusEnum.运输中))//解决产线人员 呼叫后货架未到的时候绑定的问题
                                           .Where(t => t.IsEnable == true)
                                           .FirstAsync();
                if (shelf != null)
                {
                    if (shelf.TransStatus == TransStatusEnum.静止)
                    {
                        return new ResponseCommon()
                        {
                            Code = 205,
                            Message = $"货架【{shelf.ShelfCode}】在工位上，无法呼叫新货架！",
                            Data = null,
                        };
                    }
                    //运输中
                    else if(shelf.TransStatus == TransStatusEnum.运输中 && shelf.DestinationLocationId == endLocation.Id)
                    {
                        return new ResponseCommon()
                        {
                            Code = 205,
                            Message = $"货架【{shelf.ShelfCode}】运输中，请勿重复呼叫！\r\n货架到达后扫货架码即可继续绑定。",
                            Data = null,
                        };
                    }
                    else if (shelf.TransStatus == TransStatusEnum.运输中 && shelf.CurrentLocationId == endLocation.Id)
                    {
                        return new ResponseCommon()
                        {
                            Code = 205,
                            Message = $"当前货架【{shelf.ShelfCode}】未从工位拉走！\r\n等待拉走后进行绑定!",
                            Data = null,
                        };
                    }
                }
                #endregion

                //获取空货架进行呼叫
                shelf = await DbHelp.db.Queryable<ShelfInfo>()
                                           .Where(t => t.TransStatus == TransStatusEnum.静止 && t.CurrentLocationId != 0)
                                           .Where(t => t.ShelfStatus == ShelfStatusEnum.空货架)
                                           .Where(t => t.ShelfTypeId == request.NeedShelfTypeId)
                                           .Where(t => t.IsEnable == true)
                                           .FirstAsync();
                if (shelf == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"货架类型[{request.NeedShelfTypeName}]，不存在空货架！",
                        Data = null,
                    };
                }

                var startLocation = await DbHelp.db.Queryable<LocationInfo>()
                                           .Where(t => t.Id == shelf.CurrentLocationId)
                                           .Where(t => t.IsEnable == true)
                                           .FirstAsync();

                var response = AGVManager.GenAgvSchedulingTask(startLocation, endLocation, shelf.ShelfCode, request.UserName);
                if (response.code == "0" && response.message == "成功")
                {
                    //更新货架位置信息
                    shelf.TransStatus = TransStatusEnum.运输中;
                    shelf.CurrentTaskCode = response.data;
                    shelf.DestinationLocationId = endLocation.Id;
                    shelf.DestinationLocaiotnCode = endLocation.LocationCode;
                    DbHelp.db.Updateable(shelf).ExecuteCommand();

                    return new ResponseCommon()
                    {
                        Code = 200,
                        Message = "success",
                        Data = null,
                    };
                }
                else if (response.code == "-999")
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"{response.message}\r\n请重试或等待上一个任务完成",
                        Data = null,
                    };
                }
                else
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"海康RCS返回：{response.message}",
                        Data = null,
                    };
                }

            }
            catch (Exception ex)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = ex.Message,
                    Data = null,
                };
            }
        }


        public async Task<ResponseCommon> bindSendBackShelf(BindMatDetailRequest request)
        {
            try
            {
                #region 参数校验
                //判断参数
                if (request.LocationId == 0 || string.IsNullOrEmpty(request.LocationCode))
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = "工位或工位编码为空！\r\n请重新扫码",
                        Data = null,
                    };
                }
                #endregion

                #region 数据校验
                //获取是否存在当前工位
                var startLocation = await DbHelp.db.Queryable<LocationInfo>()
                                              .Where(t => t.Id == request.LocationId)
                                              .Where(t => t.IsEnable == true)
                                              .FirstAsync();
                if (startLocation == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"工位[{request.LocationCode}]不存在或已被禁用!\r\n请联系系统管理人员维护工位信息！",
                        Data = null,
                    };
                }

                //获取当前工位的货架
                var shelf = await DbHelp.db.Queryable<ShelfInfo>()
                                           .Where(t => t.CurrentLocationId == startLocation.Id && t.TransStatus == TransStatusEnum.静止)
                                           .Where(t => t.IsEnable == true)
                                           .FirstAsync();
                if (shelf == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"当前工位上不存在货架【{request.ShelfCode}】,请确认！",
                        Data = null,
                    };
                }
                #endregion

                var endLocation = await DbHelp.db.Queryable<LocationInfo>()
                                                 .LeftJoin<ShelfInfo>((li,si) => (li.Id == si.CurrentLocationId && si.TransStatus == TransStatusEnum.静止) || (li.Id == si.DestinationLocationId && si.TransStatus == TransStatusEnum.运输中))
                                                 .Where((li, si) => li.LocationAreaId == request.SendBackLocationAreaId)
                                                 .Where((li, si) => li.IsEnable == true)
                                                 .Where((li, si) => li.Id != shelf.CurrentLocationId)
                                                 .Where((li, si) => si.Id == null)
                                                 .Select((li, si) => li)
                                                 .FirstAsync();
                if (endLocation == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"区域[{request.SendBackLocationAreaName}]不存在空闲位置！",
                        Data = null,
                    };
                }

                var response = AGVManager.GenAgvSchedulingTask(startLocation, endLocation, shelf.ShelfCode, request.UserName);
                if (response.code == "0" && response.message == "成功")
                {
                    //更新货架位置信息
                    shelf.TransStatus = TransStatusEnum.运输中;
                    shelf.CurrentTaskCode = response.data;
                    shelf.DestinationLocationId = endLocation.Id;
                    shelf.DestinationLocaiotnCode = endLocation.LocationCode;
                    DbHelp.db.Updateable(shelf).ExecuteCommand();

                    return new ResponseCommon()
                    {
                        Code = 200,
                        Message = "success",
                        Data = null,
                    };
                }
                else if (response.code == "-999")
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"{response.message}\r\n请重试或等待上一个任务完成",
                        Data = null,
                    };
                }
                else
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"海康RCS返回：{response.message}",
                        Data = null,
                    };
                }

            }
            catch (Exception ex)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = ex.Message,
                    Data = null,
                };
            }
        }

        public async Task<ResponseBase> resendAGVTask(ResendAGVTasksRequest request)
        {
            try
            {
                #region 参数、数据校验
                if (request.TaskId == 0 || string.IsNullOrEmpty(request.TaskCode))
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"传入参数错误！",
                    };
                }

                var agvTask = await DbHelp.db.Queryable<AgvTask>()
                                             .Where(t => t.Id == request.TaskId)
                                             .Where(t => t.TaskCode == request.TaskCode)
                                             .FirstAsync();
                if (agvTask == null)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"任务[{agvTask.TaskCode}]不存在！",
                    };
                }

                if (agvTask.TaskStatus != TaskStatusEnum.取消完成)
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"任务[{agvTask.TaskCode}]状态为【{agvTask.TaskStatus}】,无法重新发送！",
                    };
                }

                if (agvTask.ModifyTime < DateTime.Now.AddMinutes(-10))
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"任务取消已超过10分钟,无法重新发送！",
                    };
                }
                #endregion

                #region 起点终点等现有数据校验
                var startLocation = await DbHelp.db.Queryable<LocationInfo>()
                                                   .Where(t => t.Id == agvTask.StratLocationId)
                                                   .Where(t => t.IsEnable == true)
                                                   .FirstAsync();
                if (startLocation == null)
                {
                    return new ResponseBase()
                    {
                        Code = 201,
                        Message = "任务重新发送失败：起点位置不存在或已被禁用！",
                    };
                }

                var endLocation = await DbHelp.db.Queryable<LocationInfo>()
                                                  .Where(t => t.Id == agvTask.EndLocationId)
                                                  .Where(t => t.IsEnable == true)
                                                  .FirstAsync();
                if (endLocation == null)
                {
                    return new ResponseBase()
                    {
                        Code = 201,
                        Message = "任务重新发送失败：终点位置不存在或已被禁用！",
                    };
                }
                //货架
                var shelf = await DbHelp.db.Queryable<ShelfInfo>()
                                                   .Where(t => t.ShelfCode == agvTask.ShelfCode)
                                                   .Where(t => t.IsEnable == true)
                                                   .FirstAsync();
                if (shelf == null)
                {
                    return new ResponseBase()
                    {
                        Code = 201,
                        Message = $"任务重新发送失败：货架{agvTask.ShelfCode}不存在或已被禁用！",
                    };
                }
                if (shelf.TransStatus != TransStatusEnum.静止 || shelf.CurrentLocationId != agvTask.StratLocationId)
                {
                    return new ResponseBase()
                    {
                        Code = 201,
                        Message = $"任务重新发送失败：货架{agvTask.ShelfCode}已不在起点位置{startLocation.LocationCode}！",
                    };
                }
                //查询终点位置是否有货架占用
                var otherShelf = await DbHelp.db.Queryable<ShelfInfo>()
                                                   .Where(t => (t.CurrentLocationId == endLocation.Id && t.TransStatus == TransStatusEnum.静止)
                                                   || (t.DestinationLocationId == endLocation.Id && t.TransStatus == TransStatusEnum.运输中))
                                                   .Where(t => t.IsEnable == true)
                                                   .FirstAsync();
                if (otherShelf != null)
                {
                    return new ResponseBase()
                    {
                        Code = 201,
                        Message = $"任务重新发送失败：终点位置已被其他货架占用！",
                    };
                }
                #endregion

                #region 调用RCS进行重新发送任务
                var response = AGVManager.GenAgvSchedulingTaskForResend(startLocation, endLocation, agvTask, shelf.ShelfCode, request.UserName);
                if (response.code == "0" && response.message == "成功")
                {
                    //更新货架位置信息
                    shelf.TransStatus = TransStatusEnum.运输中;
                    shelf.CurrentTaskCode = response.data;
                    shelf.DestinationLocationId = endLocation.Id;
                    shelf.DestinationLocaiotnCode = endLocation.LocationCode;
                    DbHelp.db.Updateable(shelf).ExecuteCommand();

                    return new ResponseCommon()
                    {
                        Code = 200,
                        Message = "success",
                        Data = null,
                    };
                }
                else if (response.code == "-999")
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"任务重新发送失败：{response.message}\r\n请重试或等待上一个任务完成",
                        Data = null,
                    };
                }
                else
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = $"任务重新发送失败，海康RCS返回：{response.message}",
                        Data = null,
                    };
                }
                #endregion
            }
            catch (Exception ex)
            {
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"任务重新发送失败:{ex.Message}",
                };
            }
        }
    }
}
