
using LinqToDB;
using log4net;
using MasaBlazorApp3.DataAccess.Dao;
using MasaBlazorApp3.Pages;
using MasaBlazorApp3.Pojo;
using MasaBlazorApp3.Pojo.Config;
using MasaBlazorApp3.Pojo.Vo;
using MasaBlazorApp3.Port;
using Microsoft.Extensions.Options;
using Mysqlx.Crud;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace MasaBlazorApp3.DataAccess.Impl
{
    public class ChannelListDao : IChannelListDao
    {

        private AppDataConnection _connection;
        private readonly SettingConfig _setting;
        private GlobalStateService _globalStateService;
        private readonly PortUtil _portUtil;

        private readonly ILog logger = LogManager.GetLogger(typeof(ChannelListDao));
        private readonly IServiceProvider _serviceProvider;
        public ChannelListDao(AppDataConnection connection, IOptions<SettingConfig> setting, GlobalStateService globalStateService, PortUtil portUtil)
        {
            _globalStateService = globalStateService;
            _connection = connection;
            _setting = setting.Value;
            _portUtil = portUtil;
        }

        public async Task<PageData<ChannelStock>> GetAllChannelList(int DrawerType, string drugName, int? take, int? skip)
        {

            var query = _connection.ChannelStock.AsQueryable();

            if (DrawerType != 0)
            {
                query = query.Where(cl => cl.DrawerType == DrawerType);
            }

            if (!String.IsNullOrEmpty(drugName))
            {
                query = query.Where(cl => cl.Drug.DrugName.Equals(drugName));
            }

            //query = query.Where(cl => !String.IsNullOrEmpty(cl.DrugId));
            query = query.Where(cl => cl.MachineId == _setting.machineId);


            int pagedData = await query.CountAsync();

            List<ChannelStock> list = await query
                .LoadWith(cl => cl.Drug)
                .LoadWith(cl => cl.Drug.Manus)
                .LoadWith(cl => cl.drugManuNo)
                .OrderBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.ColNo)
                .Skip((int)skip)
                .Take((int)take)
                .ToListAsync();


            return new PageData<ChannelStock>()
            {

                TotalDesserts = pagedData,
                Desserts = list
            };
        }

        public async Task<List<ChannelStock>> GetChannelStockByDrugId(string DrugId)
        {
            var query = _connection.ChannelStock.AsQueryable();


            return await query
                .LoadWith(cs => cs.Drug)
                .InnerJoin(
                    _connection.ChannelList.Where(cl => cl.MachineId.Equals(_setting.machineId)).Where(cl => cl.DrawerType == 1),
                    (cs, cl) => cs.ListId == cl.Id,
                    (cs, cl) => cs
                )
                .Where(cs => cs.DrugId == DrugId)
                .Where(cs => cs.MachineId == _setting.machineId)
                //.Where(cs => cs.Quantity > 0)
                .OrderBy((cs) => cs.EffDate)
                .ThenBy((cs) => cs.DrawerNo)
                .ThenBy((cs) => cs.ColNo)
                .ToListAsync();
        }

        public async Task<List<ChannelStock>> GetChannelStockByDrawerNo(int DrawerNo, int Quantity = 0)
        {
            var query = _connection.ChannelStock.AsQueryable()
                .LoadWith(cs => cs.Drug)
                .LoadWith(cs => cs.drugManuNo)
                .LoadWith(cs => cs.Drug.Manus)
                .Where(cs => cs.DrawerNo == DrawerNo)
                .Where(cs => cs.DrugId != String.Empty)
                .Where(cs => cs.DrawerType == 1)
                .Where(cs => cs.MachineId == _setting.machineId);

            if (Quantity > 0)
            {
                query = query.Where(cs => cs.Quantity > 0);
            }
            return await query
                .OrderBy((cs) => cs.DrawerNo)
                .ThenBy((cs) => cs.ColNo)
                .ToListAsync();
        }

        public async Task<List<ChannelList>> GetChannelListByDrawerNo(int DrawerNo)
        {
            var query = _connection.ChannelList.AsQueryable();


            return await query
                .LoadWith(cl => cl.Drug)
                .LoadWith(cl => cl.ChannelStocks.Where(cs => cs.Quantity > 0))
                .Where(cl => cl.DrawerNo == DrawerNo)
                .Where(cl => cl.DrawerType == 1)
                .Where(cl => cl.MachineId == _setting.machineId)
                .OrderBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.ColNo)
                .ToListAsync();
        }

        public async Task<List<ChannelStock>> GetAllDrugChannelStock()
        {
            var query = _connection.ChannelStock.AsQueryable();


            return await query
                .LoadWith(cs => cs.Drug)
                .Where(cs => !String.IsNullOrEmpty(cs.DrugId))
                .Where(cs => cs.DrawerType == 1)
                .Where(cs => cs.MachineId == _setting.machineId)
                .OrderBy((cs) => cs.DrugId)
                .ThenBy((cs) => cs.EffDate)
                .ThenBy((cs) => cs.DrawerNo)
                .ThenBy((cs) => cs.ColNo)
                .ToListAsync();
        }

        public async Task<List<ChannelList>> GetAllDrugChannelList()
        {
            var query = _connection.ChannelList.AsQueryable();


            return await query
                .LoadWith(cl => cl.Drug)
                .LoadWith(cl => cl.ChannelStocks)
                .Where(cl => !String.IsNullOrEmpty(cl.DrugId))
                .Where(cl => cl.DrawerType == 1)
                .Where(cl => cl.MachineId == _setting.machineId)
                .OrderBy((cl) => cl.DrugId)
                .ThenBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.ColNo)
                .ToListAsync();
        }

        public async Task<bool> DrawerOperationFinish(List<ChannelStock> Stocks, int type, BoxModel boxModel, List<ChannelList> channelLists)
        {
            try
            {
                _connection.BeginTransaction();

                string InvoiceId = "DRAWER_" + CurrentTimeMillis();
                var flag = true;
                for (var i = 0; i < Stocks.Count; i++)
                {
                    var stock = Stocks[i];

                    //var ManuNo = !stock.drugManuNo.ManuNo.Equals(stock.ManuNo) ? stock.drugManuNo.ManuNo : stock.ManuNo;
                    //var EffDate = !stock.drugManuNo.ManuNo.Equals(stock.ManuNo) ? stock.drugManuNo.EffDate : stock.EffDate;
                    var ManuNo = stock.ManuNo;
                    var EffDate = stock.EffDate;
                    if (!DateTime.TryParse(stock.EffDate, out DateTime dEffDate))
                    {
                        //效期转换出错
                        if (stock.ManuNo != null)
                        {
                            string[] idate = stock.EffDate.Split('/');
                            foreach (string iS in idate)
                            {
                                if (!string.IsNullOrEmpty(iS.Replace(" ", "").Trim()))
                                {
                                    switch (iS.Replace(" ", "").Trim().Length)
                                    {
                                        case 4:
                                            EffDate = iS.Replace(" ", "").Trim();
                                            break;
                                        case 2:
                                            EffDate += "-" + iS.Replace(" ", "").Trim();
                                            break;
                                        case 1:
                                            EffDate += "-0" + iS.Replace(" ", "").Trim();
                                            break;
                                    }
                                }
                            }


                        }
                    }
                    else
                    {
                        EffDate = dEffDate.ToString("yyyy-MM-dd");
                    }

                    // 出入库记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = stock.DrawerNo,
                        ColNo = stock.ColNo,
                        DrugId = stock.DrugId,
                        ManuNo = ManuNo,
                        EffDate = !String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = type,
                        Quantity = type == 1 ? stock.AddQuantity : stock.TakeQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = InvoiceId,
                        Status = type == 1 ? 0 : (boxModel != null) ? 0 : 2,
                        BoxDrawer = boxModel == null ? 0 : boxModel.BoxName,
                        BoxColNo = boxModel == null ? 0 : boxModel.BoxNo
                    });
                    // 更新库存
                    var stockQ = _connection.ChannelStock.Where(cs => cs.Id == stock.Id)
                        .Set(cs => cs.Quantity, type == 1 ? stock.Quantity + stock.AddQuantity : stock.Quantity - stock.TakeQuantity);
                    // 入库时如果库存为0则有可能会修改批次效期进行保存
                    if (type == 1 && stock.Quantity == 0 && !stock.drugManuNo.ManuNo.Equals(stock.ManuNo))
                    {
                        stockQ = stockQ.Set(cs => cs.ManuNo, stock.drugManuNo.ManuNo).Set(cs => cs.EffDate, stock.drugManuNo.EffDate?.ToString("yyyy-MM-dd")).Set(cs => cs.Dmnguid, stock.drugManuNo.Id);
                    }
                    int r = stockQ.Update();
                    // 获取更新完库存之后的药品库存
                    List<ChannelStock> list = await _connection.ChannelStock.AsQueryable()
                         .InnerJoin(
                             _connection.ChannelList.Where(cl => cl.MachineId.Equals(_setting.machineId)).Where(cl => cl.DrawerType == 1),
                             (cs, cl) => cs.ListId == cl.Id,
                             (cs, cl) => cs
                         )
                         .Where(cs => cs.DrugId.Equals(stock.DrugId))
                         .ToListAsync();
                    // 保存账册
                    int acid = _connection.InsertWithInt32Identity(new AccountBook()
                    {
                        MachineId = _setting.machineId,
                        DrugId = stock.DrugId,
                        ManuNo = ManuNo,
                        EffDate = !String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = type,
                        OutQuantity = stock.TakeQuantity,
                        AddQuantity = stock.AddQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        ManuStock = list.Where(it => it.ManuNo == stock.ManuNo).Sum(it => it.Quantity),
                        TotalStock = list.Sum(it => it.Quantity),
                        InvoiceId = InvoiceId
                    });
                    if (mid > 0 && r > 0 && acid > 0)
                    {

                    }
                    else
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {

                    if (boxModel != null)
                    {
                        //抽屉给药盒补药
                        var BoxChannelStock = Stocks.GroupBy(cs => new { cs.DrugId, cs.ManuNo, cs.EffDate }).Select(cs => new
                        {
                            cs.Key.DrugId,
                            cs.Key.ManuNo,
                            cs.Key.EffDate,
                            total = cs.Sum(it => it.TakeQuantity)
                        }).ToList();
                        foreach (var item in BoxChannelStock)
                        {
                            //查询本次加药的药盒里是否有该药品批次库存，有则累计加数量，无则insert记录
                            ChannelStock cs = _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == boxModel.BoxName && cs.ColNo == boxModel.BoxNo && cs.DrugId == item.DrugId && cs.ManuNo == item.ManuNo).FirstOrDefault();
                            if (cs != null)
                            {
                                //存在批次库存，更改数量
                                cs.Quantity += item.total;
                                int iUpdate = await _connection.UpdateAsync(cs);
                            }
                            else
                            {
                                //不存在批次库存，插入一条批次数据
                                // 保存账册
                                //查询新加的药是否是已绑定的套餐，是则将基数写入，不是则基数记为零
                                int baseQuantity = 0;
                                string listId = string.Empty;
                                ChannelStock csBase = _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == boxModel.BoxName && cs.ColNo == boxModel.BoxNo && cs.DrugId == item.DrugId).FirstOrDefault();
                                if (csBase != null)
                                {
                                    baseQuantity = csBase.CheckQuantity;
                                    listId = csBase.ListId;
                                }
                                int acid = _connection.InsertWithInt32Identity(new ChannelStock()
                                {
                                    Id = "DM5_" + Guid.NewGuid().ToString(),
                                    ListId = listId,
                                    MachineId = _setting.boxMachineId,
                                    DrugId = item.DrugId,
                                    ManuNo = item.ManuNo,
                                    EffDate = item.EffDate,
                                    DrawerNo = boxModel.BoxName,
                                    ColNo = boxModel.BoxNo,
                                    Quantity = item.total,
                                    BaseQuantity = baseQuantity
                                });
                            }
                            //将库存数加入channel_list表
                            ChannelList clList = _connection.ChannelList.Where(cl => cl.MachineId.Equals(_setting.boxMachineId) && cl.DrawerNo == boxModel.BoxName && cl.ColNo == boxModel.BoxNo).FirstOrDefault();
                            if (clList != null)
                            {
                                clList.TotalQuantity += item.total;
                                int iUpdate = await _connection.UpdateAsync(clList);
                                if (iUpdate <= 0)
                                {
                                    logger.Info($"抽屉加药记录药盒{boxModel.BoxName}-{boxModel.BoxNo}总库存失败，加药数量{item.total}");
                                }
                            }
                            //药盒中是否有未绑套餐且库存为0的数据，有则删除
                            _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && (string.IsNullOrEmpty(cs.ListId)) && cs.DrawerNo == boxModel.BoxName && cs.ColNo == boxModel.BoxNo && cs.Quantity <= 0).Delete();
                            //删除药盒中已绑套餐中同一药品多批次且库存为0的第一条数据
                            List<ChannelStock> delChannelStock = await _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == boxModel.BoxName && cs.ColNo == boxModel.BoxNo && cs.DrugId == item.DrugId).ToListAsync();
                            if (delChannelStock != null && delChannelStock.Count > 1)
                            {
                                //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                                //for (int i = 1; i < delChannelStock.Count; i++)
                                //{
                                //    _connection.Delete(delChannelStock[i]);
                                //}
                                //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                                List<ChannelStock> del = delChannelStock.Where(c => c.Quantity <= 0).ToList();
                                if (del != null && del.Count > 0)
                                {
                                    if (delChannelStock.Count == del.Count)
                                    {
                                        for (int j = 1; j < del.Count; j++)
                                        {
                                            _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                        }
                                    }
                                    else
                                    {
                                        for (int j = 0; j < del.Count; j++)
                                        {
                                            _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    _connection.CommitTransaction();
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;

            }
            catch (Exception ex)
            {
                logger.Error($"抽屉{(type == 1 ? "加药" : "取药")}操作完成保存数据库失败，错误：" + ex.Message);
                _connection.RollbackTransaction();
                return false;
            }
        }

        public long CurrentTimeMillis()
        {
            return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }

        public async Task<bool> UnBind(string id)
        {
            var r = await _connection.ChannelStock
                .Where(cs => cs.Id == id)
                .Set(cs => cs.DrugId, String.Empty)
                .Set(cs => cs.Dmnguid, String.Empty)
                .Set(cs => cs.EffDate, String.Empty)
                .Set(cs => cs.ManuNo, String.Empty)
                .UpdateAsync();
            return r > 0;
        }

        public async Task<bool> Bind(ChannelStock Stock)
        {
            var q = _connection.ChannelStock
                .Where(cs => cs.Id == Stock.Id)
                .Set(cs => cs.Dmnguid, Stock.drugManuNo?.Id ?? String.Empty)
                .Set(cs => cs.EffDate, Stock.drugManuNo?.EffDate.Value.ToString("yyyy-MM-dd") ?? String.Empty)
                .Set(cs => cs.ManuNo, Stock.drugManuNo?.ManuNo ?? String.Empty);

            if (Stock.Drug != null && !Stock.Drug.DrugId.Equals(Stock.DrugId))
            {
                q = q.Set(cs => cs.DrugId, Stock.Drug?.DrugId);
            }

            var r = await q.UpdateAsync();
            return r > 0;
        }
        public async Task<PageMultiData<ChannelStock, DrugInfo>> GetAllChannelListWithDrug(int DrawerType, string drugName, int? take, int? skip)
        {

            var query = _connection.ChannelStock.AsQueryable();

            if (DrawerType != 0)
            {
                query = query.Where(cl => cl.DrawerType == DrawerType);
            }

            if (!String.IsNullOrEmpty(drugName))
            {
                query = query.Where(cl => cl.Drug.DrugName.Equals(drugName));
            }

            //query = query.Where(cl => !String.IsNullOrEmpty(cl.DrugId));
            query = query.Where(cl => cl.MachineId == _setting.machineId);


            int pagedData = await query.CountAsync();

            List<ChannelStock> list = await query
                .LoadWith(cl => cl.Drug)
                .LoadWith(cl => cl.Drug.Manus)
                .LoadWith(cl => cl.drugManuNo)
                .OrderBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.ColNo)
                .Skip((int)skip)
                .Take((int)take)
                .ToListAsync();

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

            return new PageMultiData<ChannelStock, DrugInfo>()
            {

                TotalDesserts = pagedData,
                Desserts = list,
                Other = drugInfos
            };
        }
        //抽屉加药、取药获取数据
        public async Task<ChannelStockWithDrawerCount<ChannelStock>> GetChannelStockByDrawerNoWithDrawers(int DrawerNo, int Quantity = 0)
        {
            var query = _connection.ChannelStock.AsQueryable()
                .LoadWith(cs => cs.Drug)
                .LoadWith(cs => cs.drugManuNo)
                .LoadWith(cs => cs.Drug.Manus)
                .Where(cs => cs.DrawerNo == DrawerNo)
                .Where(cs => cs.DrugId != String.Empty)
                //.Where(cs => cs.DrawerType == 1)
                .Where(cs => cs.MachineId == _setting.machineId);

            if (Quantity > 0)
            {
                query = query.Where(cs => cs.Quantity > 0);
            }
            int[] ints = _connection.ChannelStock.Where(cs => cs.MachineId == _setting.machineId).GroupBy(cs => cs.DrawerNo).Select(cs => cs.Key).ToArray();
            List<ChannelStock> channelStocks = await query
                .OrderBy((cs) => cs.DrawerNo)
                .ThenBy((cs) => cs.ColNo)
                .ToListAsync();
            return new ChannelStockWithDrawerCount<ChannelStock>() { DrawerArray = ints, ChannelStocks = channelStocks };
        }
        //盘点
        public async Task<bool> DrawerCheckFinish(List<ChannelStock> Stocks)
        {
            try
            {
                _connection.BeginTransaction();

                string InvoiceId = "CHECK_" + CurrentTimeMillis();
                var flag = true;
                for (var i = 0; i < Stocks.Count; i++)
                {
                    var stock = Stocks[i];

                    //var ManuNo = !stock.drugManuNo.ManuNo.Equals(stock.ManuNo) ? stock.drugManuNo.ManuNo : stock.ManuNo;
                    //var EffDate = !stock.drugManuNo.ManuNo.Equals(stock.ManuNo) ? stock.drugManuNo.EffDate : stock.EffDate;
                    var ManuNo = stock.ManuNo;
                    var EffDate = stock.EffDate;
                    if (!DateTime.TryParse(stock.EffDate, out DateTime dEffDate))
                    {
                        //效期转换出错
                        if (stock.ManuNo != null)
                        {
                            string[] idate = stock.EffDate.Split('/');
                            foreach (string iS in idate)
                            {
                                if (!string.IsNullOrEmpty(iS.Replace(" ", "").Trim()))
                                {
                                    switch (iS.Replace(" ", "").Trim().Length)
                                    {
                                        case 4:
                                            EffDate = iS.Replace(" ", "").Trim();
                                            break;
                                        case 2:
                                            EffDate += "-" + iS.Replace(" ", "").Trim();
                                            break;
                                        case 1:
                                            EffDate += "-0" + iS.Replace(" ", "").Trim();
                                            break;
                                    }
                                }
                            }


                        }
                    }
                    else
                    {
                        EffDate = dEffDate.ToString("yyyy-MM-dd");
                    }
                    // 出入库记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = stock.DrawerNo,
                        ColNo = stock.ColNo,
                        DrugId = stock.DrugId,
                        ManuNo = ManuNo,
                        EffDate = !String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = 4,
                        Quantity = stock.CheckQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = InvoiceId
                    });
                    // 更新库存
                    var stockQ = _connection.ChannelStock.Where(cs => cs.Id == stock.Id)
                        .Set(cs => cs.Quantity, stock.CheckQuantity)
                        .Set(cs => cs.ManuNo, ManuNo)
                        .Set(cs => cs.EffDate, EffDate)
                        .Set(cs => cs.Dmnguid, stock.drugManuNo?.Id);

                    int r = stockQ.Update();
                    // 获取更新完库存之后的药品库存
                    List<ChannelStock> list = await _connection.ChannelStock.AsQueryable()
                         .InnerJoin(
                             _connection.ChannelList.Where(cl => cl.MachineId.Equals(_setting.machineId)).Where(cl => cl.DrawerType == 1),
                             (cs, cl) => cs.ListId == cl.Id,
                             (cs, cl) => cs
                         )
                         .Where(cs => cs.DrugId.Equals(stock.DrugId))
                         .ToListAsync();
                    // 保存账册
                    int acid = _connection.InsertWithInt32Identity(new AccountBook()
                    {
                        MachineId = _setting.machineId,
                        DrugId = stock.DrugId,
                        ManuNo = ManuNo,
                        EffDate = !String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = 3,
                        OutQuantity = stock.TakeQuantity,
                        AddQuantity = stock.AddQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        ManuStock = list.Where(it => it.ManuNo == stock.ManuNo).Sum(it => it.Quantity),
                        TotalStock = list.Sum(it => it.Quantity),
                        InvoiceId = InvoiceId
                    });
                    if (mid > 0 && r > 0 && acid > 0)
                    {
                        //根据抽屉类型判断是否需要写标签
                        if (stock.BoardType.ToString().Contains("5"))
                        {
                            await _portUtil.WriteQuantityMethod(stock.CheckQuantity, stock.DrawerNo, stock.ColNo);
                        }
                    }
                    else
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    _connection.CommitTransaction();
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;

            }
            catch (Exception ex)
            {
                logger.Error($"抽屉盘点操作完成保存数据库失败，错误：" + ex.Message);
                _connection.RollbackTransaction();
                return false;
            }
        }

        //抽屉获取库存数据--药品绑定
        public async Task<ChannelStockWithDrawerCount<ChannelStock>> GetChannelStockByBiaoDing(int DrawerNo, int Quantity = 0)
        {
            var query = _connection.ChannelStock.AsQueryable()
                .LoadWith(cs => cs.Drug)
                .LoadWith(cs => cs.drugManuNo)
                .LoadWith(cs => cs.Drug.Manus)
                .Where(cs => cs.DrawerType == 1)
                .Where(cs => cs.MachineId == _setting.machineId);

            if (DrawerNo > 0)
            {
                query = query.Where(cs => cs.DrawerNo == DrawerNo);
            }
            int[] ints = _connection.ChannelStock.Where(cs => cs.MachineId == _setting.machineId).GroupBy(cs => cs.DrawerNo).Select(cs => cs.Key).ToArray();


            List<ChannelStock> channelStocks = await query
                .OrderBy((cs) => cs.DrawerNo)
                .ThenBy((cs) => cs.ColNo)
                .ToListAsync();
            return new ChannelStockWithDrawerCount<ChannelStock>() { DrawerArray = ints, ChannelStocks = channelStocks };
        }
        //手术室药盒获取绑定数据
        public async Task<PageMultiData<ChannelList, Plan>> GetAllChannelListWithPlan(int? take, int? skip)
        {

            var query = _connection.ChannelList.AsQueryable()
                .Where(cl => cl.MachineId == _setting.boxMachineId);
            //.LoadWith(cl=>cl.PlanInfo);


            int pagedData = await query.CountAsync();

            List<ChannelList> list = await query
                .OrderBy((cl) => cl.DrawerNo)
                .Skip((int)skip)
                .Take((int)take)
                .ToListAsync();
            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    if (!string.IsNullOrEmpty(list[i].DrugId))
                    {
                        list[i].PlanInfo = _connection.Plan.AsQueryable().Where(p => p.Id == Convert.ToInt32(list[i].DrugId)).FirstOrDefault();
                    }
                    list[i].BoxDisabled = list[i].TotalQuantity > 0 ? true : false;
                }
            }

            var other = _connection.Plan.AsQueryable().Where(p => p.UseState == 1 && p._PlanDetails.Count > 0);
            List<Plan> planInfos = await other
                .LoadWith(p => p._PlanDetails.Where(pd => pd.UseState == 1))
                .OrderBy((p) => p.Id)
                .ToListAsync();
            if (planInfos != null && planInfos.Count > 0)
            {
                for (int i = 0; i < planInfos.Count(); i++)
                {
                    for (int j = 0; j < planInfos[i]._PlanDetails.Count(); j++)
                    {
                        planInfos[i]._PlanDetails[j]._DrugInfo =
                             _connection.DrugInfo.AsQueryable().Where(di => di.DrugId == planInfos[i]._PlanDetails[j].DrugId).First();

                    }
                }
            }

            return new PageMultiData<ChannelList, Plan>()
            {

                TotalDesserts = pagedData,
                Desserts = list,
                Other = planInfos
            };
        }
        /// <summary>
        /// 手术室药盒绑定套餐
        /// </summary>
        /// <returns></returns>
        public async Task<bool> BindBox(ChannelList list, Plan plan)
        {
            try
            {
                _connection.BeginTransaction();
                bool bFlag = true;

                var q = _connection.ChannelList
                    .Where(cs => cs.Id == list.Id).Set(cs => cs.DrugId, plan.Id.ToString());
                //将套餐中的药品信息写入channelStock
                //查询套餐中药品信息
                var query = _connection.PlanDetails.AsQueryable().Where(p => p.PlanId == plan.Id && p.UseState == 1);
                List<PlanDetails> planInfos = await query.ToListAsync();
                if (planInfos != null && planInfos.Count > 0)
                {
                    for (int i = 0; i < planInfos.Count; i++)
                    {
                        int mid = await _connection.InsertAsync(new ChannelStock()
                        {
                            Id = Guid.NewGuid().ToString(),
                            ListId = list.Id,
                            MachineId = list.MachineId,
                            DrawerNo = list.DrawerNo,
                            ColNo = list.ColNo,
                            DrugId = planInfos[i].DrugId.ToString(),
                            BaseQuantity = planInfos[i].BaseQuantity,
                            //BoxState = 1
                        });
                        if (mid > 0)
                        {
                            bFlag = true;
                        }
                        else
                        {
                            bFlag = false;
                            break;
                        }
                    }
                }
                var r = await q.UpdateAsync();
                if (bFlag && r > 0)
                {
                    //保存操作记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = list.DrawerNo,
                        ColNo = list.ColNo,
                        DrugId = list.DrugId,
                        OperationTime = DateTime.Now,
                        Type = 55,
                        Quantity = list.TotalQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"药盒{list.DrawerNo}绑定套餐{list.DrugId}",
                        //GetId = operationVo.data.Id
                    });
                    _connection.CommitTransaction();
                    return true;
                }
                else
                {
                    _connection.RollbackTransaction();
                    return false;
                }
            }
            catch (Exception ex)
            {
                _connection.RollbackTransaction();
                logger.Info($"绑定套餐异常{ex.Message}");
                return false;
            }
        }
        /// <summary>
        /// 手术室药盒绑定套餐
        /// </summary>
        /// <returns></returns>
        public async Task<bool> BindBox(ChannelList list)
        {
            try
            {
                _connection.BeginTransaction();
                bool bFlag = true;

                var q = _connection.ChannelList
                    .Where(cs => cs.Id == list.Id).Set(cs => cs.DrugId, list.PlanInfo.Id.ToString());
                //将套餐中的药品信息写入channelStock
                //查询套餐中药品信息
                var query = _connection.PlanDetails.AsQueryable().Where(p => p.PlanId == list.PlanInfo.Id && p.UseState == 1);
                List<PlanDetails> planInfos = await query.ToListAsync();
                if (planInfos != null && planInfos.Count > 0)
                {
                    for (int i = 0; i < planInfos.Count; i++)
                    {
                        int mid = await _connection.InsertAsync(new ChannelStock()
                        {
                            Id = Guid.NewGuid().ToString(),
                            ListId = list.Id,
                            MachineId = list.MachineId,
                            DrawerNo = list.DrawerNo,
                            ColNo = list.ColNo,
                            DrugId = planInfos[i].DrugId.ToString(),
                            BaseQuantity = planInfos[i].BaseQuantity,
                            //BoxState = 1
                        });
                        if (mid > 0)
                        {
                            bFlag = true;
                        }
                        else
                        {
                            bFlag = false;
                            break;
                        }
                    }
                }
                var r = await q.UpdateAsync();
                if (bFlag && r > 0)
                {
                    //保存操作记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = list.DrawerNo,
                        ColNo = list.ColNo,
                        DrugId = list.DrugId,
                        OperationTime = DateTime.Now,
                        Type = 55,
                        Quantity = list.TotalQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"药盒{list.DrawerNo}绑定套餐{list.DrugId}",
                        //GetId = operationVo.data.Id
                    });
                    _connection.CommitTransaction();
                    return true;
                }
                else
                {
                    _connection.RollbackTransaction();
                    return false;
                }
            }
            catch (Exception ex)
            {
                _connection.RollbackTransaction();
                logger.Info($"绑定套餐异常{ex.Message}");
                return false;
            }
        }
        /// <summary>
        /// 手术室药盒解绑套餐
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<bool> UnBindBox(ChannelList list)
        {
            try
            {
                _connection.BeginTransaction();

                var r = await _connection.ChannelList
                     .Where(cs => cs.Id == list.Id)
                     .Set(cs => cs.DrugId, String.Empty)
                     .UpdateAsync();
                int iCount = await _connection.ChannelStock.Where(cs => cs.ListId == list.Id).CountAsync();
                int cs = 0;
                if (iCount > 0)
                {
                    cs = await _connection.ChannelStock.Where(cs => cs.ListId == list.Id).DeleteAsync();
                }
                if (r > 0 && (iCount > 0 && cs > 0 || iCount <= 0))
                {
                    //保存操作记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = list.DrawerNo,
                        ColNo = list.ColNo,
                        DrugId = list.DrugId,
                        OperationTime = DateTime.Now,
                        Type = 56,
                        Quantity = list.TotalQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"药盒{list.DrawerNo}解绑套餐{list.DrugId}",
                        //GetId = operationVo.data.Id
                    });
                    _connection.CommitTransaction();
                    return true;
                }
                else
                {
                    _connection.RollbackTransaction();
                    return false;
                }
            }
            catch (Exception ex)
            {
                _connection.RollbackTransaction();
                logger.Info($"手术室药盒解绑异常：{ex.Message}");
                return false;
            }
        }
        //获取手术室药盒中所有要补药的数据
        public async Task<PageData<ChannelList>> GetAllBoxAddDrug(int? take, int? skip)
        {
            try
            {
                List<ChannelList> channelLists = new List<ChannelList>();
                var query = _connection.ChannelStock//.AsQueryable()
                .Where(cs => cs.MachineId == _setting.boxMachineId)
                .GroupBy(cs => new { cs.DrawerNo, cs.ColNo, cs.DrugId })
                .Select(g => new
                {
                    DrawerNo = g.Key.DrawerNo,
                    DrugId = g.Key.DrugId,
                    ColNo = g.Key.ColNo,
                    sumQuantity = g.Sum(cs => cs.Quantity),
                    baseQuantity = g.Max(cs => cs.BaseQuantity),
                    sumAdd = g.Sum(cs => cs.AddToQuantity)
                }).Where(x => x.baseQuantity > x.sumQuantity + x.sumAdd)
                .ToList();

                var queryChannelStock = _connection.ChannelStock.AsQueryable()
               .Where(cs => cs.MachineId == _setting.boxMachineId)
               .LoadWith(cs => cs.Drug).ToList();


                var queryList = await _connection.ChannelList.AsQueryable().Where(cl => cl.MachineId == _setting.boxMachineId).ToListAsync();
                for (int i = 0; i < queryList.Count; i++)
                {
                    foreach (var item in query)
                    {
                        if (queryList[i].DrawerNo == item.DrawerNo && queryList[i].ColNo == item.ColNo)
                        {
                            ChannelStock stock = queryChannelStock.Where(cs => cs.DrawerNo == item.DrawerNo && cs.ColNo == item.ColNo && cs.DrugId == item.DrugId && cs.BaseQuantity > item.sumQuantity).FirstOrDefault();
                            if (stock != null)
                            {
                                stock.NeedQuantity = stock.BaseQuantity - item.sumQuantity;
                                queryList[i].ChannelStocks.Add(stock);
                            }
                        }
                    }
                    if (queryList[i].ChannelStocks != null && queryList[i].ChannelStocks.Count > 0)
                    {
                        channelLists.Add(queryList[i]);
                    }
                }

                //if (query != null && query.Count > 0)
                //{
                //    var queryList = await _connection.ChannelList.AsQueryable().Where(cl => cl.MachineId == _setting.boxMachineId).ToListAsync();
                //    for (int i = 0; i < queryList.Count; i++)
                //    {
                //        foreach (var item in query)
                //        {
                //            if (queryList[i].DrawerNo == item.DrawerNo)

                //            {
                //                ChannelStock? stock = _connection.ChannelStock.AsQueryable()
                //                    .Where(cs => cs.MachineId == _setting.boxMachineId && cs.DrawerNo == item.DrawerNo && cs.DrugId == item.DrugId).LoadWith(cs => cs.Drug).FirstOrDefault();
                //                stock.NeedQuantity = item.baseQuantity - item.sumQuantity;
                //                queryList[i].ChannelStocks.Add(stock);
                //            }
                //        }
                //        if (queryList[i].ChannelStocks != null && queryList[i].ChannelStocks.Count > 0)
                //        {
                //            channelLists.Add(queryList[i]);
                //        }
                //    }
                //}


                int pagedData = channelLists.Count;




                return new PageData<ChannelList>()
                {

                    TotalDesserts = pagedData,
                    Desserts = channelLists
                };
            }
            catch (Exception ex)
            {
                logger.Info($"获取药盒中补药数据失败{ex.Message}");
                return null;
            }
        }

        //手术室药盒补药获取毒麻柜中的药品信息
        public async Task<List<BoxTakeVo>> getTakeInfoByBox(ChannelList cl)
        {
            try
            {
                List<BoxTakeVo> tempData = new();
                List<BoxTakeVo> tempData2 = new();
                var flag = true;
                for (int i = 0; i < cl.ChannelStocks.Count; i++)
                {
                    ChannelStock boxCs = cl.ChannelStocks[i];
                    // 当前药品取药数量
                    var Quantity = boxCs.NeedQuantity;
                    List<ChannelStock> stockList = await _connection.ChannelStock
                        .Where(cs => cs.MachineId == _setting.machineId && cs.DrawerType == 1 && cs.DrugId == boxCs.DrugId && cs.Quantity > 0 && cs.ManuNo != null)
                        .AsQueryable()
                        .OrderBy(cs => new { cs.EffDate, cs.Quantity }).ToListAsync();

                    // 当前药品的库存总量
                    var total = stockList.Sum(current => current.Quantity);

                    tempData2.Add(new BoxTakeVo()
                    {
                        Drug = boxCs.Drug,
                        StockQuantity = total,
                        Quantity = Quantity
                    });

                    if (flag)
                    {
                        // 盘点库存是否足够
                        if (total >= Quantity)
                        {

                            for (var j = 0; Quantity > 0; j++)
                            {
                                ChannelStock stock = stockList[j];
                                if (Quantity > stock.Quantity)
                                {
                                    // 取药数量大于库存
                                    tempData.Add(new BoxTakeVo()
                                    {
                                        Drug = boxCs.Drug,
                                        BoxDetail = boxCs,
                                        ChannelStock = stock,
                                        StockQuantity = total,
                                        Quantity = stock.Quantity,
                                    });
                                    Quantity -= stock.Quantity;
                                }
                                else
                                {
                                    //取药数量小于库存
                                    tempData.Add(new BoxTakeVo()
                                    {
                                        Drug = boxCs.Drug,
                                        BoxDetail = boxCs,
                                        ChannelStock = stock,
                                        StockQuantity = total,
                                        Quantity = Quantity,
                                    });
                                    Quantity = 0;
                                }
                            }
                        }
                        else
                        {
                            // 库存不足
                            flag = false;
                        }
                    }
                }
                if (flag)
                {
                    tempData.Sort((s1, s3) =>
                    {
                        int i = s1.ChannelStock.DrawerNo.CompareTo(s3.ChannelStock.DrawerNo);
                        if (i == 0)
                        {
                            return s1.ChannelStock.ColNo.CompareTo(s3.ChannelStock.ColNo);
                        }
                        return i;
                    });
                    return tempData;
                }
                else
                {
                    return tempData2;
                }

            }
            catch (Exception ex)
            {
                logger.Info($"获取数据异常{ex.Message}");
                return null;
            }
        }
        //手术室药盒补药完成
        public async Task<bool> BoxTakeFinish(List<BoxTakeVo> datas, ChannelList boxChannelList)
        {

            try
            {
                _connection.BeginTransaction();
                var flag = true;
                for (var i = 0; i < datas.Count; i++)
                {
                    var boxTakeVo = datas[i];
                    var EffDate = boxTakeVo.ChannelStock.EffDate;
                    if (!DateTime.TryParse(boxTakeVo.ChannelStock.EffDate, out DateTime dEffDate))
                    {
                        //效期转换出错
                        if (boxTakeVo.ChannelStock.EffDate != null)
                        {
                            string[] idate = boxTakeVo.ChannelStock.EffDate.Split('/');
                            foreach (string iS in idate)
                            {
                                if (!string.IsNullOrEmpty(iS.Trim()))
                                {
                                    switch (iS.Trim().Length)
                                    {
                                        case 4:
                                            EffDate = iS.Trim();
                                            break;
                                        case 2:
                                            EffDate += "-" + iS.Trim();
                                            break;
                                        case 1:
                                            EffDate += "-0" + iS.Trim();
                                            break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        EffDate = dEffDate.ToString("yyyy-MM-dd");
                    }
                    // 出库记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = boxTakeVo.ChannelStock.DrawerNo,
                        ColNo = boxTakeVo.ChannelStock.ColNo,
                        DrugId = boxTakeVo.ChannelStock.DrugId,
                        ManuNo = boxTakeVo.ChannelStock.ManuNo,
                        EffDate = !String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = 2,
                        Status = 2,//给交接柜补药不需要还药或还空瓶
                        Quantity = boxTakeVo.GetQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = boxTakeVo.BoxDetail.Id.ToString(),
                    });
                    // 更新库存
                    int r = _connection.ChannelStock.Where(cs => cs.Id == boxTakeVo.ChannelStock.Id)
                        .Set(cs => cs.Quantity, boxTakeVo.ChannelStock.Quantity - boxTakeVo.GetQuantity)
                        .Update();
                    #region 保存账册,给药盒补药不记录出库账册
                    // 获取更新完库存之后的药品库存
                    //List<ChannelStock> list = await _connection.ChannelStock.AsQueryable()
                    //     .InnerJoin(
                    //         _connection.ChannelList.Where(cl => cl.MachineId.Equals(_setting.machineId)).Where(cl => cl.DrawerType == 1),
                    //         (cs, cl) => cs.ListId == cl.Id,
                    //         (cs, cl) => cs
                    //     )
                    //     .Where(cs => cs.DrugId.Equals(boxTakeVo.ChannelStock.DrugId))
                    //     .ToListAsync();
                    // 保存账册,给药盒补药不记录出库账册
                    //int acid = _connection.InsertWithInt32Identity(new AccountBook()
                    //{
                    //    MachineId = _setting.machineId,
                    //    DrugId = boxTakeVo.ChannelStock.DrugId,
                    //    ManuNo = boxTakeVo.ChannelStock.ManuNo,
                    //    EffDate = !String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                    //    OperationTime = DateTime.Now,
                    //    Type = 2,
                    //    OutQuantity = boxTakeVo.GetQuantity,
                    //    AddQuantity = 0,
                    //    Operator = _globalStateService.Operator.Id,
                    //    Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                    //    ManuStock = list.Where(it => it.ManuNo == boxTakeVo.ChannelStock.ManuNo).Sum(it => it.Quantity),
                    //    TotalStock = list.Sum(it => it.Quantity),
                    //    //InvoiceId = orderTakeVo.OrderDetail.Id.ToString()
                    //});
                    #endregion
                    //查询药盒中是否有该批次药品，有则把对应数量累加，无则insert
                    ChannelStock? BoxChannelStock = _connection.ChannelStock.AsQueryable()
                        .Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == boxTakeVo.BoxDetail.DrawerNo && cs.ColNo == boxTakeVo.BoxDetail.ColNo && cs.DrugId == boxTakeVo.ChannelStock.DrugId && cs.ManuNo == boxTakeVo.ChannelStock.ManuNo && cs.EffDate == EffDate).FirstOrDefault();
                    int boxID = 0;
                    if (BoxChannelStock != null)
                    {
                        //BoxChannelStock.AddToQuantity += boxTakeVo.GetQuantity;
                        //BoxChannelStock.BoxState = 2;
                        //改为直接加到药盒库存中
                        BoxChannelStock.Quantity += boxTakeVo.GetQuantity;
                        boxID = await _connection.UpdateAsync(BoxChannelStock);
                    }
                    else
                    {
                        //更新药盒中的药品数量
                        boxID = _connection.Insert(new ChannelStock()
                        {
                            Id = Guid.NewGuid().ToString(),
                            ListId = boxTakeVo.BoxDetail.ListId,
                            MachineId = _setting.boxMachineId,
                            DrawerNo = boxTakeVo.BoxDetail.DrawerNo,
                            ColNo = boxTakeVo.BoxDetail.ColNo,
                            //AddToQuantity = boxTakeVo.Quantity,//boxTakeVo.GetQuantity,
                            //NeedQuantity = 0,
                            Quantity = boxTakeVo.GetQuantity,
                            DrugId = boxTakeVo.ChannelStock.DrugId,
                            ManuNo = boxTakeVo.ChannelStock.ManuNo,
                            EffDate = EffDate,
                            BaseQuantity = boxTakeVo.BoxDetail.BaseQuantity,
                            BoardType = boxTakeVo.BoxDetail.BoardType,
                            //BoxState = 2, //补药完成
                            FillTime = DateTime.Now
                        });
                    }
                    // 手术室药盒入库记录
                    int boxMId = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = boxTakeVo.BoxDetail.DrawerNo,
                        ColNo = boxTakeVo.BoxDetail.ColNo,
                        DrugId = boxTakeVo.ChannelStock.DrugId,
                        ManuNo = boxTakeVo.ChannelStock.ManuNo,
                        EffDate = !String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = 1,
                        Quantity = boxTakeVo.GetQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = boxTakeVo.ChannelStock.Id.ToString(),
                    });
                    int delResutl = await _connection.ChannelStock.Where(cs => cs.MachineId == boxTakeVo.BoxDetail.MachineId && cs.DrugId == boxTakeVo.BoxDetail.DrugId && cs.DrawerNo == boxTakeVo.BoxDetail.DrawerNo && cs.ColNo == boxTakeVo.BoxDetail.ColNo && cs.ManuNo == null).DeleteAsync();
                    if (mid > 0 && r > 0 && boxID > 0 && boxMId > 0)
                    {
                        if (boxTakeVo.ChannelStock.BoardType.ToString().Contains("5"))
                        {
                            await _portUtil.WriteQuantityMethod(boxTakeVo.ChannelStock.Quantity - boxTakeVo.GetQuantity, boxTakeVo.ChannelStock.DrawerNo, boxTakeVo.ChannelStock.ColNo);
                        }

                    }
                    else
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    int totalQuantity = boxChannelList.TotalQuantity + datas.Sum(it => it.GetQuantity);
                    int list = _connection.ChannelList.Where(cl => cl.Id == boxChannelList.Id)
                        .Set(cl => cl.TotalQuantity, totalQuantity)
                        .Update();
                    _connection.CommitTransaction();
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;

            }
            catch (Exception ex)
            {
                logger.Error("处方取药完成保存数据库失败，错误：" + ex.Message);
                _connection.RollbackTransaction();
                return false;
            }
        }


        //手术室药盒入库
        public async Task<PageData<ChannelList>> GetBoxWaitInfo(int? take, int? skip)
        {
            try
            {
                List<ChannelList> channelLists = new List<ChannelList>();
                var query = _connection.ChannelStock//.AsQueryable()
                .Where(cs => cs.MachineId == _setting.boxMachineId)
                .GroupBy(cs => new { cs.DrawerNo, cs.DrugId })
                .Select(g => new
                {
                    DrawerNo = g.Key.DrawerNo,
                    DrugId = g.Key.DrugId,
                    sumQuantity = g.Sum(cs => cs.Quantity),
                    baseQuantity = g.Max(cs => cs.BaseQuantity),
                    AddToQuantity = g.Sum(cs => cs.AddToQuantity)
                }).Where(x => x.baseQuantity > x.sumQuantity)
                .ToList();

                var queryChannelStock = _connection.ChannelStock.AsQueryable()
               .Where(cs => cs.MachineId == _setting.boxMachineId && cs.BoxState == 2)
               .LoadWith(cs => cs.Drug).ToList();


                var queryList = await _connection.ChannelList.AsQueryable().Where(cl => cl.MachineId == _setting.boxMachineId).ToListAsync();
                for (int i = 0; i < queryList.Count; i++)
                {
                    foreach (var item in query)
                    {
                        if (queryList[i].DrawerNo == item.DrawerNo)
                        {
                            ChannelStock? stock = queryChannelStock.Where(cs => cs.DrawerNo == item.DrawerNo && cs.DrugId == item.DrugId && cs.BaseQuantity > item.sumQuantity).FirstOrDefault();
                            if (stock != null)
                            {
                                stock.NeedQuantity = stock.BaseQuantity - item.sumQuantity;
                                stock.AddToQuantity = item.AddToQuantity;
                                queryList[i].ChannelStocks.Add(stock);
                            }
                        }
                    }
                    if (queryList[i].ChannelStocks != null && queryList[i].ChannelStocks.Count > 0)
                    {
                        channelLists.Add(queryList[i]);
                    }
                }
                int pagedData = channelLists.Count;




                return new PageData<ChannelList>()
                {

                    TotalDesserts = pagedData,
                    Desserts = channelLists
                };
            }
            catch (Exception ex)
            {
                logger.Info($"获取药盒中补药数据失败{ex.Message}");
                return null;
            }
        }
        // 药盒入库弹窗页面获取要入库的药品明细信息
        public async Task<List<ChannelStock>> GetBoxAddToBox(ChannelList cl)
        {
            if (cl != null)
            {
                List<DrugManuNo> manuNosList = new List<DrugManuNo>();
                foreach (var item in cl.ChannelStocks)
                {
                    List<DrugManuNo> manuList = new List<DrugManuNo>();
                    List<ChannelStock> csList = _connection.ChannelStock.Where(cs => cs.DrawerNo == item.DrawerNo && cs.DrugId == item.DrugId && cs.BoxState == 2).ToList();
                    for (int i = 0; i < csList.Count; i++)
                    {
                        var existingItem = manuList.FirstOrDefault(item => item.DrugId == csList[i].DrugId && item.ManuNo == csList[i].ManuNo && item.EffDate.ToString() == csList[i].EffDate);
                        if (existingItem != null)
                        {
                            existingItem.Quantity += csList[i].AddToQuantity;
                        }
                        else
                        {
                            DrugManuNo manu = new DrugManuNo();
                            manu.DrugId = csList[i].DrugId;
                            manu.ManuNo = csList[i].ManuNo;
                            manu.EffDate = Convert.ToDateTime(csList[i].EffDate);
                            manu.Quantity = csList[i].AddToQuantity;
                            manuList.Add(manu);
                        }
                    }
                    item.drugManuNoList = manuList;
                }
            }
            return cl.ChannelStocks;
        }
        //手术室药盒入库获取待入库明细
        public async Task<List<BoxTakeVo>> getBoxWaitByBox(ChannelList cl, int? take, int? skip)
        {
            try
            {
                List<BoxTakeVo> tempData = new();
                List<BoxTakeVo> tempData2 = new();
                var flag = true;
                for (int i = 0; i < cl.ChannelStocks.Count; i++)
                {
                    ChannelStock boxCs = cl.ChannelStocks[i];
                    // 当前药品取药数量
                    var Quantity = boxCs.NeedQuantity;
                    List<ChannelStock> stockList = await _connection.ChannelStock
                        .Where(cs => cs.MachineId == _setting.boxMachineId && cs.DrugId == boxCs.DrugId && cs.Quantity > 0 && cs.ManuNo != null)
                        .AsQueryable()
                        .Skip((int)skip)
                        .Take((int)take)
                        .OrderBy(cs => cs.EffDate).ToListAsync();

                    // 当前药品的库存总量
                    var total = stockList.Sum(current => current.Quantity);

                    tempData2.Add(new BoxTakeVo()
                    {
                        Drug = boxCs.Drug,
                        StockQuantity = total,
                        Quantity = Quantity
                    });
                }
                return tempData;

            }
            catch (Exception ex)
            {
                logger.Info($"获取数据异常{ex.Message}");
                return null;
            }
        }
        // 手术室药盒待入库明细入库完成
        public async Task<bool> BoxAddBoxFinish(ChannelList boxChannelList)
        {
            try
            {
                _connection.BeginTransaction();
                bool flag = true;
                int totalQuantity = 0;
                for (var i = 0; i < boxChannelList.ChannelStocks.Count; i++)
                {
                    for (int j = 0; j < boxChannelList.ChannelStocks[i].drugManuNoList.Count; j++)
                    {
                        var EffDate = boxChannelList.ChannelStocks[i].drugManuNoList[j].EffDate?.ToString("yyyy-MM-dd");
                        //效期转换出错
                        //if (boxChannelList.ChannelStocks[i].EffDate != null)
                        //{
                        //    string[] idate = boxChannelList.ChannelStocks[i].EffDate.Split('/');
                        //    foreach (string iS in idate)
                        //    {
                        //        if (!string.IsNullOrEmpty(iS.Trim()))
                        //        {
                        //            switch (iS.Trim().Length)
                        //            {
                        //                case 4:
                        //                    EffDate = iS.Trim();
                        //                    break;
                        //                case 2:
                        //                    EffDate += "-" + iS.Trim();
                        //                    break;
                        //                case 1:
                        //                    EffDate += "-0" + iS.Trim();
                        //                    break;
                        //            }
                        //        }
                        //    }
                        //}
                        // 手术室药盒入库记录
                        int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                        {
                            MachineId = _setting.boxMachineId,
                            DrawerNo = boxChannelList.ChannelStocks[i].DrawerNo,
                            DrugId = boxChannelList.ChannelStocks[i].DrugId,
                            ManuNo = boxChannelList.ChannelStocks[i].drugManuNoList[j].ManuNo,
                            EffDate = boxChannelList.ChannelStocks[i].drugManuNoList[j].EffDate,//!String.IsNullOrEmpty(EffDate) ? DateTime.ParseExact(EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                            OperationTime = DateTime.Now,
                            Type = 1,
                            Quantity = boxChannelList.ChannelStocks[i].drugManuNoList[j].Quantity,
                            Operator = _globalStateService.Operator.Id,
                            Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                            InvoiceId = boxChannelList.ChannelStocks[i].Id.ToString(),
                        });
                        // 更新库存
                        ChannelStock? updateChannelStock = _connection.ChannelStock.AsQueryable()
                            .Where(cs => cs.DrawerNo == boxChannelList.ChannelStocks[i].DrawerNo && cs.DrugId == boxChannelList.ChannelStocks[i].drugManuNoList[j].DrugId && cs.ManuNo == boxChannelList.ChannelStocks[i].drugManuNoList[j].ManuNo && cs.EffDate == EffDate)
                            .FirstOrDefault();
                        int r = 0;
                        if (updateChannelStock != null)
                        {
                            updateChannelStock.Quantity = updateChannelStock.Quantity + boxChannelList.ChannelStocks[i].drugManuNoList[j].Quantity;
                            updateChannelStock.AddToQuantity = 0;
                            updateChannelStock.NeedQuantity = 0;
                            updateChannelStock.BoxState = 0;
                            //updateChannelStock.EffDate = EffDate?.ToString("yyyy-MM-dd");
                            //updateChannelStock.ManuNo = boxChannelList.ChannelStocks[i].drugManuNoList[j].ManuNo;
                            r = _connection.Update(updateChannelStock);

                        }

                        //totalQuantity += _connection.PlanDetails.Where(p => p.PlanId == Convert.ToInt32(boxChannelList.DrugId) && p.DrugId == boxChannelList.ChannelStocks[i].DrugId).Sum(p => p.BaseQuantity);
                        totalQuantity += boxChannelList.ChannelStocks[i].drugManuNoList[j].Quantity;

                        if (!(mid > 0 && (updateChannelStock == null || r > 0)))
                        {
                            flag = false;
                            break;
                        }

                    }
                }
                if (flag)
                {
                    boxChannelList.TotalQuantity += totalQuantity;
                    int updateResult = _connection
                        .Update(boxChannelList);
                    if (updateResult > 0)
                    {
                        _connection.CommitTransaction();
                    }
                    else
                    {
                        flag = false;
                        _connection.RollbackTransaction();
                    }
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;
            }
            catch (Exception ex)
            {
                logger.Info($"手术室药盒待入库明细入库完成操作异常：{ex.Message}");
                return false;
            }
        }

        //手术室药盒获取药盒药品及库存信息
        public async Task<PageData<PlanDetails>> GetBoxDrugInfo(string strDrawerNoCol, int? take, int? skip)
        {
            if (!string.IsNullOrEmpty(strDrawerNoCol))
            {
                int drawerNo = 0;
                int colNo = 0;
                var spl = strDrawerNoCol.Split('-');
                if (spl != null && spl.Count() > 0)
                {
                    drawerNo = Convert.ToInt32(spl[0]);
                    colNo = Convert.ToInt32(spl[1]);
                }

                var query = _connection.PlanDetails.AsQueryable()
                    .InnerJoin(
                    _connection.ChannelList.Where(cl => cl.MachineId == _setting.boxMachineId && cl.DrawerNo.Equals(drawerNo) && cl.ColNo.Equals(colNo)),
                    (pd, cl) => pd.PlanId.ToString() == cl.DrugId,
                    (pd, cl) => pd).Where(pd => pd.UseState == 1);

                //查询不在套餐中的药
                List<ChannelStock> outOfPlanStock = await _connection.ChannelStock
                    .Where(cs => cs.MachineId == _setting.boxMachineId && cs.DrawerNo.Equals(drawerNo) && cs.ColNo.Equals(colNo) && string.IsNullOrEmpty(cs.ListId))
                    .LoadWith(cs => cs.Drug)
                    .LoadWith(cs => cs.Drug.Manus)
                    .ToListAsync();
                List<PlanDetails> outOfPlanDetailList = new();
                if (outOfPlanStock != null && outOfPlanStock.Count > 0)
                {
                    for (int i = 0; i < outOfPlanStock.Count; i++)
                    {
                        outOfPlanDetailList.Add(new PlanDetails()
                        {
                            _DrugInfo = outOfPlanStock[i].Drug,
                            channelStocks = outOfPlanStock,
                            _ManuNo = null
                        });

                    }
                }

                int pagedData = await query.CountAsync();

                List<PlanDetails> list = await query
                    .LoadWith(pd => pd._DrugInfo)
                    //.LoadWith(pd => cl._PlanDetails._DrugInfo)
                    .OrderBy((pd) => pd.DrugId)
                    //.ThenBy((cl) => cl.ColNo)
                    //.Skip((int)skip)
                    //.Take((int)take)
                    .ToListAsync();
                if (list != null && list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].channelStocks = _connection.ChannelStock.AsQueryable()
                            .Where(cs => cs.MachineId == _setting.boxMachineId && cs.DrawerNo == drawerNo && cs.ColNo == colNo && cs.DrugId == list[i].DrugId)
                            .LoadWith(cs => cs.Drug)
                            .LoadWith(cs => cs.Drug.Manus)
                            .ToList();
                    }
                }
                if (outOfPlanDetailList != null && outOfPlanDetailList.Count > 0)
                {
                    for (int i = 0; i < outOfPlanDetailList.Count; i++)
                    {
                        list.Add(outOfPlanDetailList[i]);
                    }
                }

                //List<ChannelStock> list = await query
                //    .LoadWith(cl => cl.Drug)
                //    .LoadWith(cl => cl.Drug.Manus)
                //    .LoadWith(cl => cl.drugManuNo)
                //    .OrderBy((cl) => cl.DrawerNo)
                //    .ThenBy((cl) => cl.ColNo)
                //    .Skip((int)skip)
                //    .Take((int)take)
                //    .ToListAsync();


                return new PageData<PlanDetails>()
                {

                    TotalDesserts = pagedData,
                    Desserts = list
                };
            }
            else
            {
                return null;
            }
        }
        //药盒移库时获取选中药盒号的药品信息
        public async Task<PageData<ChannelStock>> GetChannelStockByDrug(ChannelStock cs, string strDrawerNoCol, int? take, int? skip)
        {
            try
            {
                int drawerNo = 0;
                int colNo = 0;
                var spl = strDrawerNoCol.Split('-');
                if (spl != null && spl.Count() > 0)
                {
                    drawerNo = Convert.ToInt32(spl[0]);
                    if (drawerNo > 30)
                    {
                        colNo = Convert.ToInt32(spl[1]);
                    }
                    else
                    {
                        colNo = Convert.ToInt32(spl[1] == "白" ? 1 : 2);
                    }
                }
                //else if (strDrawerNoCol.Length > 0)
                //{
                //    switch (strDrawerNoCol)
                //    {
                //        case "胃镜药盒":
                //            drawerNo = 31;
                //            colNo = 1;
                //            break;
                //        case "导管药盒":
                //            drawerNo = 32;
                //            colNo = 1;
                //            break;
                //        case "生殖药盒":
                //            drawerNo = 33;
                //            colNo = 1;
                //            break;
                //        case "妇门药盒":
                //            drawerNo = 34;
                //            colNo = 1;
                //            break;
                //        case "急诊药盒":
                //            drawerNo = 99;
                //            colNo = 1;
                //            break;
                //        case "恢复室药盒":
                //            drawerNo = 111;
                //            colNo = 1;
                //            break;
                //    }
                //}

                var query = _connection.ChannelStock.AsQueryable().Where(c => c.MachineId == _setting.boxMachineId && c.DrawerNo.Equals(drawerNo) && c.ColNo.Equals(colNo) && c.DrugId.Equals(cs.DrugId) && c.ManuNo != cs.ManuNo);
                int pagedData = await query.CountAsync();

                List<ChannelStock> list = await query
                    .LoadWith(cs => cs.Drug)
                    .OrderBy((cs) => cs.DrugId)
                    .Skip((int)skip)
                    .Take((int)take)
                    .ToListAsync();

                return new PageData<ChannelStock>()
                {

                    TotalDesserts = pagedData,
                    Desserts = list
                };



            }
            catch (Exception ex)
            {
                logger.Info($"药盒移库时获取选中药盒号的药品信息异常：{ex.Message}");
                return null;
            }
        }


        /// <summary>
        /// 药盒交换药品获取所有除本药盒外的所有药盒号
        /// </summary>
        /// <param name="machineId"></param>
        /// <returns></returns>
        public async Task<string[]> GetDrawerNum(ChannelStock channelStock)
        {
            //string[] stringArray = _connection.ChannelStock.Where(cs => cs.MachineId == channelStock.MachineId && cs.DrugId == channelStock.DrugId && cs.DrawerNo != channelStock.DrawerNo && !string.IsNullOrEmpty(cs.ManuNo) && cs.ManuNo != channelStock.ManuNo)
            //    .GroupBy(cs => new { cs.DrawerNo, cs.ColNo }).Select(cs => cs.Key.DrawerNo == 99 ? "急诊药盒" : cs.Key.DrawerNo == 111 ? "恢复室药盒" : cs.Key.DrawerNo == 31 ? "胃镜药盒" : cs.Key.DrawerNo == 32 ? "导管药盒" : cs.Key.DrawerNo == 33 ? "生殖药盒" : cs.Key.DrawerNo == 34 ? "妇门药盒" : cs.Key.DrawerNo.ToString() + "-" + (cs.Key.ColNo == 1 ? "白" : "绿")).ToArray();
            //return stringArray;
            string[] stringArray = _connection.ChannelStock.Where(cs => cs.MachineId == channelStock.MachineId && cs.DrugId == channelStock.DrugId && !string.IsNullOrEmpty(cs.ManuNo) && cs.ManuNo != channelStock.ManuNo && (cs.DrawerNo == channelStock.DrawerNo && cs.ColNo != channelStock.ColNo || cs.DrawerNo != channelStock.DrawerNo))
              .GroupBy(cs => new { cs.DrawerNo, cs.ColNo })
              .Select(cs => cs.Key.DrawerNo == 99 ? "急诊药盒" : cs.Key.DrawerNo == 111 ? "恢复室药盒" : cs.Key.DrawerNo == 31 ? "胃镜药盒" : cs.Key.DrawerNo == 32 ? "导管药盒" : cs.Key.DrawerNo == 33 ? "生殖药盒" : cs.Key.DrawerNo == 34 ? "妇门药盒" : cs.Key.DrawerNo.ToString() + "-" + (cs.Key.ColNo == 1 ? "白" : "绿")).ToArray();
            return stringArray;
        }
        /// <summary>
        /// 药盒移除药品，获取所有除本药盒外的所有包含该药品的药盒号
        /// </summary>
        /// <param name="machineId"></param>
        /// <returns></returns>
        public async Task<string[]> GetDrawerNumForRemove(ChannelStock channelStock)
        {
            string[] stringArray = _connection.ChannelStock.Where(cs => cs.MachineId == channelStock.MachineId && (cs.DrawerNo == channelStock.DrawerNo && cs.ColNo != channelStock.ColNo || cs.DrawerNo != channelStock.DrawerNo))
                .GroupBy(cs => new { cs.DrawerNo, cs.ColNo })
                .Select(cs => cs.Key.DrawerNo == 99 ? "急诊药盒" : cs.Key.DrawerNo == 111 ? "恢复室药盒" : cs.Key.DrawerNo == 31 ? "胃镜药盒" : cs.Key.DrawerNo == 32 ? "导管药盒" : cs.Key.DrawerNo == 33 ? "生殖药盒" : cs.Key.DrawerNo == 34 ? "妇门药盒" : cs.Key.DrawerNo.ToString() + "-" + (cs.Key.ColNo == 1 ? "白" : "绿")).ToArray();
            string[] stringDrawer = _connection.ChannelStock.Where(cs => cs.MachineId == _setting.machineId && cs.DrugId == channelStock.DrugId && cs.ManuNo == channelStock.ManuNo).Select(cs => cs.Location).ToArray();
            string[] resultArr = stringArray.Concat(stringDrawer).ToArray();
            return resultArr;
        }
        //手术室药盒交换药品完成
        public async Task<bool> BoxReplaceFinish(ChannelStock stock, List<ChannelStock> stockList)
        {
            try
            {
                bool flag = true;
                _connection.BeginTransaction();
                for (int i = 0; i < stockList.Count; i++)
                {
                    //查询出药的药盒是否有该批次的药品
                    ChannelStock replace1ChannelStock = _connection.ChannelStock.AsQueryable()
                        .Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == stock.DrawerNo && cs.ColNo == stock.ColNo && cs.DrugId == stockList[i].DrugId && cs.ManuNo == stockList[i].ManuNo)
                        .FirstOrDefault();
                    if (replace1ChannelStock != null)
                    {
                        //如果有该批次的药品，则更新数量
                        int r = _connection.ChannelStock.Where(cs => cs.Id == replace1ChannelStock.Id)
                            .Set(cs => cs.Quantity, replace1ChannelStock.Quantity + stockList[i].AddQuantity)
                            .Update();
                        if (r <= 0)
                        {
                            logger.Info($"更新药盒药品数量失败，药盒号：{stockList[i].Location}，药品ID：{stockList[i].DrugId}");
                        }
                    }
                    else
                    {
                        //如果没有该批次的药品，则新增一条批次数据
                        int mid = _connection.Insert(new ChannelStock()
                        {
                            Id = Guid.NewGuid().ToString(),
                            ListId = stock.ListId,
                            MachineId = _setting.boxMachineId,
                            DrawerNo = stock.DrawerNo,
                            ColNo = stock.ColNo,
                            DrugId = stock.DrugId,
                            ManuNo = stockList[i].ManuNo,
                            EffDate = stockList[i].EffDate,
                            DrawerType = stock.DrawerType,
                            BoardType = stock.BoardType,
                            Quantity = stockList[i].AddToQuantity,
                            BaseQuantity = stock.BaseQuantity,
                            //BoxState = 1
                        });
                        if (mid <= 0)
                        {
                            logger.Info($"新增药盒药品记录失败，药盒号：{stockList[i].DrawerNo}，药品ID：{stockList[i].DrugId}");
                            flag = false;
                            break;
                        }
                    }

                    //记录操作记录
                    int recordId = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = stock.MachineId,
                        DrawerNo = stock.DrawerNo,
                        ColNo = stock.ColNo,
                        DrugId = stock.DrugId,
                        ManuNo = stock.ManuNo,
                        EffDate = !String.IsNullOrEmpty(stock.EffDate) ? DateTime.ParseExact(stock.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = 69, //交换
                        Quantity = stockList[i].AddQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = $"{stock.Location}-{stock.Drug.DrugName}-{stock.ManuNo}与{stockList[i].Location}-{stockList[i].Drug.DrugName}-{stockList[i].ManuNo}交换,交换数量{stockList[i].AddQuantity}",
                        BoxDrawer = stockList[i].DrawerNo,
                        BoxColNo = stockList[i].ColNo
                    });
                    if (recordId <= 0)
                    {
                        logger.Info($"药盒{stock.DrawerNo}交换药品新增操作记录失败，药盒号：{stockList[i].DrawerNo}，药品ID：{stockList[i].DrugId}");
                        flag = false;
                        break;
                    }



                    //更新入药的药盒中的药品数量
                    ChannelStock replace2ChannelStock = _connection.ChannelStock.AsQueryable()
                         .Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == stockList[i].DrawerNo && cs.ColNo == stockList[i].ColNo && cs.DrugId == stock.DrugId && cs.ManuNo == stock.ManuNo)
                         .FirstOrDefault();
                    if (replace2ChannelStock != null)
                    {
                        //如果有该批次的药品，则更新数量
                        int r = _connection.ChannelStock.Where(cs => cs.Id == replace2ChannelStock.Id)
                            .Set(cs => cs.Quantity, replace2ChannelStock.Quantity + stockList[i].AddQuantity)
                            .Update();
                        if (r <= 0)
                        {
                            logger.Info($"更新药盒药品数量失败，药盒号：{stockList[i].DrawerNo}，药品ID：{stockList[i].DrugId}");
                            flag = false;
                            break;
                        }
                    }
                    else
                    {
                        //如果没有该批次的药品，则新增一条记录
                        int mid = _connection.Insert(new ChannelStock()
                        {
                            Id = Guid.NewGuid().ToString(),
                            ListId = stockList[i].ListId,
                            MachineId = _setting.boxMachineId,
                            DrawerNo = stockList[i].DrawerNo,
                            ColNo = stockList[i].ColNo,
                            DrugId = stock.DrugId,
                            ManuNo = stock.ManuNo,
                            EffDate = stock.EffDate,
                            Quantity = stockList[i].AddQuantity,
                            BaseQuantity = stockList[i].BaseQuantity,
                            //BoxState = 1
                        });
                        if (mid <= 0)
                        {
                            logger.Info($"新增药盒药品记录失败，药盒号：{stockList[i].DrawerNo}，药品ID：{stockList[i].DrugId}");
                            flag = false;
                            break;
                        }

                    }

                    //出库药盒减数量
                    int updateQuantity = _connection.ChannelStock.Where(cs => cs.Id == stock.Id)
                           .Set(cs => cs.Quantity, stock.Quantity - stockList[i].AddQuantity)
                           .Update();
                    if (updateQuantity <= 0)
                    {
                        logger.Info($"更新出库药盒药品减数量失败，药盒号：{stock.DrawerNo}，药品ID：{stock.DrugId}");
                        flag = false;
                        break;
                    }
                    //入库药盒减数量
                    int updateQuantity2 = _connection.ChannelStock.Where(cs => cs.Id == stockList[i].Id)
                            .Set(cs => cs.Quantity, stockList[i].Quantity - stockList[i].AddQuantity)
                            .Update();
                    if (updateQuantity2 <= 0)
                    {
                        logger.Info($"更新入库药盒药品减数量失败，药盒号：{stockList[i].DrawerNo}，药品ID：{stockList[i].DrugId}"); flag = false;
                        break;
                    }

                    //删除批次库存为零的数据
                    //移出库位里是否有未绑套餐且库存为0的数据，有则删除
                    _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && (string.IsNullOrEmpty(cs.ListId)) && cs.DrawerNo == stock.DrawerNo && cs.ColNo == stock.ColNo && cs.Quantity <= 0).Delete();
                    _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && (string.IsNullOrEmpty(cs.ListId)) && cs.DrawerNo == stockList[i].DrawerNo && cs.ColNo == stockList[i].ColNo && cs.Quantity <= 0).Delete();
                    //删除绑定套餐中同一药品多批次且库存为0的第一条数据
                    List<ChannelStock> delChannelStock = await _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == stock.DrawerNo && cs.ColNo == stock.ColNo && cs.DrugId == stock.DrugId).ToListAsync();
                    if (delChannelStock != null && delChannelStock.Count > 1)
                    {
                        //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                        List<ChannelStock> del = delChannelStock.Where(c => c.Quantity <= 0).ToList();
                        if (del != null && del.Count > 0)
                        {
                            if (delChannelStock.Count == del.Count)
                            {
                                for (int j = 1; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                            else
                            {
                                for (int j = 0; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                        }
                    }
                    //删除绑定套餐中同一药品多批次且库存为0的第一条数据
                    List<ChannelStock> listChannelStock = await _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == stockList[i].DrawerNo && cs.ColNo == stockList[i].ColNo && cs.DrugId == stockList[i].DrugId).ToListAsync();
                    if (listChannelStock != null && listChannelStock.Count > 1)
                    {
                        //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                        List<ChannelStock> del = listChannelStock.Where(c => c.Quantity <= 0).ToList();
                        if (del != null && del.Count > 0)
                        {
                            if (listChannelStock.Count == del.Count)
                            {
                                for (int j = 1; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                            else
                            {
                                for (int j = 0; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                        }
                    }
                }
                if (flag)
                {

                    _connection.CommitTransaction();
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;

            }
            catch (Exception ex)
            {
                logger.Info($"手术室药盒交换药品完成异常：{ex.Message}");
                _connection.RollbackTransaction();
                return false;
            }
        }
        //手术室药盒移出药品完成
        public async Task<bool> BoxRemoveFinish(ChannelStock stock, string SelectedDrawerNo, int removeQuantity)
        {
            try
            {
                bool flag = true;
                _connection.BeginTransaction();

                int selectDrawerNo = 0;
                int selectColNo = 0;
                var selectSpl = SelectedDrawerNo.Split('-');
                if (selectSpl != null && selectSpl.Count() > 0)
                {
                    selectDrawerNo = Convert.ToInt32(selectSpl[0]);
                    selectColNo = Convert.ToInt32(selectSpl[1] == "白" ? 1 : 2);
                    if (selectDrawerNo > 30)
                    {
                        selectColNo = Convert.ToInt32(selectSpl[1]);
                    }
                    else
                    {
                        selectColNo = Convert.ToInt32(selectSpl[1] == "白" ? 1 : 2);
                    }
                }
                //else if (SelectedDrawerNo.Length > 0)
                //{
                //    switch (SelectedDrawerNo)
                //    {
                //        case "胃镜药盒":
                //            selectDrawerNo = 31;
                //            selectColNo = 1;
                //            break;
                //        case "导管药盒":
                //            selectDrawerNo = 32;
                //            selectColNo = 1;
                //            break;
                //        case "生殖药盒":
                //            selectDrawerNo = 33;
                //            selectColNo = 1;
                //            break;
                //        case "妇门药盒":
                //            selectDrawerNo = 34;
                //            selectColNo = 1;
                //            break;
                //        case "急诊药盒":
                //            selectDrawerNo = 99;
                //            selectColNo = 1;
                //            break;
                //        case "恢复室药盒":
                //            selectDrawerNo = 111;
                //            selectColNo = 1;
                //            break;
                //    }
                //}

                //查询移入的药品是否有库存
                ChannelStock inChannelStock = _connection.ChannelStock.AsQueryable()
                       .Where(cs => cs.MachineId == stock.MachineId && cs.DrawerNo == selectDrawerNo && cs.ColNo == selectColNo && cs.DrugId == stock.DrugId && cs.ManuNo == stock.ManuNo)
                       .FirstOrDefault();
                if (inChannelStock != null)
                {
                    //如果有该批次的药品，则更新数量
                    int r = _connection.ChannelStock.Where(cs => cs.Id == inChannelStock.Id)
                        .Set(cs => cs.Quantity, inChannelStock.Quantity + removeQuantity)
                        .Update();
                    if (r <= 0)
                    {
                        logger.Info($"手术室药盒移出药品更新数量失败，药盒号：{SelectedDrawerNo}，药品ID：{stock.DrugId}");
                    }
                }
                else
                {
                    //如果没有该批次的药品，先查询是否有未绑批次的，有则更新批次信息，无则新增一条记录
                    ChannelStock inDrugChannelStock = _connection.ChannelStock.AsQueryable()
                      .Where(cs => cs.MachineId == stock.MachineId && cs.DrawerNo == selectDrawerNo && cs.ColNo == selectColNo && cs.DrugId == stock.DrugId && cs.Quantity <= 0)
                      .FirstOrDefault();
                    if (inDrugChannelStock != null)
                    {
                        int mid = _connection.ChannelStock.Where(cs => cs.Id == inDrugChannelStock.Id)
                        .Set(cs => cs.Quantity, removeQuantity)
                        .Set(cs => cs.ManuNo, stock.ManuNo)
                        .Set(cs => cs.EffDate, stock.EffDate)
                        .Update();
                        if (mid <= 0)
                        {
                            logger.Info($"更新药盒药品批次记录失败，药盒号：{stock.DrawerNo}，药品ID：{stock.DrugId}");
                            flag = false;
                        }
                    }
                    else
                    {
                        int mid = _connection.Insert(new ChannelStock()
                        {
                            Id = Guid.NewGuid().ToString(),
                            MachineId = stock.MachineId,
                            DrawerNo = selectDrawerNo,
                            ColNo = selectColNo,
                            DrugId = stock.DrugId,
                            ManuNo = stock.ManuNo,
                            EffDate = stock.EffDate,
                            Quantity = removeQuantity,
                            BaseQuantity = stock.BaseQuantity,
                            //BoxState = 1
                        });
                        if (mid <= 0)
                        {
                            logger.Info($"新增药盒药品记录失败，药盒号：{stock.DrawerNo}，药品ID：{stock.DrugId}");
                            flag = false;
                        }
                    }
                }
                if (flag)
                {
                    //减本库位库存数量
                    int updateQuantity2 = _connection.ChannelStock.Where(cs => cs.Id == stock.Id)
                            .Set(cs => cs.Quantity, stock.Quantity - removeQuantity)
                            .Update();
                    if (updateQuantity2 <= 0)
                    {
                        logger.Info($"更新入库药盒药品减数量失败，药盒号：{stock.DrawerNo}，药品ID：{stock.DrugId}");
                        flag = false;
                    }
                    else
                    {
                        int updateTotalQuantity = 0;
                        int updateMoveToTotalQuantity = 0;
                        //修改总库存数
                        ChannelList channelList = _connection.ChannelList.Where(cl => cl.MachineId.Equals(_setting.boxMachineId) && cl.DrawerNo == stock.DrawerNo && cl.ColNo == stock.ColNo).FirstOrDefault();
                        if (channelList != null)
                        {
                            updateTotalQuantity = _connection.ChannelList.Where(cl => cl.Id == channelList.Id)
                                .Set(cl => cl.TotalQuantity, channelList.TotalQuantity - removeQuantity)
                                .Update();
                        }

                        //修改移入药盒的总库存数

                        ChannelList moveToChannelList = _connection.ChannelList.Where(cl => cl.MachineId == stock.MachineId && cl.DrawerNo == selectDrawerNo && cl.ColNo == selectColNo).FirstOrDefault();
                        if (moveToChannelList != null)
                        {
                            updateMoveToTotalQuantity = _connection.ChannelList.Where(cl => cl.Id == moveToChannelList.Id)
                                .Set(cl => cl.TotalQuantity, moveToChannelList.TotalQuantity + removeQuantity)
                                .Update();
                        }
                        if (updateTotalQuantity > 0 && updateMoveToTotalQuantity > 0)
                        {
                            flag = true;
                        }
                        else
                        {
                            flag = false;
                        }

                    }
                    if (flag)
                    {
                        //记录操作记录
                        int recordId = _connection.InsertWithInt32Identity(new MachineRecord()
                        {
                            MachineId = stock.MachineId,
                            DrawerNo = stock.DrawerNo,
                            ColNo = stock.ColNo,//移入的药盒号
                            DrugId = stock.DrugId,
                            ManuNo = stock.ManuNo,
                            EffDate = !String.IsNullOrEmpty(stock.EffDate) ? DateTime.ParseExact(stock.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                            OperationTime = DateTime.Now,
                            Type = 21, //移
                            Quantity = removeQuantity,
                            Operator = _globalStateService.Operator.Id,
                            Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                            BoxDrawer = selectDrawerNo,
                            BoxColNo = selectColNo,
                            InvoiceId = stock.Id.ToString(),
                        });
                        if (recordId <= 0)
                        {
                            logger.Info($"药盒{stock.DrawerNo}交换药品新增操作记录失败，药盒号：{stock.DrawerNo}，药品ID：{stock.DrugId}");
                            flag = false;
                        }
                    }
                    //移出库位里是否有未绑套餐且库存为0的数据，有则删除
                    _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && (string.IsNullOrEmpty(cs.ListId)) && cs.DrawerNo == selectDrawerNo && cs.ColNo == selectColNo && cs.Quantity <= 0).Delete();
                    _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && (string.IsNullOrEmpty(cs.ListId)) && cs.DrawerNo == stock.DrawerNo && cs.ColNo == stock.ColNo && cs.Quantity <= 0).Delete();
                    //删除绑定套餐中同一药品多批次且库存为0的第一条数据
                    List<ChannelStock> delChannelStock = await _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == stock.DrawerNo && cs.ColNo == stock.ColNo && cs.DrugId == stock.DrugId).ToListAsync();
                    if (delChannelStock != null && delChannelStock.Count > 1)
                    {
                        //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                        //for (int i = 1; i < delChannelStock.Count; i++)
                        //{
                        //    _connection.Delete(delChannelStock[i]);
                        //}
                        //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                        List<ChannelStock> del = delChannelStock.Where(c => c.Quantity <= 0).ToList();
                        if (del != null && del.Count > 0)
                        {
                            if (delChannelStock.Count == del.Count)
                            {
                                for (int j = 1; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                            else
                            {
                                for (int j = 0; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                        }
                    }
                }
                if (flag)
                {

                    _connection.CommitTransaction();
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;

            }
            catch (Exception ex)
            {
                logger.Info($"手术室药盒移出药品异常{ex.Message}");
                _connection.RollbackTransaction();
                return false;
            }
        }


        public async Task<List<ChannelList>> GetAllBox()
        {
            var query = _connection.ChannelList.AsQueryable();


            return await query
                .Where(cl => cl.MachineId == _setting.boxMachineId)
                .OrderBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.ColNo)
                .ToListAsync();
        }
        //根据药盒查询药品信息
        public async Task<List<ChannelStock>> GetChannelStockByBox(int BoxNum)
        {
            var query = _connection.ChannelStock.AsQueryable()
                .Where(cl => cl.MachineId == _setting.boxMachineId && cl.DrawerNo == BoxNum && cl.Quantity > 0);
            return await query
                //.Where(cl=>cl.Quantity<=0)
                .OrderBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.DrawerNo)
                .ThenBy((cl) => cl.ColNo)
                .ToListAsync();
        }
        //根据套餐下无库存的药箱
        public async Task<List<ChannelStock>> GetChannelStockByPlan(string plan)
        {
            var query = await _connection.ChannelList.AsQueryable().Where(cl => cl.MachineId == _setting.boxMachineId && cl.DrugId == plan).Select(c => c.DrawerNo).ToListAsync();
            if (query != null && query.Count > 0)
            {
                return await _connection.ChannelStock.Where(c => query.Contains(c.DrawerNo) && c.MachineId == _setting.boxMachineId && c.Quantity <= 0).ToListAsync();
            }
            return null;
        }

        //手术室药盒获取绑定数据
        public async Task<List<ChannelList>> GetAllChannelList()
        {

            var query = _connection.ChannelList.AsQueryable()
                .Where(cl => cl.MachineId == _setting.boxMachineId);
            //.LoadWith(cl=>cl.PlanInfo);


            int pagedData = await query.CountAsync();

            List<ChannelList> list = await query
                .OrderBy((cl) => cl.DrawerNo)
                .ToListAsync();
            return list;
        }

        //抽屉取药向药盒加药校验药盒中是否存在该药
        public async Task<CheckInfo<ChannelList>> CheckBoxDrugInfo(BoxModel BoxNum, List<ChannelStock> channelStockList)
        {
            string errorInfo = string.Empty;
            int count = 0;
            List<ChannelList> channelList = new List<ChannelList>();
            for (int i = 0; i < channelStockList.Count; i++)
            {
                //ChannelList cl = _connection.ChannelList.InnerJoin
                //    (
                //    _connection.PlanDetails.Where(pd => pd.UseState == 1 && pd.DrugId == channelStockList[i].DrugId),
                //    (cs, pd) => cs.DrugId == pd.PlanId.ToString(),
                //    (cs, pd) => cs
                //    ).FirstOrDefault();
                ChannelList cl = _connection.ChannelList.Where(cl => cl.MachineId == _setting.boxMachineId && cl.DrawerNo == BoxNum.BoxName && cl.ColNo == BoxNum.BoxNo).FirstOrDefault();
                if (cl != null && !string.IsNullOrEmpty(cl.DrugId))
                {
                    //查该库位绑定的套餐对应的药品信息
                    cl._PlanDetails = _connection.PlanDetails.Where(pd => pd.PlanId.ToString() == cl.DrugId && pd.DrugId == channelStockList[i].DrugId).ToList();
                    channelList.Add(cl);
                }
                else
                {
                    errorInfo += $"{channelStockList[i].Drug.DrugName}未在{(BoxNum.BoxName == 99 ? "急诊" : BoxNum.BoxName == 111 ? "恢复室" : string.Concat(BoxNum.BoxName.ToString(), (BoxNum.BoxNo == 1 ? "-白" : "-绿")))}药盒中绑定;";
                }
            }

            return new CheckInfo<ChannelList>()
            {

                StrInfo = errorInfo,
                TEntity = channelList
            };
        }
        //药箱中的药移入到抽屉
        /// <summary>
        /// 
        /// </summary>
        /// <param name="SelectedDrawerNo">移入的抽屉</param>
        /// <param name="channelStock">移出的药盒</param>
        /// <param name="quantity">移出数量</param>
        /// <returns></returns>
        public async Task<bool> RemoveDrugToDrawerFinish(string SelectedDrawerNo, ChannelStock stock, int removeQuantity)
        {
            try
            {
                bool flag = true;
                _connection.BeginTransaction();

                int selectDrawerNo = 0;
                int selectColNo = 0;
                var selectSpl = SelectedDrawerNo.Split('-');
                if (selectSpl != null && selectSpl.Count() > 0)
                {
                    selectDrawerNo = Convert.ToInt32(selectSpl[0]);
                    selectColNo = Convert.ToInt32(selectSpl[1]);
                }

                //查询移入的药品是否有库存
                ChannelStock inChannelStock = _connection.ChannelStock.AsQueryable()
                       .Where(cs => cs.MachineId.Equals(_setting.machineId) && cs.DrawerNo == selectDrawerNo && cs.ColNo == selectColNo && cs.DrugId == stock.DrugId && cs.ManuNo == stock.ManuNo)
                       .FirstOrDefault();
                if (inChannelStock != null)
                {
                    //如果有该批次的药品，则更新数量
                    int r = _connection.ChannelStock.Where(cs => cs.Id == inChannelStock.Id)
                        .Set(cs => cs.Quantity, inChannelStock.Quantity + removeQuantity)
                        .Update();
                    if (r <= 0)
                    {
                        logger.Info($"手术室药盒移出药品更新数量失败，药盒号：{SelectedDrawerNo}，药品ID：{stock.DrugId}");
                    }
                }
                else
                {
                    logger.Info($"抽屉{SelectedDrawerNo}不存在药品{stock.Drug.DrugName}，批次{stock.ManuNo}，无法移入");
                    flag = false;
                }
                if (flag)
                {
                    //减本库位库存数量
                    int updateQuantity2 = _connection.ChannelStock.Where(cs => cs.Id == stock.Id)
                            .Set(cs => cs.Quantity, stock.Quantity - removeQuantity)
                            .Update();
                    if (updateQuantity2 <= 0)
                    {
                        logger.Info($"更新入库药盒药品减数量失败，药盒号：{stock.DrawerNo}，药品ID：{stock.DrugId}");
                        flag = false;
                    }
                    if (flag)
                    {
                        //记录操作记录
                        int recordId = _connection.InsertWithInt32Identity(new MachineRecord()
                        {
                            MachineId = _setting.machineId,
                            DrawerNo = stock.DrawerNo,
                            ColNo = stock.ColNo,//移入的抽屉库位
                            BoxDrawer = selectDrawerNo,
                            BoxColNo = selectColNo,//移入的抽屉库位
                            DrugId = stock.DrugId,
                            ManuNo = stock.ManuNo,
                            EffDate = !String.IsNullOrEmpty(stock.EffDate) ? DateTime.ParseExact(stock.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                            OperationTime = DateTime.Now,
                            Type = 21, //交换
                            Quantity = removeQuantity,
                            Operator = _globalStateService.Operator.Id,
                            Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                            InvoiceId = $"药盒{stock.Location}中药品{stock.Drug.DrugName}批次{stock.ManuNo},移入抽屉{SelectedDrawerNo}，数量{removeQuantity}",
                        });
                        if (recordId <= 0)
                        {
                            logger.Info($"移盒移出药品失败：药盒{stock.Location}中药品{stock.Drug.DrugName}批次{stock.ManuNo},移入抽屉{SelectedDrawerNo}，数量{removeQuantity}");
                            flag = false;
                        }
                    }
                    //移出库位里是否有未绑套餐且库存为0的数据，有则删除
                    _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && (string.IsNullOrEmpty(cs.ListId)) && cs.DrawerNo == stock.DrawerNo && cs.ColNo == stock.ColNo && cs.Quantity <= 0).Delete();
                    //删除绑定套餐中同一药品多批次且库存为0的第一条数据
                    List<ChannelStock> delChannelStock = await _connection.ChannelStock.Where(cs => cs.MachineId.Equals(_setting.boxMachineId) && cs.DrawerNo == stock.DrawerNo && cs.ColNo == stock.ColNo && cs.DrugId == stock.DrugId).ToListAsync();
                    if (delChannelStock != null && delChannelStock.Count > 1)
                    {
                        //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                        //for (int i = 1; i < delChannelStock.Count; i++)
                        //{
                        //    _connection.Delete(delChannelStock[i]);
                        //}
                        //删除绑定套餐中库存为0的药的批次数据，只保留一条数据
                        List<ChannelStock> del = delChannelStock.Where(c => c.Quantity <= 0).ToList();
                        if (del != null && del.Count > 0)
                        {
                            if (delChannelStock.Count == del.Count)
                            {
                                for (int j = 1; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                            else
                            {
                                for (int j = 0; j < del.Count; j++)
                                {
                                    _connection.ChannelStock.Where(cs => cs.Id == del[j].Id).Delete();
                                }
                            }
                        }
                    }
                }
                if (flag)
                {

                    _connection.CommitTransaction();
                }
                else
                {
                    _connection.RollbackTransaction();
                }
                return flag;

            }
            catch (Exception ex)
            {
                logger.Info($"手术室药盒移出药品异常{ex.Message}");
                _connection.RollbackTransaction();
                return false;
            }
        }


    }
}
