using BPA.KitChen.GroupMeal.Application.BaseDto;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.Member.MemberInfo.Dtos.MemberTag;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.Member.MemberTag.Dtos;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.PayCardInfo;
using BPA.KitChen.GroupMeal.Core.Common.Const;
using BPA.KitChen.GroupMeal.Core.Entity;
using BPA.KitChen.GroupMeal.Core.Enum;
using BPA.KitChen.GroupMeal.SqlSugar;
using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.RemoteRequest;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.KitChen.GroupMeal.Application.Service.OneCard.Member.MemberTag
{

    [ApiDescriptionSettings("会员管理", Tag = "会员标签")]
    public  class MemberTagService : SupperRepository, IDynamicApiController, IMemberTagService, ITransient
    {
        private readonly SqlSugarScope db;

        public MemberTagService()
        {
            db = SqlSugarDb.Db;   // 推荐操作
        }

        /// <summary>
        /// 查询会员标签信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberTagService/MemberTagQueryDto")]
        public PageUtil GetMemberTag(MemberTagQueryDto dto)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();

            string groupId = App.User.FindFirst(ClaimConst.GroupId)?.Value;
            if (!string.IsNullOrEmpty(dto.Name))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Name", ConditionalType = ConditionalType.Like, FieldValue= dto.Name.ToString() });
            }
            if (!string.IsNullOrEmpty(dto.PlatformType))
            {
                conModels.Add(new ConditionalModel() { FieldName = "PlatformType", ConditionalType = ConditionalType.Equal, FieldValue = dto.PlatformType });
            }
            if (!string.IsNullOrEmpty(dto.Status.ToString()))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Status", ConditionalType = ConditionalType.Equal, FieldValue = dto.Status.ToString() });
            }
            int total = new RefAsync<int>();
            var res = db.Queryable<BPA_MemberTag>()
                .Where(a => a.IsDeleted == 0)
                .Where(conModels)
                .WhereIF(dto.CreateAt.HasValue, a => SqlFunc.DateIsSame(a.CreateAt, Convert.ToDateTime(dto.CreateAt), DateType.Day))
                .OrderBy(x => x.CreateAt, OrderByType.Desc)
                .Select(t => new MemberTagQueryDto
                {
                    Id = t.Id,
                    Name = t.Name,
                    Sort = t.Sort,
                    PlatformType = t.PlatformType.ToString(),
                    CreateAt = t.CreateAt,
                    Status = Convert.ToInt32(t.Status),

                }).ToPageList(dto.Current, dto.PageSize, ref total);
            return new PageUtil()
            {
                Data = res,
                Total = total
            };
        }

        /// <summary>
        /// 添加会员标签信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberTagService/AddMemberTag")]
        public async Task<bool> AddMemberTag(MemberTagDto dto)
        {
            var activityRecord = new BPA_MemberTag
            {
                Name = dto.Name,
                Sort = dto.Sort,
                PlatformType =(int)dto.PlatformType,
                Status =(CommonStatus)dto.Status,
            };
            var res = await db.Insertable(activityRecord).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
            return await Task.FromResult(res > 0);
        }

        /// <summary>
        /// 更新会员标签信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("/api/MemberTagService/UpdateMemberTag")]
        public async Task<bool> UpdateMemberTag(MemberTagDto dto)
        {

            try
            {
                db.BeginTran();
                var resEntity = db.Queryable<BPA_MemberTag>().Where(it => it.IsDeleted == 0).First(it => it.Id == dto.Id);
                if (null == resEntity)
                {
                    return false;
                }
                resEntity.Name = dto.Name;
                resEntity.Sort = dto.Sort;
                resEntity.PlatformType = (int)dto.PlatformType;
                resEntity.Status =(CommonStatus) dto.Status;
                //if (!string.IsNullOrEmpty(dto.Status.ToString()))
                //{

                //}
                var res = db.Updateable(resEntity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.Modify()).ExecuteCommand();
              
                db.CommitTran();
                return await Task.FromResult(res > 0);
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                //BPALog.WriteLog(msg + ":" + ex.Message, LogEnum.Error, null, ex);
                throw Oops.Oh(ex.Message);
            }

           
        }


        /// <summary>
        /// 删除会员标签信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("/api/MemberTagService/DelMemberTag")]
        public bool DelMemberTag(string Id)
        {
            // 查询数据库中是否存在未删除的活动参与记录信息
            var resEntity = db.Queryable<BPA_MemberTag>().First(it => it.Id == Id);
            if (null == resEntity)
            {
                return false;
            }
            resEntity.IsDeleted = 1;
            resEntity.Status = CommonStatus.DELETED;
            var res = db.Updateable(resEntity).CallEntityMethod(m => m.Delete()).ExecuteCommand();
            return res > 0;
        }



    }
}
