using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using WCS.BLL;
using WCS.BLL.DbModels;
using WCS.BLL.HardWare;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
using WCS.BLL.Services.Service;
using WCS.DAL.Db;
using WCS.DAL.DbModels;
using WCS.Model;
using WCS.Model.ApiModel.AGV;
using WCS.Model.ApiModel.Home;
using WCS.Model.ApiModel.StoreInfo;
using Mode = WCS.BLL.HardWare.Mode;

namespace WCS.WebApi.Controllers
{
    /// <summary>
    /// 主页面的接口
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class AgvTaskController : ControllerBase
    {
        public IPDAMatBindService _PDAMatBindService { get; set; }
        public AgvTaskController(IPDAMatBindService PDAMatBindService)
        {
            _PDAMatBindService = PDAMatBindService;
        }

        [Route("getAGVTaskStatus")]
        [HttpPost(Name = "getAGVTaskStatus")]
        public async Task<ResponseCommon> getAGVTaskStatus(RequestBase request)
        {
            try
            {
                var status = new List<GetAGVTasksResponseData>();
                status.Add(new GetAGVTasksResponseData{Id = null,TaskStatusName="全部" });
                var statusesInDb = Enum.GetValues(typeof(TaskStatusEnum))
                                  .Cast<TaskStatusEnum>()
                                  .ToList();
                statusesInDb.ForEach(t => status.Add(new GetAGVTasksResponseData{ Id = (int)t,TaskStatusName = t.ToString()}));
                return new ResponseCommon
                { 
                    Code=200,
                    Data = status,
                    Message = "success"
                };
            }
            catch (Exception ex)
            {
                return new ResponseCommon
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }
        public class GetAGVTasksResponseData
        {
            public int? Id { get; set; }
            public string TaskStatusName { get; set; }
        }

        /// <summary>
        /// 获取AGV任务列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("getAGVTasks")]
        [HttpPost(Name = "getAGVTasks")]
        public async Task<PageQueryResponse<AgvTask>> getAGVTasks(GetAGVTasksRequest request)
        {
            try
            {
                if (request.TaskStatus == TaskStatusEnum.正在执行)
                {
                    AGVManager.RefreshAgvStatus();
                }

                var recordsQueryable = DbHelp.db.Queryable<AgvTask>()
                                                .WhereIF(string.IsNullOrEmpty(request.ShelfCode), t => t.ShelfCode.Contains(request.ShelfCode))
                                                .WhereIF(string.IsNullOrEmpty(request.CreateUser), t => t.CreateUser.Contains(request.CreateUser))
                                                .WhereIF(string.IsNullOrEmpty(request.StartLocationCode), t => t.StartLocationCode.Contains(request.StartLocationCode))
                                                .WhereIF(string.IsNullOrEmpty(request.EndLocationCode), t => t.StartLocationCode.Contains(request.EndLocationCode))
                                                .WhereIF(request.TaskStatus != null, t => t.TaskStatus == request.TaskStatus);

                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .OrderByDescending(t => t.CreateTime)
                                    .Skip((request.PageNumber - 1) * request.PageSize).Take(request.PageSize)
                                    .ToListAsync();
                //生成序号
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].RowNumber = (request.PageNumber - 1) * request.PageSize + i + 1;
                }
                return new PageQueryResponse<AgvTask>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<AgvTask>()
                    {
                        TotalCount = totalCount,
                        MaxPage = request.PageSize == 0 ? 0 : (int)Math.Ceiling((decimal)totalCount / request.PageSize),
                        Count = records.Count,
                        Lists = records.ToList()
                    }
                };
            }
            catch (Exception ex)
            {
                return new PageQueryResponse<AgvTask>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("cancelAGVTask")]
        [HttpPost(Name = "cancelAGVTask")]
        public async Task<ResponseBase> cancelAGVTask(CancelAGVTasksRequest 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}】,无法取消！",
                    };
                }
                #endregion

                #region 调用RCS进行取消任务
                var response = AGVManager.CancelTask(agvTask);
                if (response.code == "0" && response.message == "成功")
                {
                    return new ResponseCommon()
                    {
                        Code = 200,
                        Message = $"success",
                    };
                }
                else
                {
                    return new ResponseCommon()
                    {
                        Code = 201,
                        Message = response.message,
                    };
                }
                #endregion
            }
            catch (Exception ex)
            {
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"任务取消失败:{ex.Message}",
                };
            }
        }

        /// <summary>
        /// 重新发送任务
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("resendAGVTask")]
        [HttpPost(Name = "resendAGVTask")]
        public async Task<ResponseBase> resendAGVTask(ResendAGVTasksRequest request)
        {
            try
            {
                return await _PDAMatBindService.resendAGVTask(request);
            }
            catch (Exception ex)
            {
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"任务重新发送失败:{ex.Message}",
                };
            }
        }
    }
}
