using BPA.KitChen.GroupMeal.Application.BaseDto;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.PayCardInfo.Dto;
using BPA.KitChen.GroupMeal.Core.Entity;
using BPA.KitChen.GroupMeal.SqlSugar;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace BPA.KitChen.GroupMeal.Application.Service.OneCard.PayCardInfo
{
    [ApiDescriptionSettings("一卡通", Tag = "刷卡机管理")]
    public class PayCardInfoService : SupperRepository, IDynamicApiController, IPayCardInfoService, ITransient
    {
        private readonly SqlSugarScope db;

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

        /// <summary>
        /// 添加刷卡机
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/PayCard/add")]
        public async Task<bool> Add(PayCardInfoAddDto inputDto)
        {
            var data = db.Queryable<BPA_PayCard>().Where(x => inputDto.Address == x.Address).ToList();
            if (data.Count > 0)
            {
                throw Oops.Oh($"编码已存在");
                return false;
            }
            return await db.Insertable(inputDto.Adapt<BPA_PayCard>())
                 .CallEntityMethod(m => m.Create()).ExecuteCommandAsync() > 0;
        }

        /// <summary>
        /// 修改刷卡机状态
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/PayCard/enable")]
        public async Task<bool> Enable(PayCardInfoEnableDto inputDto)
        {
            var data = await db.Queryable<BPA_Gate>().Where(x => inputDto.Id == x.Id).ToListAsync();
            foreach (var item in data)
            {
                item.Status = inputDto.Status;
            }
            var res = await db.Updateable(data)
              .CallEntityMethod(m => m.Modify()).ExecuteCommandAsync();
            return res > 0;
        }

        /// <summary>
        /// 获取撒卡机列表
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpGet("/api/PayCard/gatealllist")]
        public async Task<List<PayCardInfoQueryDto>> GetGateAllList([FromQuery] PayCardInfoQueryAllInputDto inputDto)
        {
            var total = new RefAsync<int>();
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            if (!string.IsNullOrEmpty(inputDto.GateId))
            {
                conModels.Add(new ConditionalModel() { FieldName = "a.GateId", ConditionalType = ConditionalType.Equal, FieldValue = inputDto.GateId });
            }

            return await db.Queryable<BPA_PayCard, BPA_Gate>((a, b) =>
                      new JoinQueryInfos(JoinType.Inner, a.GateId == b.Id))
                .Where((a, b) => a.IsDeleted == 0)
                   .Where(conModels)
               .OrderBy((a, b) => a.CreateAt, OrderByType.Desc)
               .Select((a, b) => new PayCardInfoQueryDto
               {
                   Id = a.Id.SelectAll(),
                   GateName = b.Name
               })
               .ToListAsync();
        }

        /// <summary>
        /// //根据门店ID查询 档口分页列表
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpGet("/api/PayCard/gateList")]
        public async Task<PageUtil> GetGateList([FromQuery] PayCardInfoQueryInputDto inputDto)
        {
            var total = new RefAsync<int>();
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            if (!string.IsNullOrEmpty(inputDto.GateId))
            {
                conModels.Add(new ConditionalModel() { FieldName = "a.GateId", ConditionalType = ConditionalType.Equal, FieldValue = inputDto.GateId });
            }

            var data = await db.Queryable<BPA_PayCard, BPA_Gate>((a, b) =>
                      new JoinQueryInfos(JoinType.Inner, a.GateId == b.Id))
                .Where((a, b) => a.IsDeleted == 0)
                   .Where(conModels)
               .OrderBy((a, b) => a.CreateAt, OrderByType.Desc)
               .Select((a, b) => new PayCardInfoQueryDto
               {
                   Id = a.Id.SelectAll(),
                   GateName = b.Name
               })
               .ToPageListAsync(inputDto.Current, inputDto.PageSize, total);
            return new PageUtil()
            {
                Data = data,
                Total = total

            };
        }


        /// <summary>
        /// 修改刷卡机
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("/api/PayCard/update")]
        public async Task<bool> Update(PayCardInfoUpdateDto inputDto)
        {
            var data = await db.Queryable<BPA_PayCard>().Where(x => inputDto.Id == x.Id).FirstAsync();
            if (data.Address != inputDto.Address)
            {
                var newdata = db.Queryable<BPA_PayCard>().Where(x => inputDto.Address == x.Address).ToList();
                if (newdata.Count > 0)
                {
                    throw Oops.Oh($"刷卡机编号已存在");
                    return false;
                }
            }
            data.Name = inputDto.Name;
            data.GateId = inputDto.GateId;
            data.SleepTime = inputDto.SleepTime;
            data.Address = inputDto.Address;
            data.Status = inputDto.Status;
            var res = await db.Updateable(data)
               .CallEntityMethod(m => m.Modify()).ExecuteCommandAsync();
            return res > 0;
        }


        /// <summary>
        /// 删除刷卡机
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("/api/PayCard/del")]
        public async Task<bool> Del(string id)
        {
            var data = await db.Queryable<BPA_PayCard>().FirstAsync(x => x.Id == id);
            if (data == null)
            {
                throw Oops.Oh($"删除的数据不存在");
            }
            data.IsDeleted = 1;
            var res = await db.Updateable(data)
                .CallEntityMethod(m => m.Delete()).ExecuteCommandAsync();
            return res > 0;
        }
    }
}
