using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TouchSocket.Core;
using WCS.BLL.Config;
using WCS.BLL.DbModels;
using WCS.BLL.HardWare;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
using WCS.DAL;
using WCS.DAL.Db;
using WCS.DAL.DbModels;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.InOutRecord;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.StoreInfo;
using WCS.Model.ApiModel.User;

namespace WCS.BLL.Services.Service
{
    public class StoreInfoService : IStoreInfoService
    {

        public async Task<PageQueryResponse<ShelfInfo>> GetShelves(GetShelvesRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<ShelfInfo>()
                                                .WhereIF(request.ShelfTypeId != null, t => t.ShelfTypeId == request.ShelfTypeId)
                                                .WhereIF(request.IsEnable != null, t => t.IsEnable == request.IsEnable)
                                                .WhereIF(!string.IsNullOrEmpty(request.ShelfCode), t => t.ShelfCode.Contains(request.ShelfCode));

                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .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<ShelfInfo>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<ShelfInfo>()
                    {
                        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<ShelfInfo>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<PageQueryResponse<ShelfInfo>> ExportShelves(GetShelvesRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<ShelfInfo>()
                                                .WhereIF(request.ShelfTypeId != null, t => t.ShelfTypeId == request.ShelfTypeId)
                                                .WhereIF(request.IsEnable != null, t => t.IsEnable == request.IsEnable)
                                                .WhereIF(!string.IsNullOrEmpty(request.ShelfCode), t => t.ShelfCode.Contains(request.ShelfCode));

                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .Take(65535)
                                    .ToListAsync();
                //生成序号
                var index = 1;
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].RowNumber = index++;
                }
                return new PageQueryResponse<ShelfInfo>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<ShelfInfo>()
                    {
                        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<ShelfInfo>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<ResponseCommon<object>> addOrUpdateShelfInfo(AddShelfInfoRequest<ShelfInfo> request)
        {
            try
            {
                var shelfnfo = await DbHelp.db.Queryable<ShelfInfo>()
                                    .Where(t => t.ShelfCode == request.ShelfInfo.ShelfCode)
                                    .FirstAsync();
                //修改货架信息
                if (request.AddOrUpdate == AddOrUpdate.Update)
                {
                    var existId = shelfnfo == null ? 0 : shelfnfo.Id;

                    shelfnfo = await DbHelp.db.Queryable<ShelfInfo>()
                   .Where(t => t.Id == request.ShelfInfo.Id)
                   .FirstAsync();
                    if (shelfnfo == null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"更新货架信息失败：该货架不存在！",
                            Data = null
                        };
                    }
                    else if (existId != 0 && existId != shelfnfo.Id)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"更新货架信息失败：货架[{shelfnfo.ShelfCode}]已存在!！",
                            Data = null
                        };
                    }
                    else
                    {
                        request.ShelfInfo.ModifyUser = request.UserName;
                        request.ShelfInfo.ModifyTime = DateTime.Now;

                        var rowNum = await DbHelp.db.Updateable(request.ShelfInfo).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"更新货架信息失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"更新货架信息成功！",
                                Data = null
                            };
                        }
                    }
                }
                else if (request.AddOrUpdate == AddOrUpdate.Add)
                {
                    if (shelfnfo != null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"货架信息失败：货架[{shelfnfo.ShelfCode}]已存在!",
                            Data = null
                        };
                    }
                    else
                    {
                        request.ShelfInfo.ModifyUser = request.UserName;
                        var rowNum = await DbHelp.db.Insertable(request.ShelfInfo).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"添加货架信息失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"添加货架信息成功！",
                                Data = null
                            };
                        }
                    }
                }
                else if (request.AddOrUpdate == AddOrUpdate.Delete)
                {
                    shelfnfo = await DbHelp.db.Queryable<ShelfInfo>()
                                              .Where(t => t.Id == request.ShelfInfo.Id)
                                              .FirstAsync();
                    if (shelfnfo == null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"删除货架信息失败：货架{request.ShelfInfo}不存在！",
                            Data = null
                        };
                    }
                    else
                    {
                        var rowNum = await DbHelp.db.Deleteable(shelfnfo).ExecuteCommandAsync();
                        if (rowNum == 0)
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 201,
                                Message = $"删除货架信息失败：请重试！",
                                Data = null
                            };
                        }
                        else
                        {
                            return new ResponseCommon<Object>
                            {
                                Code = 200,
                                Message = $"删除货架信息成功！",
                                Data = null
                            };
                        }
                    }
                }
                else
                {
                    var response = new ResponseCommon<Object>
                    {
                        Code = 300,
                        Message = "不支持的操作！",
                        Data = null
                    };
                    return response;
                }
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }

        public async Task<ResponseCommon<object>> deleteShelfInfo(DeleteInfosRequest request)
        {
            //先查询出具体的Id
            var shelfInfos = await DbHelp.db.Queryable<ShelfInfo>()
                    .Where(t => request.needDeleteIds.Contains(t.Id))
                    .ToListAsync();
            //执行删除
            try
            {
                var deleteRows = await DbHelp.db.Deleteable(shelfInfos).ExecuteCommandAsync();
                return new ResponseCommon<Object>
                {
                    Code = 200,
                    Message = $"已删除{deleteRows}条数据！",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }

        #region 模组管理
        /// <summary>
        /// 发送指令获取模组的电压值
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>


        #endregion

        #region 库位管理
        public async Task<PageQueryResponse<StoreInfo>> GetStores(GetStoresRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<StoreInfo>()
                                                .WhereIF(!string.IsNullOrEmpty(request.ShelfCode), t => t.ShelfCode.Contains(request.ShelfCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.ModuleCode), t => t.ModuleCode.Contains(request.ModuleCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.StoreCode), t => t.StoreCode.Contains(request.StoreCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.CurrentMatSN), t => t.CurrentMatSn.Contains(request.CurrentMatSN))
                                                ;
                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .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<StoreInfo>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<StoreInfo>()
                    {
                        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<StoreInfo>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<ResponseCommon> disableOrEnableStore(DisableOrEnableStoreRequest request)
        {
            //找到库位
            var storeInfo = await DbHelp.db.Queryable<StoreInfo>()
                                      .Where(t => t.Id == request.StoreId)
                                      .FirstAsync();
            //库位不存在
            if (storeInfo == null)
            {
                return new ResponseCommon()
                {
                    Code = 201,
                    Message = $"操作失败：库位{request.SroreCode}不存在！"
                };
            }
            try
            {
                DbHelp.db.BeginTran();
                //禁用需要删除当前库存数据
                if (request.DisableOrEnable == DisableOrEnableEnum.Disable)
                {

                    //盟讯公司发送钉钉消息
                    if (LocalFile.Config.IsMx)
                    {
                        var DingDing = string.Empty;
                        MXBackgroundThread.SendDingDingMsg($"【智能货架】库位{storeInfo.StoreCode}被屏蔽（库位管理），请及时调查或维保硬件！", new List<string> { "104379", "103595" }, ref DingDing);
                        Logs.Write($"【智能货架】库位{storeInfo.StoreCode}被屏蔽（库位管理），请及时调查或维保硬件！");

                    }

                    //库位
                    storeInfo.CurrentMatSn = "禁用";
                    //库存数据处理
                    var inventorys = DbHelp.db.Queryable<InventoryDetail>()
                                                   .Where(t => t.StoreId == storeInfo.Id)
                                                   .ToList();
                    if (inventorys != null && inventorys.Count > 0)
                    {
                        //删除并进行出入库记录
                        foreach (var inventory in inventorys)
                        {
                            var inOutRecord = new InOutRecord()
                            {
                                StoreCode = storeInfo.StoreCode,
                                StoreId = storeInfo.Id,
                                StoreInfo = storeInfo,

                                R = storeInfo.R,
                                C = storeInfo.C,
                                Wei = storeInfo.Wei,
                                BigShelfCode = storeInfo.BigShelfCode,
                                GroupName = storeInfo.GroupName,

                                MatSN = inventory.MatSN,
                                MatCode = inventory.MatCode,
                                MatName = inventory.MatName,
                                MatSpec = inventory.MatSpec,
                                MatBatch = inventory.MatBatch,
                                MatQty = inventory.MatQty,
                                MatCustomer = inventory.MatCustomer,
                                MatSupplier = inventory.MatSupplier,

                                OperateUser = request.UserName + "（禁用库位）",
                                Direction = DirectionEnum.丢失,
                            };
                            DbHelp.db.Insertable(inOutRecord).ExecuteCommand();
                            DbHelp.db.Deleteable(inventory).ExecuteCommand();
                        }
                    }
                }
                else
                {
                    storeInfo.CurrentMatSn = string.Empty;
                }
                DbHelp.db.Updateable(storeInfo).ExecuteCommand();
                DbHelp.db.CommitTran();
                return new ResponseCommon()
                {
                    Code = 200,
                    Message = $"Success"
                };
            }
            catch (Exception ex)
            {
                DbHelp.db.RollbackTran();
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"操作失败：异常{ex.Message}！"
                };
            }
        }
        #endregion
    }
}
