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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace MasaBlazorApp3.DataAccess.Impl
{
    public class SelfTakeDao : ISelfTakeDao
    {
        private AppDataConnection _connection;
        private readonly SettingConfig _setting;
        ILog logger = LogManager.GetLogger(typeof(SelfTake));
        private GlobalStateService _globalStateService;
        private readonly PortUtil _portUtil;

        public SelfTakeDao(AppDataConnection connection, IOptions<SettingConfig> setting, GlobalStateService globalStateService, PortUtil portUtil)
        {
            _connection = connection;
            _setting = setting.Value;
            _globalStateService = globalStateService;
            _portUtil = portUtil;
        }
        /// <summary>
        /// 根据药品信息 获取药品库存信息
        /// </summary>
        /// <param name="drugInfos"></param>
        /// <returns></returns>
        public async Task<List<ChannelStock>> GetChannelStocksByDrug(List<DrugInfo> drugInfos)
        {
            List<ChannelStock> channelStocks = new List<ChannelStock>();
            try
            {
                foreach (var drugInfo in drugInfos)
                {
                    var query = _connection.ChannelStock.AsQueryable();
                    ChannelStock channelStock = query.Where(cs => cs.MachineId == _setting.machineId && cs.DrawerType == 1 && cs.DrugId == drugInfo.DrugId).First();
                    if (channelStock != null)
                    {
                        channelStocks.Add(channelStock);
                    }
                    else
                    {
                        logger.Info($"药品{drugInfo.DrugName}未绑定");
                        channelStocks.Add(new ChannelStock()
                        {
                            DrugId = drugInfo.DrugId,
                            DrawerType = 1,
                            MachineId = _setting.machineId,
                            Quantity = 0
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Info($"SelfTakeDao异常{ex.Message}");
            }
            return channelStocks;
        }
        /// <summary>
        /// 根据药品明细获取数据
        /// </summary>
        /// <param name="orderDetails"></param>
        /// <returns></returns>
        public async Task<List<OrderTakeVo>> getTakeInfoByOrderNo(List<OrderDetail> orderDetails)
        {

            List<OrderTakeVo> tempData = new();
            List<OrderTakeVo> tempData2 = new();
            var flag = true;
            for (var i = 0; i < orderDetails.Count; i++)
            {
                //List<IDictionary<string, object>> tempData = new();
                OrderDetail detail = orderDetails[i];
                // 当前detail取药数量
                var Quantity = detail.Quantity;
                List<ChannelStock> stockList = await this.GetChannelStockByDrugId(detail.Drug.DrugId, detail.SetManuNo, Quantity);

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

                tempData2.Add(new OrderTakeVo()
                {
                    Drug = detail.Drug,
                    OrderDetail = detail,
                    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 OrderTakeVo()
                                {
                                    Drug = detail.Drug,
                                    OrderDetail = detail,
                                    ChannelStock = stock,
                                    StockQuantity = total,
                                    Quantity = stock.Quantity,
                                });
                                Quantity -= stock.Quantity;
                            }
                            else
                            {
                                //取药数量小于库存
                                tempData.Add(new OrderTakeVo()
                                {
                                    Drug = detail.Drug,
                                    OrderDetail = detail,
                                    ChannelStock = stock,
                                    StockQuantity = total,
                                    Quantity = Quantity,
                                });
                                Quantity = 0;
                            }
                        }
                    }
                    else
                    {
                        // 库存不足
                        flag = false;
                    }
                }

            }
            if (flag)
            {
                return tempData;
            }
            else
            {
                return tempData2;
            }
        }

        public async Task<List<ChannelStock>> GetChannelStockByDrugId(string DrugId, String ManuNo, int quantity = 0)
        {
            var query = _connection.ChannelStock.AsQueryable();


            query = query.Where(cs => cs.MachineId.Equals(_setting.machineId)).Where(cs => cs.DrawerType == 1)
                .Where(cs => cs.Quantity > 0)
                .Where(cs => cs.DrugId.Equals(DrugId));

            if (quantity > 0)
            {
                if (!String.IsNullOrEmpty(ManuNo))
                {
                    query = query.Where(cs => cs.ManuNo.Equals(ManuNo));
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(ManuNo))
                {
                    query = query.Where(cs => cs.ManuNo.Equals(ManuNo) || cs.Quantity == 0);
                }
            }


            return await query.OrderBy((cs) => cs.EffDate)
                        .ThenBy((cs) => cs.DrawerNo)
                        .ThenBy((cs) => cs.ColNo)
                        .ToListAsync();
        }

        /// <summary>
        /// 保存自选取药完成数据
        /// </summary>
        /// <param name="datas"></param>
        /// <returns></returns>
        public async Task<bool> OrderTakeFinish(List<OrderTakeVo> datas, OrderInfo order)
        {

            try
            {
                _connection.BeginTransaction();
                var flag = true;
                // 保存处方信息
                order.Status = 1;
                order.PatientId = order.PatientId == null ? "0" : order.PatientId;
                int r1 = _connection.InsertWithInt32Identity<OrderInfo>(order);
                if (!(r1 > 0))
                {
                    flag = false;
                    logger.Error("处方取药完成更新处方状态失败");
                    _connection.RollbackTransaction();
                    return flag;
                }
                for (var i = 0; i < datas.Count; i++)
                {
                    var orderTakeVo = datas[i];
                    //保存处方明细
                    orderTakeVo.OrderDetail.PatientId = orderTakeVo.OrderDetail.PatientId == null ? order.PatientId : orderTakeVo.OrderDetail.PatientId;
                    orderTakeVo.OrderDetail.ChargeDate = orderTakeVo.OrderDetail.ChargeDate == null ? order.ChargeDate : orderTakeVo.OrderDetail.ChargeDate;
                    orderTakeVo.OrderDetail.OrderNo = order.OrderNo;
                    orderTakeVo.OrderDetail.DrugId = orderTakeVo.Drug.DrugId;
                    orderTakeVo.OrderDetail.SetManuNo = orderTakeVo.ChannelStock.ManuNo;
                    orderTakeVo.OrderDetail.SetEffDate = orderTakeVo.ChannelStock.EffDate;
                    int od = _connection.InsertWithInt32Identity<OrderDetail>(orderTakeVo.OrderDetail);
                    // 出库记录
                    int mid = _connection.InsertWithInt32Identity(new MachineRecord()
                    {
                        MachineId = _setting.machineId,
                        DrawerNo = orderTakeVo.ChannelStock.DrawerNo,
                        ColNo = orderTakeVo.ChannelStock.ColNo,
                        DrugId = orderTakeVo.ChannelStock.DrugId,
                        ManuNo = orderTakeVo.ChannelStock.ManuNo,
                        EffDate = !String.IsNullOrEmpty(orderTakeVo.ChannelStock.EffDate) ? DateTime.ParseExact(orderTakeVo.ChannelStock.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = 2,
                        Quantity = orderTakeVo.GetQuantity,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        InvoiceId = orderTakeVo.OrderDetail.Id.ToString(),
                    });
                    // 更新库存
                    int r = _connection.ChannelStock.Where(cs => cs.Id == orderTakeVo.ChannelStock.Id)
                        .Set(cs => cs.Quantity, orderTakeVo.ChannelStock.Quantity - orderTakeVo.GetQuantity)
                        .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(orderTakeVo.ChannelStock.DrugId))
                         .ToListAsync();
                    // 保存账册
                    int acid = _connection.InsertWithInt32Identity(new AccountBook()
                    {
                        MachineId = _setting.machineId,
                        DrugId = orderTakeVo.ChannelStock.DrugId,
                        ManuNo = orderTakeVo.ChannelStock.ManuNo,
                        EffDate = !String.IsNullOrEmpty(orderTakeVo.ChannelStock.EffDate) ? DateTime.ParseExact(orderTakeVo.ChannelStock.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                        OperationTime = DateTime.Now,
                        Type = 2,
                        OutQuantity = orderTakeVo.GetQuantity,
                        AddQuantity = 0,
                        Operator = _globalStateService.Operator.Id,
                        Reviewer = _globalStateService.Reviewer?.Id ?? _globalStateService.Operator.Id,
                        ManuStock = list.Where(it => it.ManuNo == orderTakeVo.ChannelStock.ManuNo).Sum(it => it.Quantity),
                        TotalStock = list.Sum(it => it.Quantity),
                        InvoiceId = orderTakeVo.OrderDetail.Id.ToString()
                    });
                    if (mid > 0 && r > 0 && acid > 0)
                    {
                        //根据抽屉类型判断是否需要写标签
                        if (orderTakeVo.ChannelStock.BoardType.ToString().Contains("5"))
                        {
                            await _portUtil.WriteQuantityMethod(orderTakeVo.ChannelStock.Quantity - orderTakeVo.GetQuantity, orderTakeVo.ChannelStock.DrawerNo, orderTakeVo.ChannelStock.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;
            }
        }
    }
}
