using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.KitChenManage.Core;
using BPA.SAAS.Manage.Application.AExternalPlatform.BaseDto;
using BPA.SAAS.Manage.Application.AExternalPlatform.Enum;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Device.Dtos;
using BPA.SAAS.Manage.Application.AExternalPlatform.Service.Goods.Dtos;
using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsAttribute;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Device;
using BPA.SAAS.Manage.Core.Product;
using Furion.DependencyInjection;
using Furion.RemoteRequest.Extensions;
using Newtonsoft.Json;
using NPOI.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ResponDataBase = BPA.SAAS.Manage.Application.AExternalPlatform.BaseDto.ResponDataBase;

namespace BPA.SAAS.Manage.Application.AExternalPlatform.Service.Device.Services
{
    public class DeviceService:  IDeviceService, ITransient
    {
        private string BaseServerUrl = App.GetConfig<string>("baseurl");
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<PageUtil<List<DeviceDto>>> GetDevicePageList(DevicePageInputDto inputDto)
        {
            RefAsync<int> total = 0;
            var data =await SqlSugarDb.Db.Queryable<BPA_DeviceInfo, BPA_Product,BPA_ProductVesion>((a, b,c) =>
                new JoinQueryInfos(JoinType.Left, a.ProductId == b.Id, JoinType.Left, a.ProductVersionId == c.Id))
                .WhereIF(!string.IsNullOrEmpty(inputDto.ProductName), (a, b, c) => b.Name.Contains(inputDto.ProductName))
                 .WhereIF(!string.IsNullOrEmpty(inputDto.DeviceName), (a, b, c) => a.DeviceName.Contains(inputDto.DeviceName))
                  .WhereIF(!string.IsNullOrEmpty(inputDto.ProductVesion), (a, b, c) => c.Vesion.Contains(inputDto.ProductVesion))
                .Select((a, b, c) => new DeviceDto()
                {
                    Id = a.Id.SelectAll(),
                    ProductName = b.Name,
                    ProductVesion = c.Vesion

                }).ToPageListAsync(inputDto.Current, inputDto.PageSize,  total);

            return new PageUtil<List<DeviceDto>>()
            {
                Total = total,
                Data = data
            };
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddDevice(DeviceInsertDto dto)
        {
            try
            {
                SqlSugarDb.Db.BeginTran();
                var resEntity = new BPA_DeviceInfo();
                resEntity.DeviceName = dto.DeviceName;
                await CheckInsertParm(dto);//验证参数
                resEntity.StopId = dto.StopId;
                resEntity.ProductId = dto.ProductId;
                resEntity.ProductVersionId = dto.ProductVersionId;
                resEntity.DeviceTypeId= dto.DeviceTypeId;
                if (!string.IsNullOrEmpty(dto.DeviceTypeName))
                {
                    var check = SqlSugarDb.Db.Queryable<BPA_DeviceType>().Where(x => x.Name == dto.DeviceTypeName).First();
                    if (check != null)
                    {
                        resEntity.DeviceTypeId = check.Id;
                    }
                    else
                    {
                        var DeviceType = await SqlSugarDb.Db.Insertable(new BPA_DeviceType() { Name = dto.DeviceTypeName }).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                        resEntity.DeviceTypeId = DeviceType.Id;
                    }
                }
                
                var res = await SqlSugarDb.Db.Insertable(resEntity).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                SqlSugarDb.Db.CommitTran();
                return res > 0;
            }
            catch (Exception ex)
            {
                SqlSugarDb.Db.RollbackTran();
                throw Oops.Oh(ErrorCodeEnum.Code1007+","+ex.Message);
            }

        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool>UpdateDevice(DeviceUpateDto dto)
        {
            var resEntity = SqlSugarDb.Db.Queryable<BPA_DeviceInfo>().Where(it => it.IsDeleted == 0).First(it => it.Id == dto.Id);
            resEntity.DeviceName = dto.DeviceName;
            //resEntity.StopId = dto.StopId;
            //resEntity.ProductId = dto.ProductId;
            //resEntity.ProductVersionId = dto.ProductVersionId;
            if (!string.IsNullOrWhiteSpace(dto.DeviceTypeName))
            {
                var check = SqlSugarDb.Db.Queryable<BPA_DeviceType>().Where(x => x.Name == dto.DeviceTypeName).First();
                if (check != null)
                {
                    resEntity.DeviceTypeId = check.Id;
                }
                else
                {
                    var DeviceType = await SqlSugarDb.Db.Insertable(new BPA_DeviceType() { Name = dto.DeviceTypeName }).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                    resEntity.DeviceTypeId = DeviceType.Id;
                }
            }
            var res = await SqlSugarDb.Db.Updateable(resEntity).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteDevice(DeviceInfoDelDto dto)
        {
            var data = await SqlSugarDb.Db.Queryable<BPA_DeviceInfo>().Where(x => dto.Ids.Contains(x.Id)).ToListAsync();
            var GoodsTechnology = await SqlSugarDb.Db.Queryable<BPA_GoodsTechnologyAction>().Where(x => dto.Ids.Contains(x.DeviceId)).AnyAsync();
            if (GoodsTechnology) throw Oops.Oh("商品工艺已经关联到该设备下面，无法删除，请先解除商品工艺对应的设备");
            var WarehouseTemplate = await SqlSugarDb.Db.Queryable<BPA_WarehouseTemplate>().Where(x => dto.Ids.Contains(x.DeviceId)).AnyAsync();
            if (WarehouseTemplate) throw Oops.Oh("该设备已绑定了仓位模板，无法删除，请先删除该设备的仓位模板");
            var res = await SqlSugarDb.Db.Deleteable(data).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 校验参数
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        private async Task CheckInsertParm(DeviceInsertDto dto)
        {
            if (string.IsNullOrWhiteSpace(dto.StopId)) throw Oops.Oh(ErrorCodeEnum.Code1009);
            var getStopurl = BaseServerUrl + "api/shop/getbyIdstorelist_alm?id=" + dto.StopId;
            var responseStop = await getStopurl.SetHeaders(new
            {
                groupId = CurrentUser.GroupId
            }).SetHttpMethod(HttpMethod.Get).GetAsStringAsync();
            var responData = JsonConvert.DeserializeObject<ResponDataBase>(responseStop);
            var resStop = JsonConvert.DeserializeObject<StopDto> (responData.data.ToString());
            if (responData.statusCode != "200") throw Oops.Oh(ErrorCodeEnum.Code10021);
            //var dataStop = responData?.data;
            if (resStop == null) throw Oops.Oh(ErrorCodeEnum.Code10022);
           // if(!dataStop.Where(x=>x.Id == dto.StopId).Any()) throw Oops.Oh(ErrorCodeEnum.Code10022);

            var checkProduct = SqlSugarDb.Db.Queryable<BPA_Product>().Where(x => x.Id == dto.ProductId).Any();
            if (!checkProduct) throw Oops.Oh(ErrorCodeEnum.Code10010);
            var checkProductVesion = SqlSugarDb.Db.Queryable<BPA_ProductVesion>().Where(x => x.Id == dto.ProductVersionId).Any();
            if (!checkProductVesion) throw Oops.Oh(ErrorCodeEnum.Code10011);
        }
    }
}
