using LinqToDB;
using log4net;
using MasaBlazorApp3.DataAccess.Dao;
using MasaBlazorApp3.Pojo;
using MasaBlazorApp3.Pojo.Config;
using Microsoft.Extensions.Options;
using Mysqlx.Crud;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MasaBlazorApp3.DataAccess.Impl
{
    public class ReportDataDao : IReportDataDao
    {
        private AppDataConnection _connection;
        private readonly SettingConfig _setting;
        private readonly ILog logger = LogManager.GetLogger(typeof(ReportDataDao));
        public ReportDataDao(AppDataConnection connection, IOptions<SettingConfig> setting)
        {
            _connection = connection;
            _setting = setting.Value;
        }
        //获取库存导出数据
        public async Task<PageData<ReportStockDateInfo>> GetStockExportData(string drugName)
        {
            try
            {
                List<ReportStockDateInfo> reportStockList = new List<ReportStockDateInfo>();
                int pagedData = 0;
                string SQL = $@"SELECT cl.drug_id AS DrugId,di.`drug_name` AS DrugName,di.drug_type AS DrugType,di.drug_spec AS DrugSpec,di.manufactory AS Manufactory,
                          di.pack_unit AS pack_unit,di.py_code AS PyCode,null AS Stocks,NULL AS Manus,db.baseQuantity AS BaseQuantity,CONCAT(cl.row_no,cl.col_no) as location,
                          cl.manu_no as ManuNo,cl.eff_date as EffDate,cl.Quantity AS Quantity,cl.manu_no,cl.eff_date FROM channel_stock cl INNER JOIN drug_info di ON di.`drug_id` = cl.`drug_id` 
                          LEFT JOIN drug_base db ON db.drugid=di.drug_id and db.machine_id= '{_setting.machineId}' 
                          WHERE cl.`machine_id` =  '{_setting.machineId}' AND cl.`drawer_type` = 1 ";
                if (!string.IsNullOrEmpty(drugName))
                {
                    SQL += $" and (di.drug_name like '%{drugName}%'|| di.py_code like '%{drugName}%'||di.drug_id like '%{drugName}%')";
                }
                SQL += " ORDER BY cl.`drug_id`";
                // 加载模板文件
                //Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "stock_template.grf");

                var reportList = _connection.FromSql<ReportStockDateInfo>(SQL);
                if (reportList != null)
                {
                    foreach (var report in reportList)
                    {
                        reportStockList.Add(report);
                    }

                    pagedData = await reportList.CountAsync();
                }
                return new PageData<ReportStockDateInfo>()
                {

                    TotalDesserts = pagedData,
                    Desserts = reportStockList
                };
            }
            catch (Exception ex)
            {
                logger.Info($"获取库存导出数据异常：{ex.Message}");
                return null;
            }
        }
        //中部战区总医院麻醉药品、第一类精神药品进出专用账册
        public async Task<PageData<ReportAccountDateInfo>> GetAccountExportData(DateTime? startDate, DateTime? endDate, string drugName)
        {
            List<ReportAccountDateInfo> accountList = new List<ReportAccountDateInfo>();
            int pagedData = 0;
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string SQL = $@"SELECT  ab.`create_time` AS `OperationTime`,ab.manu_no AS ManuNo,ab.eff_date as EffDate, ab.add_quantity AS `inQuantity`, 
                        ab.out_quantity AS `outQuantity`,ab.manu_quantity as ManuQuantity,ab.total_quantity as StockQuantity,
                         u1.`user_name` AS `operatorName`, u2.`user_name` AS `reviewerName`, ab.`drug_id` AS `drugId`,di.`drug_name` AS `drugName`,di.`drug_spec` AS `drugSpec`,  di.`pack_unit` AS `BigUnit`, di.`dosage` AS `dosage`,
                        di.`manufactory` AS `manufactory`,  ab.`invoice_id` AS `invoiceId`, ab.department as department,'' as Remarks FROM 
                        account_book ab  LEFT JOIN drug_info di ON ab.`drug_id` = di.`drug_id`  LEFT JOIN user_list u1 ON ab.`operator` = u1.`id`  
                        LEFT JOIN user_list u2 ON ab.`reviewer` = u2.`id` WHERE ab.`machine_id` = '{_setting.machineId}' AND ab.type in(1,2,31)  DATE_FORMAT(ab.`create_time`,'%Y-%m-%d') > '{p_startDate}'
                        AND  DATE_FORMAT(ab.`create_time`,'%Y-%m-%d') < '{p_endDate}'";
            if (!string.IsNullOrEmpty(drugName))
            {
                SQL += $" AND (di.drug_name like '%{drugName}%' or di.drug_id like '%{drugName}%' or di.py_code like '%{drugName}%')";
            }
            SQL += " ORDER BY ab.`create_time`, ab.`drug_id`";
            var reportList = _connection.FromSql<ReportAccountDateInfo>(SQL);
            if (reportList != null)
            {
                foreach (var report in reportList)
                {
                    accountList.Add(report);
                }

                pagedData = await reportList.CountAsync();
            }
            return new PageData<ReportAccountDateInfo>()
            {

                TotalDesserts = pagedData,
                Desserts = accountList
            };
        }
        //手术室患者麻醉药品使用登记本(主表数据)
        public async Task<List<ReportUsageParentDateInfo>> GetOrderInfoParentData(DateTime? searchDate)
        {
            //List<ReportUsageParentDateInfo> accountList = new List<ReportUsageParentDateInfo>();
            int pagedData = 0;

            string SQL = $@"SELECT od.drug_id drugId1, di.drug_Name drugName1,od.set_manu_No as manuNo1,sum(od.quantity) quantity1 ,oi.charge_Date as portDate
                            from order_info oi inner join order_detail od on oi.order_no=od.order_no inner join drug_info di on od.drug_id=di.drug_id
                            WHERE DATE_FORMAT(oi.charge_Date,'%Y-%m-%d')='{searchDate?.ToString("yyyy-MM-dd")}' and oi.dm_status=2 and oi.cancel_flag=0 and oi.his_disp_flag=0 and di.pack_h=1 group by od.drug_id,od.set_manu_No";




            var reportList =await _connection.FromSql<ReportUsageParentDateInfo>(SQL).ToListAsync();
            //if (reportList != null)
            //{
            //    foreach (var report in reportList)
            //    {
            //        accountList.Add(report);
            //    }

            //    pagedData = await reportList.CountAsync();
            //}
            return reportList;
        }

        //手术室患者麻醉药品使用登记本（子数据）
        public async Task<List<ReportUsageDateInfo>> GetOrderInfoData(DateTime? searchDate)
        { 
            string SQL = $@"SELECT oi.charge_Date as portdate, od.drug_id as DrugId,1 as ShouShuJian,oi.anaesthetist_code as doctor1,oi.anaesthetist_name as doctor2,oi.patient_id as patientId,oi.p_name as PName,oi.disease as Diagnose,
                           CONCAT(di.drug_name,' ',di.drug_spec)  as DrugName,od.set_manu_No as ManuNo,od.use_dosage as UsageDosage,'' as CanYeLiang,'' as CanYeChuZhi,'' as UseUserName,'' as CheckUserName,od.quantity as quantity
                            from order_info oi inner join order_detail od on oi.order_no=od.order_no inner join drug_info di on od.drug_id=di.drug_id
                            WHERE DATE_FORMAT(oi.charge_Date,'%Y-%m-%d')='{searchDate?.ToString("yyyy-MM-dd")}' and oi.dm_status=2 and oi.cancel_flag=0 and oi.his_disp_flag=0 and di.pack_h=1 order by oi.anaesthetist_code,oi.anaesthetist_name, od.drug_id";




            var reportList =await _connection.FromSql<ReportUsageDateInfo>(SQL).ToListAsync();
            return reportList;
        }

        //麻醉科毒麻药品请领登记表
        public async Task<PageData<ReportApplyInfo>> GetApplyInfoDate(DateTime searchDate)
        {
            List<ReportApplyInfo> accountList = new List<ReportApplyInfo>();
            int pagedData = 0;

            string SQL = $@"SELECT Drawerno as BoxNum,Create_date AS applyinfo,userfirst,usersecond,drugid,doctor,manager 
                            from applyinfo ap inner join drug_info di on ap.drugid=di.drug_id
                            WHERE machine_id='{_setting.boxMachineId}'  and DATE_FORMAT(ap.Create_date,'%Y-%m-%d')='{searchDate.ToString("yyyy-MM-dd")}' ";




            var reportList = _connection.FromSql<ReportApplyInfo>(SQL);
            if (reportList != null&& reportList.Count()>0)
            {
                foreach (var report in reportList)
                {
                    accountList.Add(report);
                }

                pagedData = await reportList.CountAsync();
            }
            return new PageData<ReportApplyInfo>()
            {

                TotalDesserts = pagedData,
                Desserts = accountList
            };
        } 
    }
}
