using BPA.KitChen.GroupMeal.Application.BaseDto;
using BPA.KitChen.GroupMeal.Application.Service.AExternalPlatform.Enum;
using BPA.KitChen.GroupMeal.Application.Service.AExternalPlatform.Service.DiningPlateService.Dtos;
using BPA.KitChen.GroupMeal.Application.Service.OneCard.DiningPlate.Dtos;
using BPA.KitChen.GroupMeal.Core.Common;
using BPA.KitChen.GroupMeal.Core.Entity;
using BPA.KitChen.GroupMeal.Core.Enum;
using BPA.KitChen.GroupMeal.SqlSugar;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static BPA.KitChen.GroupMeal.Application.Service.AExternalPlatform.Service.DiningPlateService.Dtos.InputDto;

namespace BPA.KitChen.GroupMeal.Application.Service.AExternalPlatform.Service.DiningPlateService.Service
{
    public class DiningPlateService: IDiningPlateService, ITransient
    {

        /// <summary>
        ///更具二维码 获取餐盘信息
        /// </summary>
        public async Task<BPA_DiningPlate> GetDiningPlateInfoByQRCode(DiningPlateQRCodeInputDto inputDto)
        {


            var res =await SqlSugarDb.Db.Queryable<BPA_DiningPlate>()
                .Where(x=>x.QRCode== inputDto.QRCode)
                .FirstAsync();

            if (res==null)
            {
                throw Oops.Oh("餐盘信息不存在");
            }

            if (res.Status== CommonStatus.DISABLE)
            {
                throw Oops.Oh("餐盘被停用");
            }
            var data = await GetDiningPlateOccupyInfo(new List<string>() { res.Id });
            if (data != null)
            {
                foreach (var item1 in data)
                {
                    if (item1.DiningPlateId==res.Id)
                    {
                        if (item1.IsOccupy)
                        {
                            throw Oops.Oh("餐盘被占用");
                        }
                    }
                }
            }

            return res;
        }

        /// <summary>
        ///更具芯片码 获取餐盘信息
        /// </summary>
        public async Task<BPA_DiningPlate> GetDiningPlateInfoByChipCode(DiningPlateChipCodeInputDto inputDto)
        {


            var res = await SqlSugarDb.Db.Queryable<BPA_DiningPlate>()
                .Where(x => x.IsDeleted == 0)
                .Where(x => x.ChipCode == inputDto.ChipCode)
                .FirstAsync();

            if (res == null)
            {
                throw Oops.Oh("餐盘信息不存在");
            }

            if (res.Status == CommonStatus.DISABLE)
            {
                throw Oops.Oh("餐盘被停用");
            }
            var data = await GetDiningPlateOccupyInfo(new List<string>() { res.Id });
            if (data != null)
            {
                foreach (var item1 in data)
                {
                    if (item1.DiningPlateId == res.Id)
                    {
                        if (item1.IsOccupy)
                        {
                            throw Oops.Oh("餐盘被占用");
                        }
                    }
                }
            }

            return res;
        }

        /// <summary>
        /// 根据二维码修改餐盘信息（有就修改没有就新增）
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> EditDiningPlateByQRCode(DiningPlateCreateOrUpdataDto inputDto)
        {
            var data = await SqlSugarDb.Db.Queryable<BPA_DiningPlate>()
                .FirstAsync(x => x.QRCode == inputDto.QRCode);


            var data1 = await SqlSugarDb.Db.Queryable<BPA_DiningPlate>()
                .FirstAsync(x => inputDto.ChipCode == x.ChipCode);

            if (data != null && data1 != null && data.Id != data1.Id)
            {
                throw Oops.Oh($"芯片码已存在");
            }

            var res = 0;
            if (data == null)
            {
                if (data1 != null)
                {
                    throw Oops.Oh($"芯片码已存在");
                }


                res = await SqlSugarDb.Db.Insertable(new BPA_DiningPlate()
                {
                    Id = Guid.NewGuid().ToString(),
                    ChipCode = inputDto.ChipCode,
                    GroupId = CurrentUser.TenantId,
                    QRCode = inputDto.QRCode,
                    IsPay= inputDto.IsPay,
                    Status = CommonStatus.ENABLE,
                }).ExecuteCommandAsync();
            }
            else
            {
                data.IsPay = inputDto.IsPay;
                data.ChipCode = inputDto.ChipCode;
                res = await SqlSugarDb.Db.Updateable(data).ExecuteCommandAsync();
            }

            return res > 0;
        }


        private async Task<List<DiningPlateOccupyDto>> GetDiningPlateOccupyInfo(List<string> inputDto)
        {
            var result = new List<DiningPlateOccupyDto>();

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("GroupId", CurrentUser.TenantId);
            var url = App.Configuration["GroupMealOrderUrl"] + "api/WeighOrder/GetDiningPlateOccupyInfo";
            var inputData = JsonConvert.SerializeObject(inputDto);
            var jsonData = HttpHelper.PostData(url, inputData, Encoding.UTF8, "application/json", dic);
            var data = JsonConvert.DeserializeObject<ResultSAASManageDto>(jsonData);

            if (data.statusCode != 200)
            {
                throw Oops.Oh(data.errors);
            }

            if (data.data != null)
            {
                result = data.data as List<DiningPlateOccupyDto>;
            }


            return result;
        }

    }
}
