using BPA.SAAS.Manage.Application.DataBase.Dtos.Goods;
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 NPOI.SS.Formula.Functions;
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 goodlist= await _db.Queryable<BPA_GoodsInfo>().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+ goodlist?.FirstOrDefault(x=>x.Id==goodsId).Name + "【"+ 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

        public async Task<bool> Updatetechnology() 
        {
            _db.Ado.BeginTran();
            var rum=0;
            try
            {  
                //查询商品数据
                var goodsInfo = await _db.Queryable<BPA_GoodsInfo>().Where(x=>x.GoodsTypeId== "ae8b8cf2-541f-4317-8814-35f268b969c9") .ToListAsync();
                if (goodsInfo.Count>0)
                {
                    //查询所有的商品大份
                    var biggoodsInfo = goodsInfo.Where(x => x.Name.Contains("大份")).ToList();
                    foreach (var item in biggoodsInfo)
                    {
                        //根据商品查询属性工艺关系表
                        var goodstechnologyaction= await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == item.Id).ToListAsync();
                        foreach (var itemgood in goodstechnologyaction)
                        {
                            //更新 GoodsAttributeId值
                            //大份的数据 去掉小份标识
                            if (itemgood.GoodsAttributeId.Contains("c73c5a29-1e55-4a06-89bf-b3b9bfcfd01a"))
                            {
                                continue;
                            }
                           var   GoodsAttributeIds = "c73c5a29-1e55-4a06-89bf-b3b9bfcfd01a";
                            itemgood.GoodsAttributeId = itemgood.GoodsAttributeId + ',' + GoodsAttributeIds;
                            rum = _db.Updateable(itemgood).ExecuteCommand();
                        }
                        var arr1 = item.Name.Split('-');
                        var smgoodsList = goodsInfo.Where(x => x.Name == (arr1[0] + "-小份")).ToList();
                        if (smgoodsList == null|| smgoodsList.Count>1) throw new Exception(item.Name + "数据异常");
                   
                        var smgoods= smgoodsList.FirstOrDefault();

                        var smgoodstechnologyaction = await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == smgoods.Id).ToListAsync();

                        foreach (var smitem in smgoodstechnologyaction)
                        {
                            smitem.GoodsId = item.Id;
                            smitem.GoodsAttributeId += ",0a2646b8-e9f2-49d8-8ff2-1b99e7bccf5d";
                             _db.Updateable(smitem).ExecuteCommand();
                        }

                        //
                        if (!item.Name.Contains("修改数据"))
                        {
                            item.Name += "(修改数据)";

                        }
                        _db.Updateable(item).ExecuteCommand();
                    }
                 
                }
               await CopyGoodsByType();
                _db.Ado.CommitTran();
                return rum > 0;
            }
            catch (Exception)
            {
                _db.Ado.RollbackTran();
                throw;
            }
        }

        public async Task CopyGoodsByType()
        {
            try
            {
                //获取所有面类商品
                var goodsInfo = await _db.Queryable<BPA_GoodsInfo>().Where(x => x.GoodsTypeId == "ae8b8cf2-541f-4317-8814-35f268b969c9" && x.Name.Contains("大份")).ToListAsync();

                if (goodsInfo.Count > 0)
                {
                    var data = (await _db.Queryable<BPA_GoodsInfo>().ToListAsync()).Max(x => x.AutoKey);
                    foreach (var item in goodsInfo)
                    {
                        //根据商品查询属性工艺关系表
                        var goodstechnologyaction = await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == item.Id).ToListAsync();
                        if (data == 0) data = 1000;
                        else data = data + 1;
                        item.Id = Guid.NewGuid().ToString();
                        item.AutoKey = data;
                        item.GoodsTypeId = "b40544ce-9647-438f-b470-57296f78843e";
                        //添加粉类商品
                        item.Name += "自动增加";
                       var newGoods=await   _db.Insertable(item).ExecuteCommandAsync();
                      
                        //替换工艺关系
                        foreach (var action in goodstechnologyaction)
                        {
                            action.Id = Guid.NewGuid().ToString();
                            action.GoodsId = item.Id;
                            //替换大份
                            var miansm = "c73c5a29-1e55-4a06-89bf-b3b9bfcfd01a";
                            var fensm = "529979f4-421e-473f-9a9b-8a7b8b2e5f8d";
                            action.GoodsAttributeId= action.GoodsAttributeId.Replace(miansm, fensm);
                            //替换小份
                            var miansm1 = "0a2646b8-e9f2-49d8-8ff2-1b99e7bccf5d";
                            var fensm1 = "4d0cc643-c9d4-4bab-85fb-a4245ec79502";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm1, fensm1);
                            //替换标准
                            var miansm4 = "392ead57-c86e-4cce-8185-526191c723a2";
                            var fensm4 = "35efd495-1674-45dc-b27b-fe5f51cfb449";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm4, fensm4);

                            //替换少辣
                            var miansm5 = "fee52f3e-68a5-4754-aa8f-ddb9d7886943";
                            var fensm5 = "cdd94a1a-aab8-4de3-a98d-c60868cf0766";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm5, fensm5);

                            //替换无蒜
                            var miansm6 = "cc917a14-c86b-4690-97ab-4dfcd839a4e1";
                            var fensm6 = "0f5a4221-fd24-453d-bc95-bcb785790984";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm6, fensm6);


                            //替换少辣无蒜
                            var miansm7 = "55037c0b-8120-4efe-a024-46234add2f2e";
                            var fensm7 = "331bdf64-2a61-4637-992f-83e450cd1d6b";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm7, fensm7);


                            //替换红汤
                            var miansm2 = "bbc9bf59-abe9-475d-ba9b-8de5288f1d87";
                            var fensm2 = "cbb8aa0b-2da7-49cb-8d6f-8ec5750d57ea";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm2, fensm2);
                            //替换清汤
                            var miansm3 = "e63c4b63-eede-4cac-9212-fbdd42c02f0a";
                            var fensm3 = "758c1b45-25f3-4aef-8fe0-c76398529595";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm3, fensm3);


                            //替换麻辣干拌
                            var miansm8 = "f19d3851-231c-4a25-84bb-22a51560204e";
                            var fensm8 = "b4c6e805-eac0-44ee-bbb9-d6d467775dd0";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm8, fensm8);

                            //替换清汤干拌
                            var miansm9 = "d7c2a180-c2d9-4b8e-ad54-57fe6dfc5d62";
                            var fensm9 = "10c0416c-169c-4254-8f2c-d8a7e76c69f6";
                            action.GoodsAttributeId = action.GoodsAttributeId.Replace(miansm9, fensm9);


                            await _db.Insertable(action).ExecuteCommandAsync();

                      
                        }
                      

                    }
                }


            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 复制工艺
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<bool> CopyTechnologyAction(IputParam param) 
        {
            _db.Ado.BeginTran();
            var rum = 0;
            try
            {     //根据商品查询属性工艺关系表
                var goodstechnologyaction = await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == param.OldgoodsId&& x.GoodsAttributeId==param.goodsAttributeId).ToListAsync();
                //查询当前商品是否存在工艺，若存在则提示
                var isExistList = await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.GoodsId == param.NewgoodsId && x.GoodsAttributeId == param.NewgoodsAttributeId&&x.DeviceId==param.DevideId).ToListAsync();
                if (isExistList?.Count>0)
                {
                    throw Oops.Oh("当前商品已存在选择的商品属性工艺，不能复制!!");
                }
                //替换工艺关系
                foreach (var action in goodstechnologyaction)
                {
                    action.Id = Guid.NewGuid().ToString();
                    action.GoodsId = param.NewgoodsId;
                    action.GoodsAttributeId = param.NewgoodsAttributeId;
                  rum = await _db.Insertable(action).ExecuteCommandAsync();
                }
                _db.Ado.CommitTran();
                return rum > 0;
            }
            catch (Exception)
            {

                _db.Ado.RollbackTran();
                throw;
            }
        }
        /// <summary>
        /// 根据设备获取工艺
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<List<DeviceTechnologyActionListView>> GetDeviceTechnologyAction(DeviceQueryDto param) 
        {
            List<DeviceTechnologyActionListView> goodsTechnologyActionListViews = new List<DeviceTechnologyActionListView>();
            var list = _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => x.DeviceId ==param.DeviceId).Select(x => new DeviceTechnologyActionListView()
            {
                Id = x.Id.SelectAll(),
            }).ToList();
            var Goodlist = await _db.Queryable<BPA_GoodsInfo>().ToListAsync();
            var Devicelist = await _db.Queryable<BPA_DeviceInfo>().ToListAsync();
            var GoodsAttributeValue = await _db.Queryable<BPA_GoodsAttributeValue>().ToListAsync();
            var sf = list.GroupBy(x => x.GoodsAttributeId).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 name = string.Join('-', sd);
                var s = sf[i].AsQueryable().ToList().GroupBy(x => x.GoodsId).ToList();
                for (int t = 0; t < s.Count; t++)
                {
                    DeviceTechnologyActionListView item = new()
                    {   
                        DeviceId =param.DeviceId ,
                        GoodsId = s[t].Key,
                        GoodsName= Goodlist?.FirstOrDefault(x => x.Id == s[t].Key).Name,
                        GoodsAttributeId = string.Join(',', sdw),
                        DeviceName = Devicelist?.FirstOrDefault(x => x.Id ==param.DeviceId).DeviceName,
                       TechnologyName = Goodlist?.FirstOrDefault(x => x.Id == s[t].Key).Name + "【" + name + "】",
                    };
                    goodsTechnologyActionListViews.Add(item);
                }
            }
            if (!string.IsNullOrWhiteSpace(param.TechnologyName))
            {
                goodsTechnologyActionListViews=goodsTechnologyActionListViews.Where(x => x.TechnologyName.Contains(param.TechnologyName)).ToList();
            }
            return goodsTechnologyActionListViews;
        }
    }

}
