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.MatDetailCurrentInfo;
using WCS.Model.ApiModel.MatDetailHistoryInfo;
using WCS.Model.ApiModel.StoreInfo;
using WCS.Model.ApiModel.User;

namespace WCS.BLL.Services.Service
{
    public class MatDetailCurrentInfoService : IMatDetailCurrentInfoService
    {

        public async Task<PageQueryResponse<MatDetailCurrentInfoModel>> GetMatDetailCurrentInfos(GetMatDetailCurrentInfosRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<MatDetailCurrentInfo>()
                                                .LeftJoin<ShelfInfo>((mci, si) => mci.ShelfId == si.Id)
                                                .LeftJoin<LocationInfo>((mci, si, li) => (si.TransStatus == TransStatusEnum.静止 && si.CurrentLocationId == li.Id)
                                                || (si.TransStatus == TransStatusEnum.运输中 && si.DestinationLocationId == li.Id))
                                                .WhereIF(request.LocationAreaId != null && request.LocationAreaId != 0, (mci, si, li) => li.LocationAreaId == request.LocationAreaId)
                                                .WhereIF(!string.IsNullOrEmpty(request.LocationCode), (mci, si, li) => li.LocationCode.Contains(request.LocationCode))
                                                .WhereIF(request.ShelfTypeId != null && request.ShelfTypeId != 0, (mci, si, li) => si.ShelfTypeId == request.ShelfTypeId)
                                                .WhereIF(!string.IsNullOrEmpty(request.ShelfCode), (mci, si, li) => si.ShelfCode.Contains(request.ShelfCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatCode), (mci, si, li) => mci.MatCode.Contains(request.MatCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatName), (mci, si, li) => mci.MatName.Contains(request.MatName))
                                                .Select((mci, si, li) => new MatDetailCurrentInfoModel()
                                                {
                                                    Id = mci.Id,
                                                    ShelfId = mci.ShelfId,
                                                    ShelfCode = mci.ShelfCode,
                                                    ShelfType = mci.ShelfType,

                                                    LocationArea = li.LocationArea,
                                                    LocationCode = li.LocationCode,

                                                    MatCode = mci.MatCode,
                                                    MatName = mci.MatName,
                                                    MatBatch = mci.MatBatch,
                                                    MatSpec = mci.MatSpec,
                                                    MatUnit = mci.MatUnit,
                                                    MatCustomer = mci.MatCustomer,
                                                    MatQty = mci.MatQty,
                                                    MatSupplier = mci.MatSupplier,

                                                    StationCode = mci.StationCode,
                                                    ModifyUser = mci.ModifyUser,
                                                    ModifyTime = mci.ModifyTime
                                                });

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

        public async Task<PageQueryResponse<MatDetailCurrentInfoModel>> ExportMatDetailCurrentInfos(GetMatDetailCurrentInfosRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<MatDetailCurrentInfo>()
                                                .LeftJoin<ShelfInfo>((mci, si) => mci.ShelfId == si.Id)
                                                .LeftJoin<LocationInfo>((mci, si, li) => (si.TransStatus == TransStatusEnum.静止 && si.CurrentLocationId == li.Id)
                                                || (si.TransStatus == TransStatusEnum.运输中 && si.DestinationLocationId == li.Id))
                                                .WhereIF(request.LocationAreaId != null && request.LocationAreaId != 0, (mci, si, li) => li.LocationAreaId == request.LocationAreaId)
                                                .WhereIF(!string.IsNullOrEmpty(request.LocationCode), (mci, si, li) => li.LocationCode.Contains(request.LocationCode))
                                                .WhereIF(request.ShelfTypeId != null && request.ShelfTypeId != 0, (mci, si, li) => si.ShelfTypeId == request.ShelfTypeId)
                                                .WhereIF(!string.IsNullOrEmpty(request.ShelfCode), (mci, si, li) => si.ShelfCode.Contains(request.ShelfCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatCode), (mci, si, li) => mci.MatCode.Contains(request.MatCode))
                                                .WhereIF(!string.IsNullOrEmpty(request.MatName), (mci, si, li) => mci.MatName.Contains(request.MatName))
                                                .Select((mci, si, li) => new MatDetailCurrentInfoModel()
                                                {
                                                    Id = mci.Id,
                                                    ShelfId = mci.ShelfId,
                                                    ShelfCode = mci.ShelfCode,
                                                    ShelfType = mci.ShelfType,

                                                    LocationArea = li.LocationArea,
                                                    LocationCode = li.LocationCode,

                                                    MatCode = mci.MatCode,
                                                    MatName = mci.MatName,
                                                    MatBatch = mci.MatBatch,

                                                    MatSpec = mci.MatSpec,
                                                    MatUnit = mci.MatUnit,
                                                    MatCustomer = mci.MatCustomer,
                                                    MatQty = mci.MatQty,
                                                    MatSupplier = mci.MatSupplier,

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

        public async Task<ResponseCommon<object>> updateMatDetailCurrentInfo(AddLocaionInfoRequest<MatDetailCurrentInfo> request)
        {
            try
            {
                var matDetailCurrentInfo = await DbHelp.db.Queryable<MatDetailCurrentInfo>()     //.Where(t => t.MatDetailCurrentCode == request.MatDetailCurrentInfo.MatDetailCurrentCode)
                                                          .Where(t => t.Id == request.LocationInfo.Id)
                                                          .FirstAsync();
                if (matDetailCurrentInfo == null)
                {
                    return new ResponseCommon<Object>
                    {
                        Code = 205,
                        Message = $"更新位置信息失败：此条数据不存在，请确认！",
                        Data = null
                    };
                }
                DbHelp.db.BeginTran();
                //新增数据修改记录表
                var historyInfo = new MatDetailHistoryInfo()
                {
                    ShlefId = matDetailCurrentInfo.ShelfId,
                    ShelfType = matDetailCurrentInfo.ShelfType,
                    ShelfCode = matDetailCurrentInfo.ShelfCode,

                    MatCode = matDetailCurrentInfo.MatCode,
                    MatName = matDetailCurrentInfo.MatName,
                    MatBatch = matDetailCurrentInfo.MatBatch,

                    MatSpec = matDetailCurrentInfo.MatSpec,
                    MatCustomer = matDetailCurrentInfo?.MatCustomer,
                    MatSupplier = matDetailCurrentInfo?.MatSupplier,

                    BeforeQty = matDetailCurrentInfo.MatQty,
                    AfterQty = request.LocationInfo.MatQty,

                    ModifyTime = DateTime.Now,
                    ModifyUser = request.UserName,
                    RecordType = RecordTypeEnum.修改,
                    FunctionType = request.DeviceType == "PDA" ? FunctionTypeEnum.PDA绑定查询 : FunctionTypeEnum.客户端货架存量,
                };
                await DbHelp.db.Insertable(historyInfo).ExecuteCommandAsync();
                //更新货架存量数据
                matDetailCurrentInfo.MatQty = request.LocationInfo.MatQty;
                matDetailCurrentInfo.ModifyUser = request.UserName;
                matDetailCurrentInfo.ModifyTime = DateTime.Now;
                var rowNum = await DbHelp.db.Updateable(matDetailCurrentInfo).ExecuteCommandAsync();
                if (rowNum == 0)
                {
                    DbHelp.db.RollbackTran();
                    return new ResponseCommon<Object>
                    {
                        Code = 201,
                        Message = $"更新货架存量信息失败：请重试！",
                        Data = null
                    };
                }
                else
                {
                    DbHelp.db.CommitTran();
                    DataProcessManager.UpdateShelfStatus();
                    return new ResponseCommon<Object>
                    {
                        Code = 200,
                        Message = $"更新货架存量信息成功！",
                        Data = null
                    };
                }
            }
            catch (Exception ex)
            {
                DbHelp.db.RollbackTran();
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"更新货架存量信息失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }



        public async Task<ResponseCommon<object>> deleteMatDetailCurrentInfo(DeleteInfosRequest request)
        {
            //先查询出具体的Id
            var matDetailCurrentInfos = await DbHelp.db.Queryable<MatDetailCurrentInfo>()
                                               .Where(t => request.needDeleteIds.Contains(t.Id))
                                               .ToListAsync();
            //执行删除
            try
            {
                DbHelp.db.BeginTran();
                //新增数据删除记录
                foreach (var matDetailCurrentInfo in matDetailCurrentInfos)
                {
                    var historyInfo = new MatDetailHistoryInfo()
                    {
                        ShlefId = matDetailCurrentInfo.ShelfId,
                        ShelfType = matDetailCurrentInfo.ShelfType,
                        ShelfCode = matDetailCurrentInfo.ShelfCode,

                        MatCode = matDetailCurrentInfo.MatCode,
                        MatName = matDetailCurrentInfo.MatName,
                        MatBatch = matDetailCurrentInfo.MatBatch,
                        MatSpec = matDetailCurrentInfo.MatSpec,
                        MatCustomer = matDetailCurrentInfo?.MatCustomer,
                        MatSupplier = matDetailCurrentInfo?.MatSupplier,

                        BeforeQty = matDetailCurrentInfo.MatQty,
                        AfterQty = 0,//删除数据 为0

                        ModifyTime = DateTime.Now,
                        ModifyUser = request.UserName,
                        RecordType = RecordTypeEnum.删除,
                        FunctionType = request.DeviceType == "PDA" ? FunctionTypeEnum.PDA绑定查询 : FunctionTypeEnum.客户端货架存量,
                    };
                    await DbHelp.db.Insertable(historyInfo).ExecuteCommandAsync();
                }
                var deleteRows = await DbHelp.db.Deleteable(matDetailCurrentInfos).ExecuteCommandAsync();

                DbHelp.db.CommitTran();
                DataProcessManager.UpdateShelfStatus();
                return new ResponseCommon<Object>
                {
                    Code = 200,
                    Message = $"已删除{deleteRows}条数据！",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                DbHelp.db.RollbackTran();
                var response = new ResponseCommon<Object>
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                    Data = null
                };
                return response;
            }
        }


    }
}
