using System;
using SqlSugar;
using Infrastructure.Attribute;
using ZR.Model;
using ZR.Repository;
using System.Linq;
using Infrastructure;
using System.Collections.Generic;
using ZR.Service.Business.IBusinessService.Inspect;
using ZR.Model.Dto.Inspect;
using ZR.Model.Models.Inspect;
using Mapster;

namespace ZR.Service.Business.Inspect
{
    /// <summary>
    /// 接口管理/SAP交验单记录表Service业务层处理
    ///
    /// @author admin
    /// @date 2023-05-05
    /// </summary>
    [AppService(ServiceType = typeof(ISapDeliverRecordService), ServiceLifetime = LifeTime.Transient)]
    public class SapDeliverRecordService : BaseService<SapDeliverRecord>, ISapDeliverRecordService
    {
        #region 业务逻辑代码

        /// <summary>
        /// 查询接口管理/SAP交验单记录表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<SapDeliverRecordDto> GetList(SapDeliverRecordQueryDto parm)
        {
            //开始拼装查询条件
            var predicate = Expressionable.Create<SapDeliverRecord>();

            if (parm.BeginTime != null && parm.EndTime != null)
            {
                parm.BeginTime = DateTimeHelper.GetBeginTime(parm.BeginTime, -1);
                parm.EndTime = DateTimeHelper.GetBeginTime(parm.EndTime, 1);
                predicate.And(d => d.CreateTime >= parm.BeginTime && d.CreateTime <= parm.EndTime);
            }
            predicate.AndIF(!string.IsNullOrEmpty(parm.DeliverNo), d => d.DeliverNo.Contains(parm.DeliverNo));
            predicate.AndIF(!string.IsNullOrEmpty(parm.BomNo), d => d.BomNo.Contains(parm.BomNo));
            predicate.AndIF(!string.IsNullOrEmpty(parm.MaterialCode), d => d.MaterialCode.Contains(parm.MaterialCode));
            predicate.AndIF(!string.IsNullOrEmpty(parm.MaterialName), d => d.MaterialName.Contains(parm.MaterialName));
            predicate.AndIF(!string.IsNullOrEmpty(parm.MaterialSpec), d => d.MaterialSpec.Contains(parm.MaterialSpec));
            predicate.AndIF(!string.IsNullOrEmpty(parm.Category), d => d.Category == parm.Category);
            predicate.AndIF(!string.IsNullOrEmpty(parm.CheckResult), d => d.CheckResult == parm.CheckResult);
            predicate.AndIF(parm.KeyFlag != null, d => d.KeyFlag == parm.KeyFlag);
            //搜索条件查询语法参考Sqlsugar
            var response = Queryable()
                .Where(predicate.ToExpression())
                .ToPage<SapDeliverRecord, SapDeliverRecordDto>(parm);

            return response;
        }


        /// <summary>
        /// 添加接口管理/SAP交验单记录表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddSapDeliverRecord(SapDeliverRecord model)
        {
            return Add(model, true);
        }

        /// <summary>
        /// 修改接口管理/SAP交验单记录表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateSapDeliverRecord(SapDeliverRecord model)
        {
            //var response = Update(w => w.Id == model.Id, it => new SapDeliverRecord()
            //{
            //    DeliverNo = model.DeliverNo,
            //    CheckName = model.CheckName,
            //    BomNo = model.BomNo,
            //    RowNo = model.RowNo,
            //    Category = model.Category,
            //    MaterialCode = model.MaterialCode,
            //    MaterialName = model.MaterialName,
            //    MaterialSpec = model.MaterialSpec,
            //    KeyFlag = model.KeyFlag,
            //    Qty = model.Qty,
            //    SpotCheckQty = model.SpotCheckQty,
            //    CheckQty = model.CheckQty,
            //    CheckResult = model.CheckResult,
            //    InstoreQty = model.InstoreQty,
            //    InstoreResult = model.InstoreResult,
            //    UpdateBy = model.UpdateBy,
            //    UpdateTime = model.UpdateTime,
            //    Remark = model.Remark,
            //});
            //return response;
            return Update(model, true);
        }

        /// <summary>
        /// 清空接口管理/SAP交验单记录表
        /// </summary>
        /// <returns></returns>
        public void TruncateSapDeliverRecord()
        {
            Truncate();
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public string ImportDatas(List<SapDeliverRecord> list)
        {
            var x = Context.Storageable(list)
                .SplitInsert(it => !it.Any())
                .ToStorage();
            var result = x.AsInsertable.ExecuteCommand();//插入可插入部分;

            string msg = string.Format(" 插入{0} 更新{1} 错误数据{2} 不计算数据{3} 删除数据{4},总共{5}",
                               x.InsertList.Count,
                               x.UpdateList.Count,
                               x.ErrorList.Count,
                               x.IgnoreList.Count,
                               x.DeleteList.Count,
                               x.TotalList.Count);
            //输出统计                      
            Console.WriteLine(msg);

            //输出错误信息               
            foreach (var item in x.ErrorList)
            {
                Console.WriteLine("交验单号为：" + item.Item.DeliverNo + " : " + item.StorageMessage);
            }

            return msg;
        }
        #endregion

        #region 2023 0524 孙亚龙 新增
        public List<SapDeliverDto> GetListNoPage(SapDeliverQueryNoPageDto parm)
        {
            //开始拼装查询条件
            var predicate = Expressionable.Create<SapDeliverRecord>();
            predicate.AndIF(parm != null && !string.IsNullOrEmpty(parm.DeliverNo), x => x.DeliverNo.Contains(parm.DeliverNo));
            predicate.AndIF(parm != null && !string.IsNullOrEmpty(parm.BomNo), x => x.BomNo.Contains(parm.BomNo));
            predicate.And(x => x.Qty > x.CheckQty);
            //搜索条件查询语法参考Sqlsugar
            var response = Queryable()
                .Distinct()
                .Where(predicate.ToExpression())
                .OrderBy(x => x.Id).Select(x => new { x.DeliverNo }).ToList();

            return response.Adapt<List<SapDeliverDto>>();
        }

        public List<SapDeliverRecordDto> GetSapDeliverRecordList(string deliverNo)
        {
            //开始拼装查询条件
            var predicate = Expressionable.Create<SapDeliverRecord>();
            predicate.And(x => x.DeliverNo == deliverNo);
            //predicate.And(x => x.Qty > x.CheckQty);
            //搜索条件查询语法参考Sqlsugar
            var response = Queryable()
                .Where(predicate.ToExpression())
                .OrderBy(x => x.Id).ToList();

            return response.Adapt<List<SapDeliverRecordDto>>();
        }

        public SapDeliverRecordSumDto GetSapDeliverRecordSum(string materialSpecCode, string deliverNo)
        {
            //开始拼装查询条件
            var predicate = Expressionable.Create<SapDeliverRecord>();
            predicate.And(x => x.MaterialSpec == materialSpecCode);
            predicate.And(x => x.DeliverNo == deliverNo);
            //搜索条件查询语法参考Sqlsugar
            var response = Queryable()
                .GroupBy(x => new { x.MaterialCode, x.MaterialName, x.MaterialSpec })
                .Where(predicate.ToExpression())
                .Select(x => new {
                    x.MaterialCode,
                    x.MaterialName,
                    x.MaterialSpec,
                    SumQty = SqlFunc.AggregateSum(x.Qty),
                    SumCheckQty = SqlFunc.AggregateSum(x.CheckQty),
                }).ToList();
            if (response.Count > 0)
            {
                return response[0].Adapt<SapDeliverRecordSumDto>();
            }
            else
            { 
                return null;
            }
        }
        #endregion
    }
}