using Google.Protobuf;
using LinqToDB;
using log4net;
using MasaBlazorApp3.DataAccess.Dao;
using MasaBlazorApp3.Pojo;
using MasaBlazorApp3.Pojo.Config;
using MasaBlazorApp3.Pojo.Vo;
using Microsoft.Extensions.Options;
using Org.BouncyCastle.Crypto;
using Radzen;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using ZstdSharp.Unsafe;

namespace MasaBlazorApp3.DataAccess.Impl
{
    public class PlanDao : IPlanDao
    {
        private AppDataConnection _connection;
        private readonly SettingConfig _setting;
        private readonly ILog logger = LogManager.GetLogger(typeof(DrugInfoDao));
        private GlobalStateService _globalStateService;
        private NotificationService _message;
        public PlanDao(AppDataConnection connection, IOptions<SettingConfig> setting, GlobalStateService globalStateService,NotificationService message)
        {
            _connection = connection;
            _setting = setting.Value;
            _globalStateService = globalStateService;
            _message = message;
        }
        /// <summary>
        /// 获取所有套餐数据
        /// </summary>
        /// <returns></returns>
        public async Task<PageMultiData<Plan, DrugInfo>> GetAllPlanInfo()
        {
            var query = _connection.Plan.AsQueryable();

            List<Plan> list = await query.Where(p => p.UseState == 1 && p.MachineId==_setting.boxMachineId)
                .LoadWith(p => p._PlanDetails.Where(pd => pd.UseState == 1))
                //.ThenLoad(p=>p._DrugInfo)
                .OrderBy(r => r.Id)
                .ToListAsync();
            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count(); i++)
                {
                    for (int j = 0; j < list[i]._PlanDetails.Count(); j++)
                    {
                        list[i]._PlanDetails[j]._DrugInfo =
                             _connection.DrugInfo.AsQueryable().Where(di => di.DrugId == list[i]._PlanDetails[j].DrugId).First();

                    }
                }
            }

            var other = _connection.DrugInfo.AsQueryable();
            List<DrugInfo> drugInfos = await other
                .LoadWith(di => di.Manus)
                .OrderBy((di) => di.DrugId)
                .ToListAsync();

            int pagedData = await query.CountAsync();
            return new PageMultiData<Plan, DrugInfo>()
            {

                TotalDesserts = pagedData,
                Desserts = list,
                Other = drugInfos
            };
        }
        /// <summary>
        /// 根据套餐ID获取套餐数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<Plan> GetPlanById(int Id)
        {
            var query = _connection.Plan.AsQueryable().Where(p => p.Id == Id && p.UseState == 1 && p.MachineId == _setting.boxMachineId);
            List<Plan> list = await query
               .LoadWith(p => p._PlanDetails)
               //.ThenLoad(p=>p._DrugInfo)
               .OrderBy(r => r.Id)
               .ToListAsync();
            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count(); i++)
                {
                    for (int j = 0; j < list[i]._PlanDetails.Count(); j++)
                    {
                        list[i]._PlanDetails[j]._DrugInfo =
                             _connection.DrugInfo.AsQueryable().Where(di => di.DrugId == list[i]._PlanDetails[j].DrugId).First();

                    }
                }
            }

            return list[0];
        }

        /// <summary>
        /// 新增套餐
        /// </summary>
        /// <param name="plan"></param>
        /// <returns></returns>
        public async Task<bool> InsertPlanInfo(Plan plan)
        {
            try
            {
                plan.AddTime = DateTime.Now;
                plan.OperatorUser = _globalStateService.Operator.Id;
                plan.ReviewerUser = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id;
                plan.UseState = 1;
                plan.MachineId = _setting.boxMachineId;
                if(_connection.InsertWithInt32Identity(plan) > 0)
                {
                    //保存操作记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.boxMachineId,
                        OperationTime = DateTime.Now,
                        Type = 50,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"新增套餐{plan.Name}",
                    });


                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {

                logger.Error($"添加套餐{plan.Name}失败，错误：" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 更新套餐
        /// </summary>
        /// <param name="plan"></param>
        /// <returns></returns>
        public async Task<bool> UpdatePlanInfo(Plan plan)
        {
            try
            {
                var iResult = _connection.Plan
                  .Where(p => p.Id == plan.Id && p.MachineId == _setting.boxMachineId)
                  .Set(p => p.Name, plan.Name)
                  .Set(p => p.Description, plan.Description);
                return iResult.Update() > 0;
            }
            catch (Exception ex)
            {
                logger.Error($"修改套餐{plan.Name}失败，错误：" + ex.Message);
                return false;
            }
        }
        //查询要删除的套餐下是否有绑定，且绑定有库存
        public async Task<bool> CheckPlanBind(int planId)
        {
            try
            {
                //查询是否有绑定，没有绑定可以删除，有绑定则不允许删除
                List<string> channelListsId = await _connection.ChannelList.AsQueryable().Where(cl => cl.DrugId == planId.ToString() && cl.MachineId == _setting.boxMachineId).Select(cl => cl.Id).ToListAsync();
                if (channelListsId != null && channelListsId.Count > 0)
                {
                    bool searchResult = _connection.ChannelStock.AsQueryable().Where(cs => channelListsId.Contains(cs.ListId)).Any(cs => cs.Quantity > 0);
                    if (searchResult)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"查询要删除的套餐下是否有绑定异常{ex.Message}");
                return false;
            }
        }


        /// <summary>
        /// 删除套餐
        /// </summary>
        /// <param name="planId"></param>
        /// <returns></returns>
        public async Task<bool> DeletePlanInfo(int planId)
        {
            try
            {
                _connection.BeginTransaction();


                //如果套餐下有绑药且库存为0的也将绑定药品信息一并删除
                List<string> listIds = await _connection.ChannelList.Where(cl => cl.DrugId == planId.ToString()).Select(cl => cl.Id).ToListAsync();
                int iDelResult = 1;
                int iDelChannelListResult = 1;
                if (listIds != null && listIds.Count > 0)
                {
                    //删除channelStock表中的绑定药品
                    iDelResult = _connection.ChannelStock.Where(cs => listIds.Contains(cs.ListId)).Delete();
                    _connection.ChannelList.Where(cl => listIds.Contains(cl.Id)).Set(cl => cl.DrugId, "").Update();


                }
                bool flag = false;
                logger.Error($"删除套餐{planId}");
                //查询该套餐下是否有药品，如果有则一并删除
                int iHasPd = _connection.PlanDetails.Where(pd => pd.PlanId == planId).Count();
                int pdResult = 1;
                if (iHasPd > 0)
                {
                    pdResult = await _connection.PlanDetails.Where(pd => pd.PlanId == planId).Set(pd => pd.UseState, 0).UpdateAsync();
                }
                int pResult = await _connection.Plan.Where(p => p.Id == planId).Set(pd => pd.UseState, 0).UpdateAsync();

                

                if (pdResult > 0 && pResult > 0 && iDelResult > 0 && iDelChannelListResult > 0)
                {
                    //保存操作记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.boxMachineId,
                        OperationTime = DateTime.Now,
                        Type = 51,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"删除套餐{planId}",
                    });

                    flag = true;
                }

                if (flag)
                {
                    _connection.CommitTransaction();
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;
            }
            catch (Exception ex)
            {
                logger.Error($"修改套餐失败，错误：" + ex.Message);
                _connection.RollbackTransaction();
                return false;
            }
        }


        /// <summary>
        /// 向套餐中添加药品
        /// </summary>
        /// <param name="details"></param>
        /// <returns></returns>
        public async Task<bool> AddPlanDetail(PlanDetails details)
        {
            try
            {
                if (!string.IsNullOrEmpty(details.DrugId))
                {
                    int id = await _connection.InsertWithInt32IdentityAsync(details);
                    details.Id = id;
                    //保存操作记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.boxMachineId,
                        OperationTime = DateTime.Now,
                        Type = 52,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"套餐{details.PlanId}添加药品{details.DrugId},基数{details.BaseQuantity}",
                    });
                    return id > 0;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                logger.Error($"添加药品{details._DrugInfo.DrugName}失败，错误：" + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 修改套餐中的药品
        /// </summary>
        /// <param name="details"></param>
        /// <returns></returns>
        public async Task<bool> UpdatePlanDetail(PlanDetails details)
        {
            try
            {
                var iResult = _connection.PlanDetails
                  .Where(p => p.Id == details.Id)
                  .Set(p => p.DrugId, details._DrugInfo.DrugId)
                  .Set(p => p.BaseQuantity, details.BaseQuantity);

                //保存操作记录
                int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                {
                    MachineId = _setting.boxMachineId,
                    OperationTime = DateTime.Now,
                    Type = 53,
                    Operator = _globalStateService.Operator.Id,
                    Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                    InvoiceId = $"修改套餐{details.PlanId}，药品{details.DrugId}-{details._DrugInfo.DrugId}，基数{details.BaseQuantity}",
                });
                return await iResult.UpdateAsync() > 0;
            }
            catch (Exception ex)
            {
                logger.Error($"修改药品{details._DrugInfo.DrugName}失败，错误：" + ex.Message);
                return false;
            }
        }

        //查询要删除的药品是否有绑定且库存大于0
        public async Task<bool> CheckPlanDetailBind(PlanDetails planDetail)
        {
            try
            {
                bool bFlag = true;
                List<string> idList = await _connection.ChannelList.AsQueryable().Where(cl => cl.DrugId == planDetail.PlanId.ToString()).Select(cl => cl.Id).ToListAsync();
                if (idList != null && idList.Count > 0)
                {
                    bFlag = !(_connection.ChannelStock.AsQueryable().Where(cs => idList.Contains(cs.ListId) && cs.DrugId == planDetail.DrugId).Any(cs => cs.Quantity > 0));
                }
                return bFlag;
            }
            catch (Exception ex)
            {
                logger.Error($"查询要删除的药品是否有绑定异常{ex.Message}");
                return true;
            }
        }

        /// <summary>
        /// 删除套餐中的药品
        /// </summary>
        /// <param name="details"></param>
        /// <returns></returns>
        public async Task<bool> DeletePlanDetail(PlanDetails detail)
        {
            try
            {
                _connection.BeginTransaction();
                logger.Error($"删除套餐中的药品{detail._DrugInfo.DrugName}");
                int iDelResult = 1;
                //删除该套餐下该药品对应绑定的库位
                List<string> idList = await _connection.ChannelList.AsQueryable().Where(cl => cl.DrugId == detail.PlanId.ToString()).Select(cl => cl.Id).ToListAsync();
                if (idList != null && idList.Count > 0)
                {
                    iDelResult = await _connection.ChannelStock.AsQueryable().Where(cs => idList.Contains(cs.ListId) && cs.DrugId == detail.DrugId).DeleteAsync();
                }
                //if (iDelResult > 0)
                //{
                bool bUpdateResult = _connection.PlanDetails.Where(p => p.Id == detail.Id).Set(p => p.UseState, 0).Update() > 0;
                if (bUpdateResult)
                { 
                    //保存操作记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.boxMachineId,
                        OperationTime = DateTime.Now,
                        Type = 54,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"删除套餐{detail.PlanId}，中的药品{detail._DrugInfo.DrugName}ID:{detail.DrugId}",
                    });
                    _connection.CommitTransaction();
                    return true;
                }
                else
                {
                    _connection.RollbackTransaction();
                    return false;
                }
                //}
                //else
                //{
                //    logger.Error($"套餐中的药品{detail._DrugInfo.DrugName}无绑定");
                //    return false;
                //}
            }
            catch (Exception ex)
            {
                logger.Error($"添加药品失败，错误：" + ex.Message);
                return false;
            }
        }

        public bool CheckDrugById(PlanDetails details)
        {
            if (details._DrugInfo.DrugId != null)
            {
                //查询该药品是否已在套餐中存在，存在则不再添加
                PlanDetails pdDrug = _connection.PlanDetails.Where(p => p.PlanId == details.PlanId && p.DrugId == details._DrugInfo.DrugId && p.UseState == 1).FirstOrDefault();

                if (details.Id > 0)
                {
                    //修改原数据
                    if (pdDrug != null && pdDrug.Id == details.Id)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    //新增数据
                    if (pdDrug != null)
                    {
                        return !(pdDrug.Id > 0);
                    }
                    else
                    {
                        return true;
                    }
                }
                //return !(hasCount > 0);
            }
            else
            {
                return true;
            }
        }

    }
}
