using OASystem.Domain.Common;
using OASystem.Domain.Dtos.Business;
using OASystem.Domain.Entities.Business;
using OASystem.Domain.ViewModels.Business;
using OASystem.Domain.ViewModels.Resource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Business
{
    public class CommonBusRepository : BaseRepository<EntityBase, ViewBase>
    {
        public CommonBusRepository(SqlSugarClient sqlSugar) : base(sqlSugar)
        {
        }

        #region 可选物料集合

        /// <summary>
        /// 获取可选物料集合
        /// </summary>
        /// <returns></returns>
        public async Task<List<OptionalBusRangeView>> GetViewList_OptionalItem()
        {
            List<OptionalBusRangeView> result = new List<OptionalBusRangeView>();

            //获取业务范围
            string sqlRange = string.Format(@" Select * From Sys_SetData With(Nolock) Where STid = {0} And IsDel=0 ", SetDataTypeDefaultParam.Media);
            List<Sys_SetData> entitySetDataList = _sqlSugar.SqlQueryable<Sys_SetData>(sqlRange).ToList();

            //获取物料信息
            List<Res_ItemInfoView> itemSource = new List<Res_ItemInfoView>();
            string sqlItemList = string.Format(@" Select 
d.ItemName,d.Id as ItemId,s.Id as ItemTypeSetDataId,d.VendorId,v.FullName as VendorFullName,
 v.ShortName as VendorShortName,t.Id as ItemTypeId,t.TypeName as ItemTypeName,
 d.MinRate,d.MaxRate,d.CurrRate,d.Remark
From Res_ItemDetail as d With(Nolock) 
Inner Join Res_ItemType as t With(Nolock) On d.ItemTypeId = t.Id
Inner Join Res_ItemVendor as v With(Nolock) On d.VendorId=v.Id
Inner Join Sys_SetData as s With(Nolock) On t.SdId=s.Id ");

            itemSource = _sqlSugar.SqlQueryable<Res_ItemInfoView>(sqlItemList).ToList();
            if (itemSource.Count > 0)
            {
                foreach (var item in entitySetDataList)
                {
                    List<Res_ItemInfoView> tempList = itemSource.Where(s => s.ItemTypeSetDataId == item.Id).ToList();
                    if (tempList.Count > 0)
                    {
                        OptionalBusRangeView _tempView = new OptionalBusRangeView()
                        {
                            SdId = item.Id,
                            SdName = item.Name
                        };

                        List<OptionalItemTypeView> optionalItemTypeViewList = new List<OptionalItemTypeView>();

                        var itemGroups = tempList.GroupBy(p => p.ItemTypeId);
                        foreach (var group in itemGroups)
                        {
                            OptionalItemTypeView tempOptional = new OptionalItemTypeView();
                            tempOptional.ItemTypeId = group.Key;
                            tempOptional.ItemTypeName = group.First().ItemTypeName;
                            tempOptional.ItemList = new List<Res_ItemInfoView>(group.ToList());
                            optionalItemTypeViewList.Add(tempOptional);
                        }
                        _tempView.ItemTypeList = new List<OptionalItemTypeView>(optionalItemTypeViewList);
                        result.Add(_tempView);
                    }
                }
            }

            return result;
        }

        #endregion

        #region 会务物料采购清单

        /// <summary>
        /// 新增会务物料采购清单和具体采购物料信息
        /// </summary>
        /// <param name="_dto"></param>
        /// <returns></returns>
        public async Task<int> Insert_ConfItemList(Edit_OptionalItemListDto _dto)
        {
            Bus_ConfItemListInfo _check1 = await Query<Bus_ConfItemListInfo>(s => s.Diid == _dto.DiId).FirstAsync();
            if (_check1 != null)
            {
                return -2;//已存在数据,无法新增,请检查BusController中非空验证
            }

            Bus_ConfItemListInfo _insert = new Bus_ConfItemListInfo();
            _insert.Diid = _dto.DiId;
            _insert.TotalCost = _dto.ConfItemList.Sum(s => (s.CurrCost * s.Count));
            BeginTran();
            try
            {
                int result = await _sqlSugar.Insertable(_insert).ExecuteReturnIdentityAsync();
                if (result > 0)
                {
                    List<Bus_ConfItemInfo> insertList = new List<Bus_ConfItemInfo>();
                    foreach (var item in _dto.ConfItemList)
                    {
                        Bus_ConfItemInfo temp = new Bus_ConfItemInfo();
                        temp.ConfListId = result;
                        temp.Count = item.Count;
                        temp.CurrCost = item.CurrCost;
                        temp.ItemId = item.ItemId;
                        temp.OpRemark = item.OpRemark;
                        insertList.Add(temp);
                    }
                    _sqlSugar.Insertable(insertList).UseParameter().ExecuteCommand();
                    return 0;
                }
                else
                {
                    return -3;//保存清单主体数据失败
                }
            }
            catch (Exception ex)
            {
                RollbackTran();
                return -4;
            }


            return -1;
        }

        /// <summary>
        /// 修改会务物料采购清单和具体采购物料信息(未存在删除、暂时)
        /// </summary>
        /// <param name="_dto"></param>
        /// <returns></returns>
        public async Task<int> Edit_ConfItemList(Edit_OptionalItemListDto _dto)
        {
            Bus_ConfItemListInfo _eidt = await Query<Bus_ConfItemListInfo>(s => s.Id == _dto.ConfItemListId).FirstAsync();
            if (_eidt == null)
            {
                return -2;//不存在数据,无法修改,请检查BusController中非空验证
            }

            _eidt.TotalCost = _dto.ConfItemList.Sum(s => (s.CurrCost * s.Count));

            BeginTran();
            try
            {
                int result = await _sqlSugar.Updateable<Bus_ConfItemListInfo>()
                            .SetColumns(it => it.TotalCost == _eidt.TotalCost)
                            .Where(s => s.Id == _dto.ConfItemListId)
                            .ExecuteCommandAsync();
                _sqlSugar.Deleteable<Bus_ConfItemInfo>().Where(it => it.ConfListId == _dto.ConfItemListId).ExecuteCommand();

                if (result > 0)
                {

                    List<Bus_ConfItemInfo> insertList = new List<Bus_ConfItemInfo>();
                    foreach (var item in _dto.ConfItemList)
                    {
                        Bus_ConfItemInfo temp = new Bus_ConfItemInfo();
                        temp.ConfListId = result;
                        temp.Count = item.Count;
                        temp.CurrCost = item.CurrCost;
                        temp.ItemId = item.ItemId;
                        temp.OpRemark = item.OpRemark;
                        insertList.Add(temp);
                    }
                    _sqlSugar.Insertable(insertList).UseParameter().ExecuteCommand();
                    return 0;
                }
                else
                {
                    return -3;//保存清单主体数据失败
                }
            }
            catch (Exception ex)
            {
                RollbackTran();
                return -4;
            }

            return -1;
        }

        #endregion
    }
}