using DM_Weight.Models;
using DM_Weight.msg;
using DM_Weight.Report;
using DM_Weight.Services;
using DM_Weight.util;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace DM_Weight.ViewModels
{
    public class AccountWindowViewModel : BindableBase, INavigationAware, IRegionMemberLifetime
    {
        public static AccountWindowViewModel vm;
        //private int _pageNum = 1;
        //public int PageNum
        //{
        //    get => _pageNum;
        //    set
        //    {
        //        SetProperty(ref _pageNum, value);
        //        RequestData();
        //    }
        //}
        //private int _pageCount = 1;
        //public int PageCount
        //{
        //    get => _pageCount;
        //    set
        //    {
        //        SetProperty(ref _pageCount, value);
        //    }
        //}
        //private int _pageSize = 8;
        //public int PageSize
        //{
        //    get => _pageSize;
        //    set
        //    {
        //        SetProperty(ref _pageSize, value);
        //    }
        //}
        //private int _totalCount = 0;
        //public int TotalCount
        //{
        //    get => _totalCount;
        //    set
        //    {
        //        SetProperty(ref _totalCount, value);
        //    }
        //}
        private DateTime? _startDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        private DateTime? nowDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        public DateTime? StartDate
        {
            get => _startDate;
            set
            {
                if (value != null)
                {
                    SetProperty(ref _startDate, new DateTime(value?.Year ?? 0, value?.Month ?? 0, value?.Day ?? 0));
                }
                else
                {
                    SetProperty(ref _startDate, value);
                }
                RequestData();
            }
        }
        private DateTime? _endDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
        public DateTime? EndDate
        {
            get => _endDate;
            set
            {
                if (value != null)
                {
                    TimeSpan ershisi = new TimeSpan(23, 59, 59);
                    SetProperty(ref _endDate, new DateTime(value?.Year ?? 0, value?.Month ?? 0, value?.Day ?? 0, 23, 59, 59));
                }
                else
                {
                    SetProperty(ref _endDate, value);
                }
                RequestData();
            }
        }
        private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        /// 
        /// 账册
        /// 
        private List _accountList = new();
        public List AccountList
        {
            get => _accountList;
            set => SetProperty(ref _accountList, value);
        }
        /// 
        /// 药品
        /// 
        private List? _drugInfos;
        public List? DrugInfos
        {
            get => _drugInfos;
            set => SetProperty(ref _drugInfos, value);
        }
        private DrugInfo? _drugInfo;
        public DrugInfo? DrugInfo
        {
            get => _drugInfo;
            set
            {
                SetProperty(ref _drugInfo, value);
                //if (_drugInfo != null)
                //{
                //DrugManuNos = _drugInfo.DrugManuNos.OrderByDescending(dm => dm.ManuNo).ToList();
                //}
                RequestData();
            }
        }
        /// 
        /// 账册类型1入2出3总结存
        /// 
        private List _accountTypeList = new List() {
                new AccountType
                {
                    AccountTypeName="借入",
                    AccountTypeValue=1
                },
                new AccountType
                {
                    AccountTypeName="发出",
                    AccountTypeValue=2
                },
                new AccountType
                {
                    AccountTypeName="日结存",
                    AccountTypeValue=5
                }
        };
        public List? AccountTypeList
        {
            get => _accountTypeList;
            set
            {
                SetProperty(ref _accountTypeList, value);
                RequestData();
            }
        }
        private AccountType? _accountType;
        public AccountType AccountType
        {
            get => _accountType;
            set
            {
                SetProperty(ref _accountType, value);
                RequestData();
            }
        }
        MachineRecordService _machineRecordService;
        ChannelStockService _channelStockService;
        IEventAggregator _eventAggregator;
        ////private SqlSugarScope SqlSugarHelper.Db;
        public AccountWindowViewModel(MachineRecordService machineRecord, ChannelStockService channelStockService, IEventAggregator eventAggregator)
        {
            _machineRecordService = machineRecord;
            _channelStockService = channelStockService;
            ////this.SqlSugarHelper.Db = sqlSugarScope;
            _eventAggregator = eventAggregator;
            vm = this;
        }
        void RequestData()
        {
            int totalCount = 0;
            AccountList = _machineRecordService.ReportAccountBook(StartDate, EndDate, AccountType == null ? 0 : AccountType.AccountTypeValue, DrugInfo == null ? "" : DrugInfo.DrugId ?? "");
            //for (int i = 0; i < accountList.Count; i++)
            //{
            //    if (accountList[i].DrugInfo is null)
            //    {
            //        DrugInfo drug= new DrugInfo();
            //        drug.DrugId = accountList[i].DrugId;
            //        drug.DrugName = accountList[i].DrugName;
            //        drug.DrugSpec = accountList[i].DrugSpec;
            //        drug.Dosage= accountList[i].Dosage;
            //        drug.PackUnit= accountList[i].PackUnit;
            //        drug.Manufactory= accountList[i].Manufactory;
            //        accountList[i].DrugInfo= drug;
            //    }
            //}
            //ICollectionView vw = CollectionViewSource.GetDefaultView(accountList);
            //vw.GroupDescriptions.Add(new PropertyGroupDescription("DrugInfo"));
        }
        private void GetAllDrugInfos()
        {
            var list = SqlSugarHelper.Db.Queryable().Includes(di => di.DrugManuNos).OrderBy(di => di.DrugId).ToList();
            DrugInfos = list;
            DrugInfo = list[0];
        }
        /// 
        /// 生成日结存
        /// 
        public DelegateCommand DayAccountBook
        {
            get => new DelegateCommand(() =>
            {
                DayAccountAction();
                RequestData();
            });
        }
        //生成一条当日没有记录的账册记录
        private void DayAccountAction()
        {
            try
            {
                string machineId = ConfigurationManager.AppSettings["machineId"] ?? "DM1";
                //根据已生成的日结存记录
                int deleteNum = SqlSugarHelper.Db.Deleteable()
                 .Where(cs => cs.Type.Equals(5) && cs.OperationTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd") && cs.MachineId.Equals(machineId)).ExecuteCommand();
                int inQuantity = 0;  //当日入库量
                int outQuantity = 0; //当日出库量
                //查询账册中所有记录,与库存中的记录做比校,如果账册中没有,则添加一条,有则添加一条总日结存
                List accountList = _machineRecordService.ReportAccountBook(nowDate, null, 0);
                //库存中的记录
                List channelStockList = _channelStockService.GetAll();
                //List channelStockInsert = new List();
                if (accountList != null && accountList.Count() > 0)
                {
                    //账册中有记录则与库存记录对比
                    for (int i = 0; i < channelStockList.Count; i++)
                    {
                        string drugId = channelStockList[i].DrugId;
                        int Count = accountList.Where(cs => cs.DrugId == drugId).Count();
                        if (Count <= 0)
                        {
                            inQuantity = 0;
                            outQuantity = 0;
                        }
                        else
                        {
                            inQuantity = accountList.Where(cs => cs.DrugId == drugId).Sum(cs => cs.InQuantity);
                            outQuantity = accountList.Where(cs => cs.DrugId == drugId).Sum(cs => cs.OutQuantity);
                        }
                        // 获取药品总库存
                        int channelStockQuantity = SqlSugarHelper.Db.Queryable()
                            .Where(cs => cs.DrugId.Equals(drugId)).Sum(it => it.Quantity);
                        //没有直接插入
                        // 保存数据 出/入库记录
                        string InvoiceId = "Account_" + CurrentTimeMillis();
                        SqlSugarHelper.Db.Insertable(new MachineRecord()
                        {
                            MachineId = channelStockList[i].MachineId,
                            DrawerNo = 0,//channelStockList[i].DrawerNo,
                            ColNo = 0,// channelStockList[i].ColNo,FV
                            DrugId = drugId,
                            ManuNo = "",//channelStockList[i].ManuNo,
                            EffDate = null,// !String.IsNullOrEmpty(channelStockList[i].EffDate) ? DateTime.ParseExact(channelStockList[i].EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                            Operator = HomeWindowViewModel.Operator?.Id,
                            Reviewer = HomeWindowViewModel.Reviewer?.Id,
                            OperationTime = DateTime.Now,
                            Quantity = 0,
                            Type = 5,
                            InvoiceId = "日结存",//InvoiceId,
                            ReturnQuantity1 = inQuantity,  //当日入库量总数
                            ReturnQuantity2 = outQuantity,  //当日出库量总数
                            StockQuantity = channelStockQuantity,
                            ManunoQuantity = 0,
                            SupplierDept = string.Empty,// ConfigurationManager.AppSettings["supplierDept"].ToString(),
                            ReceiveDept = string.Empty,//ConfigurationManager.AppSettings["receiveDept"].ToString()
                        }).ExecuteCommand();
                    }
                }
                else
                {
                    for (int i = 0; i < channelStockList.Count; i++)
                    {
                        //账册中没有记录则把库存中的所有数据都要生成一条账册记录
                        // 保存数据 出/入库记录
                        // 获取药品总库存
                        string drugId= channelStockList[i].DrugId;
                        int channelStockQuantity = SqlSugarHelper.Db.Queryable()
                            .Where(cs => cs.DrugId.Equals(drugId)).Sum(it => it.Quantity);
                        string InvoiceId = "Account_" + CurrentTimeMillis();
                        SqlSugarHelper.Db.Insertable(new MachineRecord()
                        {
                            MachineId = channelStockList[i].MachineId,
                            DrawerNo = 0,//channelStockList[i].DrawerNo,
                            ColNo = 0,//channelStockList[i].ColNo,
                            DrugId = drugId,
                            ManuNo = "",// channelStockList[i].ManuNo,
                            EffDate = null,// !String.IsNullOrEmpty(channelStockList[i].EffDate) ? DateTime.ParseExact(channelStockList[i].EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
                            Operator = HomeWindowViewModel.Operator?.Id,
                            Reviewer = HomeWindowViewModel.Reviewer?.Id,
                            OperationTime = DateTime.Now,
                            Quantity = 0,
                            Type = 5,
                            InvoiceId = "日结存",// string.Empty,//InvoiceId,
                            ReturnQuantity1 = inQuantity,  //当日入库量总数
                            ReturnQuantity2 = outQuantity,  //当日出库量总数
                            StockQuantity = channelStockQuantity,
                            ManunoQuantity = 0,
                            SupplierDept = string.Empty,//ConfigurationManager.AppSettings["supplierDept"].ToString(),
                            ReceiveDept = string.Empty,//ConfigurationManager.AppSettings["receiveDept"].ToString()
                        }).ExecuteCommand();
                    }
                }
                AlertMsg alertMsg = new AlertMsg
                {
                    Message = "日结存已生成完成",
                    Type = MsgType.SUCCESS,
                };
                _eventAggregator.GetEvent().Publish(alertMsg);
            }
            catch (Exception ex)
            {
                AlertMsg alertMsg = new AlertMsg
                {
                    Message = "生成日结存失败",
                    Type = MsgType.ERROR,
                };
                _eventAggregator.GetEvent().Publish(alertMsg);
            }
            RequestData();
        }
        public long CurrentTimeMillis()
        {
            return (long)(DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
        }
        //public void InsertDayAccount()
        //{
        //    // 保存数据 出/入库记录
        //    SqlSugarHelper.Db.Insertable(new MachineRecord()
        //    {
        //        MachineId = it.MachineId,
        //        DrawerNo = it.DrawerNo,
        //        ColNo = it.ColNo,
        //        DrugId = it.DrugId,
        //        ManuNo = it.ManuNo,
        //        EffDate = !String.IsNullOrEmpty(it.EffDate) ? DateTime.ParseExact(it.EffDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture) : null,
        //        Operator = HomeWindowViewModel.Operator?.Id,
        //        Reviewer = HomeWindowViewModel.Reviewer?.Id,
        //        OperationTime = DateTime.Now,
        //        Quantity = it.AddQuantity,
        //        Type = 1,
        //        InvoiceId = InvoiceId,
        //        StockQuantity = nowChannels.Sum(it => it.Quantity),
        //        ManunoQuantity = nowChannels.FindAll(it2 => it2.ManuNo == it.ManuNo).Sum(it => it.Quantity),
        //        SupplierDept = Invoice.PharmacyName1 ?? ConfigurationManager.AppSettings["supplierDept"].ToString(),
        //        ReceiveDept = Invoice.PharmacyName2 ?? ConfigurationManager.AppSettings["receiveDept"].ToString()
        //    }).ExecuteCommand();
        //}
        /// 
        /// 导出账册
        /// 
        public DelegateCommand DownloadAccountBook
        {
            get => new DelegateCommand(() =>
            {
                GridReportUtil.PrintReportAccountBook(StartDate, EndDate, AccountType == null ? 0 : AccountType.AccountTypeValue, DrugInfo == null ? "" : DrugInfo.DrugId);
            });
        }
        /// 
        /// 刷新
        /// 
        public DelegateCommand Query
        {
            get => new DelegateCommand(() =>
            {
                RequestData();
            });
        }
        public bool KeepAlive => true;
        public void UpdateComboBoxItems(string text)
        {
            string str = @"SELECT d.drug_id,d.py_code,d.drug_barcode,d.drug_name,d.drug_brand_name,d.drug_spec,d.dosage,d.pack_unit,
                        d.manufactory,d.max_stock FROM `drug_info` d";
            if (string.IsNullOrEmpty(text))
            {
                DrugInfos = SqlSugarHelper.Db.SqlQueryable(str).OrderBy(di => di.DrugName).OrderBy(di => di.DrugId).ToList();
                return;
            }
            if (DrugInfos != null)
            {
                DrugInfos.Clear();
            }
            DrugInfos = SqlSugarHelper.Db.SqlQueryable(str).Where(di => di.DrugName.Contains(text) || di.PyCode.Contains(text) || di.DrugId.Contains(text)).OrderBy(di => di.DrugName).OrderBy(di => di.DrugId).ToList();
        }
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            //药品信息
            GetAllDrugInfos();
            //查询表格数据
            RequestData();
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
    }
}