using BPA.SAAS.Manage.Application.System.Dtos;
using BPA.SAAS.Manage.Application.System.Interface;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.system;
using BPA.SAAS.Manage.Core.System;

namespace BPA.SAAS.Manage.Application
{
    public class DictDataService : IDictDataService, ITransient
    {
        /// <summary>
        /// 核心对象：拥有完整的SqlSugar全部功能
        /// </summary>
        private readonly ISqlSugarClient _db;
        /// <summary>
        /// construct
        /// </summary>
        /// <param name="sqlSugarRepository"></param>
        public DictDataService(ISqlSugarClient db)
        {
            _db=db;
        }
        /// <summary>
        /// 根据字典类型编码查询
        /// </summary>
        /// <param name="TypeCode"></param>
        /// <returns></returns>
        public async Task<List<BPA_DictData>> GetDicList(string TypeCode)
        {
            var res =await _db.Queryable<BPA_DictData, BPA_DictType>((a, b) => new JoinQueryInfos(JoinType.Inner, a.TypeId.ToString() == b.Id))
                .Where((a, b) => b.Code == TypeCode && a.IsDeleted == 0 && b.IsDeleted == 0)
                .Select((a, b) => new BPA_DictData
                {
                    Id = a.Id.SelectAll()
                }).ToListAsync();
            return res;
        }
        /// <summary>
        /// 查询字典信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<PageUtil> GetDictData(DictDataQueryDto dto)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            if (!string.IsNullOrEmpty(dto.TypeId))
            {
                conModels.Add(new ConditionalModel() { FieldName = "a.TypeId", ConditionalType = ConditionalType.Like, FieldValue = dto.TypeId });
            }
            if (!string.IsNullOrEmpty(dto.Value))
            {
                conModels.Add(new ConditionalModel() { FieldName = "a.Value", ConditionalType = ConditionalType.Like, FieldValue = dto.Value });
            }
            if (!string.IsNullOrEmpty(dto.Status))
            {
                conModels.Add(new ConditionalModel() { FieldName = "a.Status", ConditionalType = ConditionalType.Equal, FieldValue = dto.Status });
            }
            if (!string.IsNullOrEmpty(dto.Code))
            {
                conModels.Add(new ConditionalModel() { FieldName = "a.Code", ConditionalType = ConditionalType.Equal, FieldValue = dto.Code });
            }
            if (!string.IsNullOrEmpty(dto.TypeCode))
            {
                conModels.Add(new ConditionalModel() { FieldName = "b.Code", ConditionalType = ConditionalType.Equal, FieldValue = dto.TypeCode });
            }
            RefAsync<int> total = 0;
            var res =await _db.Queryable<BPA_DictData, BPA_DictType>((a, b) => new JoinQueryInfos(JoinType.Inner, a.TypeId.ToString() == b.Id))
                .Where((a, b) => a.IsDeleted == 0 && b.IsDeleted == 0)
                .Where(conModels)
                .WhereIF(dto.CreateAt.HasValue, x => x.CreateAt.Date == dto.CreateAt.Value.Date)
                .Select((a, b) => new DictDataQueryDto
                {
                    Id = a.Id.SelectAll(),
                    TypeName = b.Name,
                    TypeCode = b.Code
                }).ToPageListAsync(dto.Current, dto.PageSize,  total);

            PageUtil util = new PageUtil()
            {
                Total = total,
                Data = res
            };
            return util;
        }
        /// <summary>
        /// 添加字典信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddDictData(DictDataDto dto)
        {
            var dicttypes = _db.Queryable<BPA_DictData>().Where(a => a.Code == dto.Code && a.IsDeleted == 0 && a.TypeId == dto.TypeId).ToList();
            if (dicttypes.Count() > 0)
            {
                throw Oops.Oh("编码已存在");
            }
            try
            {
                _db.Ado.BeginTran();
                var dictData = new BPA_DictData
                {
                    TypeId = dto.TypeId,
                    Value = dto.Value,
                    Code = dto.Code,
                    Remark = dto.Remark,
                };
                var res =await _db.Insertable(dictData).CallEntityMethod(t => t.Create()).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return res>0;
            }
            catch (Exception ex)
            {
                _db.Ado.RollbackTran();
                return false;
            }
        }
        /// <summary>
        /// 修改字典信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateDictData(DictDataDto dto)
        {
            var resEntity = _db.Queryable<BPA_DictData>().Where(it => it.IsDeleted == 0).First(it => it.Id == dto.Id);
            if (null == resEntity)
            {
                return false;
            }
            var resEntity2 = _db.Queryable<BPA_DictData>().Where(it => it.IsDeleted == 0).First(it => it.Id != dto.Id && it.Code == dto.Code);
            if (resEntity2 != null)
            {
                throw Oops.Oh("code已存在");
            }
            resEntity.Value = dto.Value;
            resEntity.Code = dto.Code;
            resEntity.Remark = dto.Remark;
            //resEntity.Status = (CommonStatus)Enum.ToObject(typeof(CommonStatus), int.Parse(dto.Status));
            var res =await _db.Updateable(resEntity).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 删除字典信息
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public async Task<bool> BatchDelDictData(List<string> Ids)
        {
            var resEntitites = _db.Queryable<BPA_DictData>().In(Ids).ToList();
            var res =await _db.Deleteable(resEntitites).ExecuteCommandAsync();
            return res > 0;
        }
    }
}