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

namespace BPA.SAAS.Manage.Application.System.Services
{
    public class DictTypeService: IDictTypeService, ITransient
    {
        /// <summary>
        /// 核心对象：拥有完整的SqlSugar全部功能
        /// </summary>
        private readonly ISqlSugarClient _db;
        /// <summary>
        /// construct
        /// </summary>
        /// <param name="sqlSugarRepository"></param>
        public DictTypeService(ISqlSugarClient db)
        {
            _db = db;
        }
        /// <summary>
        /// 查询字典类型信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<PageUtil> GetDictType(DictTypeQueryDto dto)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            if (!string.IsNullOrEmpty(dto.Name))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Name", ConditionalType = ConditionalType.Like, FieldValue = dto.Name });
            }
            if (!string.IsNullOrEmpty(dto.Code))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Code", ConditionalType = ConditionalType.Like, FieldValue = dto.Code });
            }
            if (!string.IsNullOrEmpty(dto.Remark))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Remark", ConditionalType = ConditionalType.Like, FieldValue = dto.Remark });
            }

            if (!string.IsNullOrEmpty(dto.Status))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Status", ConditionalType = ConditionalType.Equal, FieldValue = dto.Status });
            }
            RefAsync<int> total = 0;
            var res =await _db.Queryable<BPA_DictType>()
                        .Where(x => x.IsDeleted == 0)
                        .Where(conModels)
                        .Select(x => new DictTypeQueryDto
                        {
                            Id = x.Id.SelectAll(),
                        })
                        .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> AddDictType(DictTypeDto dto)
        {
            var dicttypes = _db.Queryable<BPA_DictType>().Where(a => a.Code == dto.Code && a.IsDeleted==0).ToList();
            if (dicttypes.Count() > 0)
            {
                throw Oops.Oh("编码已存在");
            }
            try
            {
                _db.Ado.BeginTran();
                var dictType = new BPA_DictType
                {
                    Code = dto.Code,
                    Name = dto.Name,
                    Remark = dto.Remark
            };
                var res =await _db.Insertable(dictType).CallEntityMethod(t => t.Create()).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception ex)
            {
                _db.Ado.RollbackTran();
                return false;
            }
        }
        /// <summary>
        /// 修改字典类型信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateDictType(DictTypeDto dto)
        {
            var dictType = _db.Queryable<BPA_DictType>().Where(x => x.IsDeleted == 0).First(x => x.Id == dto.Id);
            if (dictType == null)
            {
                return false;
            }
            if (dictType.Code != dto.Code)
            {
                throw Oops.Oh("编码不能修改");
            }
            try
            {
                _db.Ado.BeginTran();
                dictType.Name = dto.Name;
                dictType.Code = dto.Code;
                dictType.Remark = dto.Remark;
                dictType.Status = (CommonStatus)Enum.ToObject(typeof(CommonStatus), int.Parse(dto.Status));
                var res =await _db.Updateable(dictType).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception)
            {
                _db.Ado.RollbackTran();
                return false;
            }
        }
        /// <summary>
        /// 删除字典类型信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> BathchDelDictType(List<string> ids)
        {
            try
            {
                _db.Ado.BeginTran();
                var dictType = _db.Queryable<BPA_DictType>().Where(x => x.IsDeleted == 0).Where(x => ids.Contains(x.Id)).ToList();
                
                var res =await _db.Deleteable(dictType).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return res>0;
            }
            catch (Exception)
            {
                _db.Ado.RollbackTran();
                return false;
            }
        }
       /// <summary>
       /// 下拉列表
       /// </summary>
       /// <returns></returns>
        public Dictionary<string, object> GetDictType()
        {
            var res = _db.Queryable<BPA_DictType>().Where(x => x.IsDeleted == 0 && x.Status == CommonStatus.ENABLE).ToDictionary(x => x.Id, x => x.Name);
            return res;

        }
    }
}
