using BPA.SAAS.Manage.Application.Device.Dtos.Device;
using BPA.SAAS.Manage.Application.Device.Dtos.WarehouseTemplate;
using BPA.SAAS.Manage.Application.Device.Interface;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.Device;
using BPA.SAAS.Manage.Core.Product;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.Device.Services
{
    public class WarehouseTemplateService : IWarehouseTemplateService, ITransient
    {
        ISqlSugarClient _db;
        public WarehouseTemplateService(ISqlSugarClient db)
        {
            _db = db;   
        }
        public async Task<PageUtil> GetWarehouseTemplatePage(WarehouseTemplateQueryInputDto inputDto)
        {
            var total = new RefAsync<int>();
            var data = await _db.Queryable<BPA_WarehouseTemplate,BPA_DeviceInfo,BPA_ProductVesion>((a,b,c) => new JoinQueryInfos(JoinType.Left,a.DeviceId==b.Id, JoinType.Left, b.ProductVersionId == c.Id))
                .WhereIF(!string.IsNullOrWhiteSpace(inputDto.TemplateName), (a, b, c) => a.TemplateName.Contains(inputDto.TemplateName))
                 .WhereIF(!string.IsNullOrWhiteSpace(inputDto.DeviceName), (a, b, c) => a.DeviceId.Contains(inputDto.DeviceName))
                 .Select((a,b,c)=>new WarehouseTemplateView
                 {
                     Id=a.Id,
                     DeviceId=a.DeviceId,
                     DeviceName=b.DeviceName,
                     TemplateName =a.TemplateName,
                     CreateAt =a.CreateAt,
                     ProductNumber=c.ProductNumber,
                     ProductUrl=c.ProductUrl
                 })
                 .Mapper(x =>
                 {
                     x.WarehousePostion= _db.Queryable <BPA_WarehousePostion>().Where(t=>t.TemplateId==x.Id).ToList();
                 })
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .ToPageListAsync(inputDto.Current, inputDto.PageSize, total);

            return new PageUtil()
            {
                Data = data,
                Total = total

            };
        }
        public async Task<List<WarehouseTemplateView>> GetWarehouseTemplateList(string deviceId)
        {
            var total = new RefAsync<int>();
            var data = await _db.Queryable<BPA_WarehouseTemplate, BPA_DeviceInfo, BPA_ProductVesion>((a, b, c) => new JoinQueryInfos(JoinType.Left, a.DeviceId == b.Id, JoinType.Left, b.ProductVersionId == c.Id))
                .WhereIF(!string.IsNullOrWhiteSpace(deviceId), (a, b, c) => a.DeviceId.Contains(deviceId))
                 .Select((a, b, c) => new WarehouseTemplateView
                 {
                     Id = a.Id,
                     DeviceId = a.DeviceId,
                     DeviceName = b.DeviceName,
                     TemplateName = a.TemplateName,
                     CreateAt = a.CreateAt,
                     ProductNumber = c.ProductNumber,
                     ProductUrl = c.ProductUrl
                 })
                 .Mapper(x =>
                 {
                     x.WarehousePostion = _db.Queryable<BPA_WarehousePostion>().Where(t => t.TemplateId == x.Id).ToList();
                 })
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .ToListAsync();

            return data;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>

        public async Task<bool> AddWarehouseTemplate(WarehouseTemplatDto inputDto)
        {
            try
            {
                _db.Ado.BeginTran();
                var check = _db.Queryable<BPA_WarehouseTemplate>().Where(x => x.TemplateName == inputDto.TemplateName).Any();
                if (check) throw Oops.Oh("模板名称不能重复");
                var res = await _db.Insertable(new BPA_WarehouseTemplate
                {
                    DeviceId = inputDto.DeviceId,
                    TemplateName = inputDto.TemplateName,

                }).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                List<BPA_WarehousePostion> list = new();
                for (int i = 0; i < inputDto.WarehousePostionData.Count; i++)
                {
                    var tem = new BPA_WarehousePostion
                    {
                        TemplateId = res.Id,
                        Code = inputDto.WarehousePostionData[i].Code,
                        BatchingId = inputDto.WarehousePostionData[i].BatchingId,
                    };
                    list.Add(tem);
                }
                var res1 = await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception e)
            {
                _db.Ado.RollbackTran();
                throw Oops.Oh("添加失败,"+e.Message);
            }
           
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="inputList"></param>
        /// <returns></returns>
        public async Task<bool> DeWarehouseTemplate(List<string> inputList)
        {
            try
            {
                _db.Ado.BeginTran();
                var datas = await _db.Queryable<BPA_WarehouseTemplate>()
                    .Where(x => inputList.Contains(x.Id))
                    .ToListAsync();
                var datas1 = await _db.Queryable<BPA_WarehousePostion>()
                    .Where(x => inputList.Contains(x.TemplateId))
                    .ToListAsync();
                _db.Deleteable(datas).ExecuteCommand();
                _db.Deleteable(datas1).ExecuteCommand();
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception)
            {
                _db.Ado.RollbackTran();
                throw Oops.Oh("删除失败");
            }
            
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <returns></returns>
        public async Task<bool> UpdateWarehouseTemplate(WarehouseTemplatDto inputDto)
        {
            try
            {
                _db.Ado.BeginTran();
                var model = _db.Queryable<BPA_WarehouseTemplate>().Where(x => x.Id == inputDto.Id).First();
                model.DeviceId= inputDto.DeviceId;
                model.TemplateName= inputDto.TemplateName;
                var res = await _db.Updateable(model).ExecuteCommandAsync();
                var warehousePostion = _db.Queryable<BPA_WarehousePostion>().Where(x => x.TemplateId == inputDto.Id).ToList();
                await  _db.Deleteable(warehousePostion).ExecuteCommandAsync();
                List<BPA_WarehousePostion> list = new();
                for (int i = 0; i < inputDto.WarehousePostionData.Count; i++)
                {
                    var tem = new BPA_WarehousePostion
                    {
                        TemplateId = inputDto.Id,
                        Code = inputDto.WarehousePostionData[i].Code,
                        BatchingId = inputDto.WarehousePostionData[i].BatchingId,
                    };
                    list.Add(tem);
                }
                var res1 = await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception)
            {
                _db.Ado.RollbackTran();
                return false;
            }
        }
    }
}
