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 LocationInfoService : ILocationInfoService
    {
        /// <summary>
        /// 获取位置数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageQueryResponse<LocationInfo>> GetLocationInfos(GetLocationInfosRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<LocationInfo>()
                                                .WhereIF(request.LocationAreaId != null, t => t.LocationAreaId == request.LocationAreaId)
                                                .WhereIF(request.IsEnable != null, t => t.IsEnable == request.IsEnable)
                                                .WhereIF(!string.IsNullOrEmpty(request.LocationCode), t => t.LocationCode.Contains(request.LocationCode));

                //分页
                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .Skip((request.PageNumber - 1) * request.PageSize).Take(request.PageSize)
                                    .ToListAsync();
                //获取系统内货架类型
                var shelfTypes = await DbHelp.db.Queryable<ShelfTypeInfo>().ToListAsync();

                //生成序号
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].AllowShelfTypesName = shelfTypes.Where(s => records[i].AllowShelfTypes.Contains(s.Id))
                                                               .Select(t => t.ShelfTypeName)
                                                               .ToList();
                    records[i].RowNumber = (request.PageNumber - 1) * request.PageSize + i + 1;
                }
                return new PageQueryResponse<LocationInfo>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<LocationInfo>()
                    {
                        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<LocationInfo>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        /// <summary>
        /// 导出位置数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<PageQueryResponse<LocationInfo>> ExportLocationInfos(GetLocationInfosRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<LocationInfo>()
                                                .WhereIF(request.LocationAreaId != null, t => t.LocationAreaId == request.LocationAreaId)
                                                .WhereIF(request.IsEnable != null, t => t.IsEnable == request.IsEnable)
                                                .WhereIF(!string.IsNullOrEmpty(request.LocationCode), t => t.LocationCode.Contains(request.LocationCode));

                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable
                                    .Take(65535)
                                    .ToListAsync();
                //获取系统内货架类型
                var shelfTypes = await DbHelp.db.Queryable<ShelfTypeInfo>().ToListAsync();

                var index = 1;
                //生成序号
                for (int i = 0; i < records.Count; i++)
                {
                    records[i].AllowShelfTypesName = shelfTypes.Where(s => records[i].AllowShelfTypes.Contains(s.Id))
                                                               .Select(t => t.ShelfTypeName)
                                                               .ToList();
                    records[i].RowNumber = index++;
                }
                return new PageQueryResponse<LocationInfo>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<LocationInfo>()
                    {
                        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<LocationInfo>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }
        public async Task<ResponseCommon<object>> addOrUpdateLocationInfo(AddLocaionInfoRequest<LocationInfo> request)
        {
            try
            {
                var locationInfo = await DbHelp.db.Queryable<LocationInfo>()
                                    .Where(t => t.LocationCode == request.LocationInfo.LocationCode)
                                    .FirstAsync();
                //修改位置信息
                if (request.AddOrUpdate == AddOrUpdate.Update)
                {
                    var existId = locationInfo == null ? 0 : locationInfo.Id;

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

                        var rowNum = await DbHelp.db.Updateable(request.LocationInfo).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 (locationInfo != null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"新增位置信息失败：位置[{locationInfo.LocationCode}]已存在!",
                            Data = null
                        };
                    }
                    else
                    {
                        request.LocationInfo.ModifyUser = request.UserName;
                        var rowNum = await DbHelp.db.Insertable(request.LocationInfo).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>> deleteLocationInfo(DeleteInfosRequest request)
        {
            //先查询出具体的Id
            var locationInfos = await DbHelp.db.Queryable<LocationInfo>()
                                               .Where(t => request.needDeleteIds.Contains(t.Id))
                                               .ToListAsync();
            //执行删除
            try
            {
                var deleteRows = await DbHelp.db.Deleteable(locationInfos).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;
            }
        }
    }
}
