using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TouchSocket.Core;
using WCS.BLL.DbModels;
using WCS.BLL.Services.IService;
using WCS.DAL;
using WCS.DAL.Db;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.MatBaseInfo;
using WCS.Model.ApiModel.User;

namespace WCS.BLL.Services.Service
{
    /// <summary>
    /// 物料基础信息
    /// </summary>
    public class MatBaseInfoService : IMatBaseInfoService
    {
        public MatBaseInfoService()
        {

        }

        public async Task<PageQueryResponse<MatBaseInfo>> getMatBaseInfo(GetMatBaseInfoRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<MatBaseInfo>()
                                          .WhereIF(!string.IsNullOrEmpty(request.MatCode), t => t.MatCode.Contains(request.MatCode))
                                          .WhereIF(!string.IsNullOrEmpty(request.MatName), t => t.MatName.Contains(request.MatName))
                                          .WhereIF(!string.IsNullOrEmpty(request.MatSpec), t => t.MatSpec.Contains(request.MatSpec))
                                          .WhereIF(request.IsEnable != null, t => t.IsEnable == request.IsEnable.GetValueOrDefault());

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

        public async Task<PageQueryResponse<MatBaseInfo>> exportMatBaseInfo(GetMatBaseInfoRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<MatBaseInfo>()
                                          .WhereIF(!string.IsNullOrEmpty(request.MatCode), t => t.MatCode.Contains(request.MatCode))
                                          .WhereIF(!string.IsNullOrEmpty(request.MatName), t => t.MatName.Contains(request.MatName))
                                          .WhereIF(!string.IsNullOrEmpty(request.MatSpec), t => t.MatSpec.Contains(request.MatSpec))
                                          .WhereIF(request.IsEnable != null, t => t.IsEnable == request.IsEnable.GetValueOrDefault());
                var records = await recordsQueryable.OrderByDescending(t => t.Id).ToListAsync();
                //生成序号
                var index = 1;
                records.ForEach(r =>
                {
                    r.RowNumber = index++;
                });
                return new PageQueryResponse<MatBaseInfo>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<MatBaseInfo>()
                    {
                        Lists = records
                    }
                };

            }
            catch (Exception ex)
            {
                return new PageQueryResponse<MatBaseInfo>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<ResponseCommon<List<string>>> importMatBaseInfo(List<MatBaseInfoImportModel> lists, string userName, string deviceType)
        {

            //获取数据
            #region 校验导入的编号是否重复
            var matCodes = lists.Select(t => t.物料编码)
                              .ToList();
            var duplicates = matCodes.GroupBy(x => x)
                    .Where(g => g.Count() > 1)
                    .Select(g => g.Key).ToList();
            //有重复的情况
            if (duplicates.Count > 0)
            {
                return new ResponseCommon<List<string>>()
                {
                    Code = 201,
                    Message = "导入失败：文件中存在物料编码重复",
                    Data = duplicates
                };
            }
            #endregion

            #region 校验导入数据与数据库中数据是否有重复数据
            duplicates = await DbHelp.db.Queryable<MatBaseInfo>()
                                           .Where(t => matCodes.Contains(t.MatCode))
                                           .Select(t => t.MatCode)
                                           .ToListAsync();

            //有重复的情况
            if (duplicates.Count > 0)
            {
                return new ResponseCommon<List<string>>()
                {
                    Code = 201,
                    Message = "导入失败：以下物料编码已存在",
                    Data = duplicates
                };
            }
            #endregion

            #region 导入数据
            try
            {
                await DbHelp.db.BeginTranAsync();
                foreach (var mat in lists)
                {
                    var matBaseInfo = new MatBaseInfo()
                    {
                        MatCode = mat.物料编码,
                        MatName = mat.名称,
                        MatSpec = mat.规格,
                        MatUnit = mat.单位,
                        MatCustomer = mat.客户,
                        ModifyUser = userName,
                        IsEnable = mat.状态 == "启用" ? true : false,
                    };
                    await DbHelp.db.Insertable(matBaseInfo).ExecuteCommandAsync();
                }
                await DbHelp.db.CommitTranAsync();
                return new ResponseCommon<List<string>>()
                {
                    Code = 200,
                    Message = "导入数据成功",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                await DbHelp.db.RollbackTranAsync();
                var ErrList = new List<string>
                {
                    ex.Message
                };
                return new ResponseCommon<List<string>>()
                {
                    Code = 200,
                    Message = "导入失败",
                    Data = ErrList
                };
            }
            #endregion
        }

        public async Task<ResponseCommon<object>> addOrUpdateMatBaseInfo(AddMatBaseInfoRequest<MatBaseInfo> request)
        {
            try
            {
                var matBaseInfo = await DbHelp.db.Queryable<MatBaseInfo>()
                                    .Where(t => t.MatCode == request.MatBaseInfo.MatCode)
                                    .FirstAsync();
                //修改物料基础数据
                if (request.AddOrUpdate == AddOrUpdate.Update)
                {
                    if (matBaseInfo == null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"更新物料基础数据失败：物料{request.MatBaseInfo}不存在！",
                            Data = null
                        };
                    }
                    else
                    {
                        matBaseInfo.MatName = request.MatBaseInfo.MatName;
                        matBaseInfo.MatSpec = request.MatBaseInfo.MatSpec;
                        matBaseInfo.MatUnit = request.MatBaseInfo.MatUnit;
                        matBaseInfo.MatCustomer = request.MatBaseInfo.MatCustomer;
                        matBaseInfo.IsEnable = request.MatBaseInfo.IsEnable;


                        matBaseInfo.ModifyTime = request.MatBaseInfo.ModifyTime;
                        matBaseInfo.ModifyUser = request.MatBaseInfo.ModifyUser;

                        var rowNum = await DbHelp.db.Updateable(matBaseInfo).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 (matBaseInfo != null)
                    {
                        return new ResponseCommon<Object>
                        {
                            Code = 201,
                            Message = $"物料基础数据失败：物料{request.MatBaseInfo.MatCode}已存在",
                            Data = null
                        };
                    }
                    else
                    {
                        var newMatBaseInfo = new MatBaseInfo()
                        {
                            MatCode = request.MatBaseInfo.MatCode,
                            MatName = request.MatBaseInfo.MatName,
                            MatSpec = request.MatBaseInfo.MatSpec,
                            MatUnit = request.MatBaseInfo.MatUnit,
                            MatCustomer = request.MatBaseInfo.MatCustomer,
                            IsEnable = request.MatBaseInfo.IsEnable,

                            ModifyTime = request.MatBaseInfo.ModifyTime,
                            ModifyUser = request.MatBaseInfo.ModifyUser,
                        };
                        var rowNum = await DbHelp.db.Insertable(newMatBaseInfo).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)
                //{
                //    if (matBaseInfo == null)
                //    {
                //        return new ResponseCommon<Object>
                //        {
                //            Code = 201,
                //            Message = $"删除物料基础数据失败：物料{request.MatBaseInfo}不存在！",
                //            Data = null
                //        };
                //    }
                //    else
                //    {
                //        var rowNum = await AuthDbHelp.db.Deleteable(matBaseInfo).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>> deleteMatBaseInfo(DeleteInfosRequest request)
        {
            //先查询出具体的Id
            var matBaseInfos = await DbHelp.db.Queryable<MatBaseInfo>()
                    .Where(t => request.needDeleteIds.Contains(t.Id))
                    .ToListAsync();
            //执行删除
            try
            {
                var deleteRows = await DbHelp.db.Deleteable(matBaseInfos).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;
            }
        }

        public async Task<ResponseCommon<List<string>>> getMatCodeList(GetMatCodeListRequest request)
        {
            try
            {
                List<string> matCodeList = null;
                if (request.IsFromBaseData)
                {
                    matCodeList = await DbHelp.db.Queryable<MatBaseInfo>()
                                                 .OrderBy(t => t.MatCode)
                                                 .Select(t => t.MatCode)
                                                 .Distinct()
                                                 .ToListAsync();
                }
                else
                {
                    matCodeList = await DbHelp.db.Queryable<InventoryDetail>()
                                                 .Select(t => t.MatCode)
                                                 .Distinct()
                                                 .ToListAsync();
                }
                return new ResponseCommon<List<string>>()
                {
                    Code = 200,
                    Message = "success",
                    Data = matCodeList
                };
            }
            catch (Exception e)
            {
                return new ResponseCommon<List<string>>()
                {
                    Code = 201,
                    Message = $"获取失败：{e.Message}",
                    Data = null
                };
            }
        }

        public async Task<PageQueryResponse<MatInfo>> getMatInfo(GetMatInfoRequest request)
        {
            try
            {
                var recordsQueryable = DbHelp.db.Queryable<MatInfo>()
                                          .WhereIF(!string.IsNullOrEmpty(request.MatCode), t => t.MatCode.Contains(request.MatCode))
                                          .WhereIF(!string.IsNullOrEmpty(request.MatName), t => t.MatName.Contains(request.MatName))
                                          .WhereIF(!string.IsNullOrEmpty(request.MatSpec), t => t.MatSpec.Contains(request.MatSpec))
                                          .WhereIF(!string.IsNullOrEmpty(request.MatBatch), t => t.MatBatch.Contains(request.MatBatch))
                                          .WhereIF(request.IsPrinted != null, t => t.IsPrinted == request.IsPrinted)
                                          .WhereIF(!string.IsNullOrEmpty(request.MatSN), t => t.MatSn.Contains(request.MatSN));
                var totalCount = await recordsQueryable.CountAsync();
                var records = await recordsQueryable.OrderByDescending(t => t.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<MatInfo>()
                {
                    Code = 200,
                    Message = $"success",
                    Data = new PageQueryResponseData<MatInfo>()
                    {
                        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<MatInfo>()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }

        public async Task<ResponseCommon> printedMatInfo(PrintedMatInfoRequest request)
        {
            try
            {

                if (request == null || request.PrintedMatInfoIds == null || request.PrintedMatInfoIds.Count == 0)
                {
                    return new ResponseCommon()
                    {
                        Code = 300,
                        Message = $"操作失败:参数为null",
                    };
                }

                DbHelp.db.BeginTran();
                //获取打印的具体数据
                var matInfos = await DbHelp.db.Queryable<MatInfo>()
                    .Where(t => request.PrintedMatInfoIds.Contains(t.Id))
                    .ToListAsync();
                //打印次数加一
                matInfos.ForEach(matInfo =>
                {
                    matInfo.IsPrinted = true;
                    matInfo.PrintedTimes = matInfo.PrintedTimes + 1;
                });
                await DbHelp.db.Updateable(matInfos).ExecuteCommandAsync();
                DbHelp.db.CommitTran();

                return new ResponseCommon()
                {
                    Code = 200,
                    Message = $"Success",
                };
            }
            catch (Exception ex)
            {
                DbHelp.db.RollbackTran();
                return new ResponseCommon()
                {
                    Code = 300,
                    Message = $"操作失败:{ex.Message}",
                };
            }
        }


    }
}
