using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsTechnology;
using BPA.SAAS.Manage.Application.DataBase.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Device;
using BPA.SAAS.Manage.Core.Product;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.DataBase.Services
{
    public class GoodsTechnologyService: IGoodsTechnologyService, ITransient
    {
        ISqlSugarClient _db;
        public GoodsTechnologyService(ISqlSugarClient db)
        {
            _db = db;
        }
        #region 商品工艺（新版本工艺制作）
        /// <summary>
        /// 添加商品工艺
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateGoodsTechnologyAction(List<GoodsTechnologyActionBaseDto> inputDto)
        {
            try
            {
                var addlist = new List<BPA_GoodsTechnologyAction>();
                var list = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.DeviceId == inputDto[0].DeviceId && x.GoodsId == inputDto[0].GoodsId && x.GoodsAttributeId == inputDto[0].GoodsAttributeId).ToList();
                _db.Ado.BeginTran();
                _db.Deleteable(list).ExecuteCommand();
                //var list = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GroupId == groupId && x.IsDeleted == 0).ToList();

                for (int i = 0; i < inputDto.Count; i++)
                {
                    var goodsinfo = _db.Queryable<BPA_GoodsInfo>().Where(x => x.Id == inputDto[i].GoodsId).First();
                    var maxsort = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == inputDto[i].GoodsId && x.DeviceId == inputDto[i].DeviceId).Max(x => x.Sort);
                    var data = new BPA_GoodsTechnologyAction()
                    {
                        Id = string.IsNullOrEmpty(inputDto[i].Id) ? Guid.NewGuid().ToString() : inputDto[i].Id,
                        GoodsId = inputDto[i].GoodsId,
                        ActionJson = inputDto[i].ActionJson,
                        StepName = inputDto[i].StepName,
                        ChnologyId = inputDto[i].ChnologyId,
                        CreateAt = DateTime.Now,
                        WarehousrTemplateId = inputDto[i].WarehousrTemplateId,
                        IsDeleted = 0,
                        GoodsAttributeId = inputDto[i].GoodsAttributeId,
                        Sort = string.IsNullOrWhiteSpace(inputDto[i].Sort.ToString()) ? maxsort + (i + 1) : Convert.ToInt32(inputDto[i].Sort.ToString()),
                        IsBatch = inputDto[i].IsBatch,
                        DeviceId = inputDto[i].DeviceId,
                    };
                    if (!goodsinfo.IsAttrubute)
                    {
                        var sx = _db.Queryable<BPA_GoodsAttributeValue, BPA_GoodsAttribute>((a, b) => new JoinQueryInfos(
                     JoinType.Left, a.GoodsAttributeId == b.Id)).Where((a, b) => b.AttributeName == "默认属性").Select((a, b) => new BPA_GoodsAttributeValue() { Id = a.Id.SelectAll() }).First();
                        data.GoodsAttributeId = sx?.Id;
                    }
                    addlist.Add(data);
                }
                var res = await _db.Insertable(addlist).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return res > 0;
            }
            catch (Exception e)
            {
                _db.Ado.RollbackTran();
                throw Oops.Oh("保存失败");
            }

        }
        public async Task<bool> AddGoodsTechnologyAction(List<GoodsTechnologyActionBaseDto> inputDto)
        {
            try
            {
                var addlist = new List<BPA_GoodsTechnologyAction>();
                for (int i = 0; i < inputDto.Count; i++)
                {
                    var goodsinfo = _db.Queryable<BPA_GoodsInfo>().Where(x => x.Id == inputDto[i].GoodsId).First();
                    var maxsort = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == inputDto[i].GoodsId && x.DeviceId == inputDto[i].DeviceId).Max(x => x.Sort);
                    var data = new BPA_GoodsTechnologyAction()
                    {
                        Id = string.IsNullOrEmpty(inputDto[i].Id) ? Guid.NewGuid().ToString() : inputDto[i].Id,
                        GoodsId = inputDto[i].GoodsId,
                        ActionJson = inputDto[i].ActionJson,
                        StepName = inputDto[i].StepName,
                        ChnologyId = inputDto[i].ChnologyId,
                        CreateAt = DateTime.Now,
                        IsDeleted = 0,
                        WarehousrTemplateId = inputDto[i].WarehousrTemplateId,
                        GoodsAttributeId = inputDto[i].GoodsAttributeId,
                        Sort = string.IsNullOrWhiteSpace(inputDto[i].Sort.ToString()) ? maxsort + (i + 1) : Convert.ToInt32(inputDto[i].Sort.ToString()),
                        IsBatch = inputDto[i].IsBatch,
                        DeviceId = inputDto[i].DeviceId,
                    };
                    if (!goodsinfo.IsAttrubute)
                    {
                        var sx = _db.Queryable<BPA_GoodsAttributeValue, BPA_GoodsAttribute>((a, b) => new JoinQueryInfos(
                     JoinType.Left, a.GoodsAttributeId == b.Id)).Where((a, b) => b.AttributeName == "默认属性").Select((a, b) => new BPA_GoodsAttributeValue() { Id = a.Id.SelectAll() }).First();
                        data.GoodsAttributeId = sx?.Id;
                    }
                    addlist.Add(data);
                }
                var res = await _db.Insertable(addlist).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                return res > 0;
            }
            catch (Exception e)
            {
                throw Oops.Oh("保存失败");
            }

        }
        public async Task<List<GoodsTechnologyActionListView>> GetGoodsTechnologyAction(string goodsId)
        {
            List<GoodsTechnologyActionListView> goodsTechnologyActionListViews = new List<GoodsTechnologyActionListView>();
            var list = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x =>  x.GoodsId == goodsId)
                .Select(x => new GoodsTechnologyActionView()
                {
                    Id = x.Id.SelectAll(),
                }).OrderBy(x => x.Sort, OrderByType.Asc).ToList();
            var Devicelist = await _db.Queryable<BPA_DeviceInfo>().ToListAsync();
            var GoodsAttributeValue = await _db.Queryable<BPA_GoodsAttributeValue>().ToListAsync();
            var sf = list.GroupBy(x =>  x.GoodsAttributeId).ToList();
            var sf1 = list.GroupBy(x => x.WarehousrTemplateId).ToList();
            for (int i = 0; i < sf.Count; i++)
            {
                var sd = GoodsAttributeValue?.Where(x => sf[i].Key.Contains(x.Id)).Select(x => x.AttributeValue).ToArray();
                var sdw = GoodsAttributeValue?.Where(x => sf[i].Key.Contains(x.Id)).Select(x => x.Id).ToArray();
                var nane =string.Join('-', sd);
                var s = sf[i].AsQueryable().ToList().GroupBy(x => x.DeviceId).ToList();
                for (int t = 0; t < s.Count; t++)
                {
                    GoodsTechnologyActionListView item = new()
                    {
                        DeviceId = s[t].Key,
                        WarehousrTemplateId = sf1[t].Key,
                        GoodsAttributeId = string.Join(',', sdw),
                        DeviceName = Devicelist?.FirstOrDefault(x => x.Id == s[t].Key).DeviceName+ "【"+ nane+"】",
                        Data = s[t].AsQueryable().ToList(),
                    };
                    goodsTechnologyActionListViews.Add(item);
                }
            }
   
            return goodsTechnologyActionListViews;
        }
        public async Task<bool> DeleteGoodsTechnologyAction(string id)
        {
            var item = await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.Id == id).FirstAsync();
            if (item != null)
            {
                var res = await _db.Deleteable(item).ExecuteCommandAsync() > 0;
                var list = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x =>x.GoodsId == item.GoodsId && x.DeviceId == item.DeviceId).OrderBy(x => x.Sort, OrderByType.Asc).ToList();
                var uplist = new List<BPA_GoodsTechnologyAction>();
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].Sort = i + 1;
                    uplist.Add(list[i]);
                }
                if (uplist.Count > 0)
                {
                    await _db.Updateable(uplist).ExecuteCommandAsync();
                }
                return true;
            }
            else
            {
                throw Oops.Oh("找不到相关数据，删除失败");
            }
        }
        public async Task<bool> DeleteGoodsTechnologyAction(GoodsTechnologDelete dto)
        {
            var item = await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.DeviceId == dto.devideId && x.GoodsId == dto.goodsId && x.GoodsAttributeId== dto.goodsAttributeId).ToListAsync();
            if (item.Count > 0)
            {
                return await _db.Deleteable(item).ExecuteCommandAsync() > 0;
            }
            else
            {
                throw Oops.Oh("找不到相关数据，删除失败");
            }
        }
        public async Task<List<DeviceGoodsTechnologyView>> GetDeviceTechnology()
        {
            var list = await _db.Queryable<BPA_DeviceInfo>().Select(x => new DeviceGoodsTechnologyView()
            {
                Id = x.Id.SelectAll(),
            }).Mapper(a =>
            {
                //a.GoodsTechnologyInfo = _db.Queryable<BPA_ProductFunction>().Where(d => d.DeviceVersionKey == a.ProductVersionId && d.Type==1).Select(d => new GoodsTechnologyInfo()
                //{
                //    DeviceTechnologyId = d.Id,
                //    DeviceVersionKey = d.DeviceVersionKey,
                //    Name = d.Name,
                //}).ToList();
            }).ToListAsync();
            return list;
        }
        #endregion
        
    }
}
