using gregn6Lib;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DM_Weight.Models;
using System.Configuration;
using DM_Weight.util;
using System.Diagnostics;
namespace DM_Weight.Report
{
    public class GridReportUtil
    {
        // 定义Grid++Report报表主对象
        public static GridppReport Report = new GridppReport();
        public static string gridConnectionString = ConfigurationManager.AppSettings["gridConnectionString"];
        /**
         * 打印预览
         * tempname: 模板文件名称
         * data: 模板数据
         */
        public static void PrintReport(string tempname, object data)
        {
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            // 加载模板文件
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + tempname);
            string s = JsonConvert.SerializeObject(data);
            // 加载数据
            Report.LoadDataFromXML(JsonConvert.SerializeObject(data));
            Report.PrintPreview(true);
        }
        public static void PrintReportStock()
        {
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            //Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(() =>
            //{
            //    Report.ParameterByName("machine_id").Value = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            //});
            string machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            string SQL = $@"SELECT cl.`row_no` AS drawerNo,cl.`col_no` AS colNo,cl.`quantity` AS quantity,cl.`manu_no` AS manuNo,cl.`eff_date` AS effDate,
                          di.`drug_name` AS drugName,di.`drug_spec` AS drugSpec,di.`pack_unit` AS packUnit,di.`manufactory` AS manuFactory,di.`max_stock` AS baseQuantity,
                          cl.`drug_id` AS drugId FROM channel_stock cl INNER JOIN drug_info di ON di.`drug_id` = cl.`drug_id` WHERE cl.`machine_id` =  '{machine_id}' AND cl.`drawer_type` = 1 ORDER BY cl.`drug_id`";
            // 加载模板文件
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "stock_template.grf");
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
        }
        public static void PrintReportAccountBook(DateTime? startDate, DateTime? endDate)
        {
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            // 加载模板文件
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "account_book_temp.grf");
            string SQL = string.Empty;
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            //Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(() =>
            //{
            //    Report.ParameterByName("machine_id").Value = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            //    Report.ParameterByName("startDate").Value = startDate ?? Convert.ToDateTime("2010-1-1");
            //    Report.ParameterByName("endDate").Value = endDate ?? DateTime.Now.AddDays(1);
            //});
            //Report.DetailGrid.Recordset.QuerySQL = SQL;
            SQL = $@"SELECT  mr.`stock_quantity` AS `stockQuantity`, IF(mr.`type` IN (1, 31), mr.`quantity`, IF(mr.`type` = 4 AND mr.`quantity` > 0, mr.`quantity`, 0)) 
                        AS `inQuantity`, IF(mr.`type` = 2, mr.`quantity`, IF(mr.`type` = 4 AND mr.`quantity` < 0, (0 - mr.`quantity`), 0)) AS `outQuantity`,
                         mr.`operation_time` AS `operationTime`, mr.`invoice_id` AS `invoiceId`, di.`drug_name` AS `drugName`, di.`drug_id` AS `drugId`,
                         di.`drug_spec` AS `drugSpec`, di.`pack_unit` AS `packUnit`, di.`dosage` AS `dosage`, di.`manufactory` AS `manufactory`, 
                        mr.`manu_no` AS `manuNo`, mr.`eff_date` AS `effDate`, u1.`user_name` AS `operatorName`, u2.`user_name` AS `reviewerName` FROM 
                        dm_machine_record mr  LEFT JOIN drug_info di ON mr.`drug_id` = di.`drug_id`  LEFT JOIN user_list u1 ON mr.`operator` = u1.`id`  
                        LEFT JOIN user_list u2 ON mr.`reviewer` = u2.`id` WHERE mr.`machine_id` = '{p_machine_id}' AND mr.`operation_time` > '{p_startDate}'
                        AND mr.`operation_time` < '{p_endDate}'  ORDER BY mr.`drug_id`, mr.`operation_time`, mr.`id`";
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
        }
        public static void PrintReportAccountBook(DateTime? startDate, DateTime? endDate, int type, string drug_id)
        {
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            // 加载模板文件
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "account_book_temp.grf");
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            string SQL = $@" SELECT ac.create_date as operationTime, ac.TYPE,
	                     if(ac.type in(1,2),0,ac.yesterday_quantity) as YQuantity,if(ac.type in(3,4),0,ac.add_quantity) as inQuantity,if(ac.type in(3,4),0,ac.out_quantity) as outQuantity,
	                     if(ac.type in(1,2),0,ac.manu_stock) as ManuStock,ac.total_stock AS stockQuantity, -- if(ac.type in(1,2),0,ac.total_stock) as TotalStock,
	                     ac.invoice_no as invoiceId, ac.manu_no as manuNo,ac.eff_date as effDate,di.drug_id,di.drug_name as DrugName,di.drug_spec as DrugSpec,di.manufactory as manufactory,di.pack_unit AS packUnit,di.dosage,u1.user_name as operatorName,u2.user_name as reviewerName
	                     FROM account_book_g2 ac left join drug_info di on ac.drug_id=di.drug_id left join user_list u1 on ac.user_id1=u1.id left join user_list u2 on ac.user_id2=u2.id
 		                    WHERE ac.machine_id='{p_machine_id}' and create_time>'{p_startDate}' AND create_time<'{p_endDate}' ";
            if (!string.IsNullOrEmpty(drug_id))
            {
                SQL += " AND ac.drug_id='" + drug_id + "' ";
            }
            if (type > 0)
            {
                if (type == 1)
                {
                    SQL += " WHERE AddQuantity>0 ";
                }
                if (type == 2)
                {
                    SQL += " WHERE OutQuantity>0 ";
                }
                if (type == 3)
                {
                    SQL += " WHERE type=3 ";
                }
                if (type == 4)
                {
                    SQL += " WHERE type=4  ";
                }
            }
            SQL += " ORDER BY di.drug_id,ac.create_date desc";
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
            //string filePath = AppDomain.CurrentDomain.BaseDirectory + "ReportTemp//" + "account_book_temp.pdf";
            //if (File.Exists(filePath))
            //{
            //    try
            //    {
            //        File.Delete(filePath);
            //    }
            //    catch (Exception ex)
            //    {
            //        FindAndKillProcess();
            //    }
            //}
            //Report.ExportDirect(GRExportType.gretPDF, filePath, false, true);
        }
        public static void PrintReportMechineRecord(int type, DateTime? startDate, DateTime? endDate)
        {
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            string SQL = string.Empty;
            //Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(() =>
            //{
            //    Report.ParameterByName("machine_id").Value = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            //    Report.ParameterByName("startDate").Value = startDate??DateTime.Now.AddYears(-10);
            //    Report.ParameterByName("endDate").Value = endDate??DateTime.Now.AddDays(1);
            //});
            // 加载模板文件
            if (type == 1)
            {
                Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "machine_log_add.grf");
                SQL = $@"SELECT dmr.`drawer_no` AS drawerNo,dmr.`col_no` AS colNo,dmr.`type` AS `type`,dmr.`quantity` AS quantity,
                      dmr.`manu_no` AS manuNo,dmr.`eff_date` AS effDate,dmr.`operation_time` AS operationTime,
                      di.`drug_name` AS drugName,di.`drug_spec` AS drugSpec,di.`pack_unit` AS packUnit,
                      di.`manufactory` AS manuFactory,di.`max_stock` AS baseQuantity,dmr.`drug_id` AS drugId,
                      ul.`user_name` AS nickname FROM dm_machine_record dmr LEFT JOIN drug_info di ON di.`drug_id` = dmr.`drug_id`
                    LEFT JOIN user_list ul ON ul.`id` = dmr.`Operator` WHERE dmr.`type` = 1 AND dmr.`machine_id` = '{p_machine_id}'
                     AND dmr.`operation_time` > '{p_startDate}' AND dmr.`operation_time` < '{p_endDate}'";
            }
            else if (type == 2)
            {
                Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "machine_log_take.grf");
                SQL = $@" SELECT dmr.`drawer_no` AS drawerNo,dmr.`col_no` AS colNo,dmr.`type` AS `type`,dmr.`quantity` AS quantity,
                      dmr.`manu_no` AS manuNo,dmr.`eff_date` AS effDate,dmr.`operation_time` AS operationTime,
                      di.`drug_name` AS drugName,di.`drug_spec` AS drugSpec,di.`pack_unit` AS packUnit,
                      di.`manufactory` AS manuFactory,di.`max_stock` AS baseQuantity,dmr.`drug_id` AS drugId,
                      ul.`user_name` AS nickname FROM dm_machine_record dmr LEFT JOIN drug_info di ON di.`drug_id` = dmr.`drug_id`
                    LEFT JOIN user_list ul ON ul.`id` = dmr.`Operator` WHERE dmr.`type` = 2 
                     AND dmr.`machine_id` ='{p_machine_id}'  AND dmr.`operation_time` > '{p_startDate}'
                     AND dmr.`operation_time` < '{p_endDate}'";
            }
            else if (type == 3)
            {
                Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "machine_log_return.grf");
                SQL = $@" SELECT dmr.`drawer_no` AS drawerNo,dmr.`col_no` AS colNo,dmr.`type` AS `type`,
                      CONCAT(dmr.`quantity`,IF(dmr.`type`=32,""(空瓶)"","""")) AS quantity,dmr.`manu_no` AS manuNo,
                      dmr.`eff_date` AS effDate,dmr.`operation_time` AS operationTime,di.`drug_name` AS drugName,
                      di.`drug_spec` AS drugSpec,di.`pack_unit` AS packUnit,
                      di.`manufactory` AS manuFactory,di.`max_stock` AS baseQuantity,
                      dmr.`drug_id` AS drugId,ul.`user_name` AS nickname FROM dm_machine_record dmr
                    LEFT JOIN drug_info di ON di.`drug_id` = dmr.`drug_id` LEFT JOIN user_list ul ON ul.`id` = dmr.`Operator`
                    WHERE dmr.`type` in (31, 32) AND dmr.`machine_id` = '{p_machine_id}' AND dmr.`operation_time` > '{p_startDate}'
                     AND dmr.`operation_time` < '{p_endDate}'";
            }
            else
            {
                Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "machine_log_check.grf");
                SQL = $@" SELECT dmr.`drawer_no` AS drawerNo,dmr.`col_no` AS colNo,dmr.`type` AS `type`,dmr.`quantity` AS quantity,
                          dmr.`manu_no` AS manuNo,dmr.`eff_date` AS effDate,dmr.`operation_time` AS operationTime,
                          di.`drug_name` AS drugName,di.`drug_spec` AS drugSpec,di.`pack_unit` AS packUnit,
                          di.`manufactory` AS manuFactory,di.`max_stock` AS baseQuantity,dmr.`drug_id` AS drugId,
                          ul.`user_name` AS nickname FROM dm_machine_record dmr LEFT JOIN drug_info di ON di.`drug_id` = dmr.`drug_id`
                        LEFT JOIN user_list ul ON ul.`id` = dmr.`Operator` WHERE dmr.`type` = 4 
                         AND dmr.`machine_id` = '{p_machine_id}' AND dmr.`operation_time` > '{p_startDate}'
                        AND dmr.`operation_time` < '{p_endDate}'";
            }
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
        }
        //交接班记录报表
        public static void PrintChangeShiftsReport(DateTime? startDate, DateTime? endDate)
        {
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            // 加载模板文件
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "changeShifts_temp.grf");
            string SQL = string.Empty;
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            Report.Initialize += new _IGridppReportEvents_InitializeEventHandler(() =>
            {
                Report.ParameterByName("machine_id").Value = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
                Report.ParameterByName("startDate").Value = startDate ?? Convert.ToDateTime("2010-1-1");
                Report.ParameterByName("endDate").Value = endDate ?? DateTime.Now.AddDays(1);
            });
            SQL = $@"SELECT opt_date,drug_name,drug_spec,beforenum,getnum,usenum,manu_no,surplus,CONCAT(fromoperator,' ',fromreviewer) as fromoperator,
                    CONCAT(tooperator,' ',toreviewer) as tooperator
                    from `hkc_shiftsreport` WHERE `machineid` = '{p_machine_id}' AND `opt_date` > '{p_startDate}'
                        AND opt_date < '{p_endDate}'  ORDER BY opt_date";
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            //Report.PrintPreview(true);
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "ReportTemp//" + "changeShifts_temp.pdf";
            if (File.Exists(filePath))
            {
                try
                {
                    File.Delete(filePath);
                }
                catch (Exception ex)
                {
                    FindAndKillProcess();
                }
            }
            Report.ExportDirect(GRExportType.gretPDF, filePath, false, true);
        }
        public static bool FindAndKillProcess()
        {
            foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.Contains("wps") || clsProcess.ProcessName.Contains("msedge"))
                {
                    clsProcess.Kill();
                    //return true;
                }
            }
            //process not found, return false
            return false;
        }
        /// 
        /// 空安瓿回收销毁报表
        /// 
        /// 
        /// 
        public static void PrintEmptyDestoryReport(DateTime? startDate, DateTime? endDate)
        {
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            string SQL = string.Empty;
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "ReturnEmptyDistory_template.grf");
            SQL = $@"
                    SELECT di.drug_id, di.drug_name as drugName,di.dosage,di.drug_spec as drugSpec,di.big_unit,oi.Order_Date, CONCAT(oi.p_name,'/',oi.dept_name) as userDeptName,
                    od.Quantity,mr.Manu_No,ul.user_name as retuenUser,u2.user_name as returnReviewer,u3.User_name as distoryUser,u4.User_name as distoryRevierer,(od.Quantity-mr.return_quantity2) as needReturnEmptyCount
                    from order_info oi inner join order_detail od on oi.order_no=od.order_no 
                    inner join (SELECT id as mrId,manu_no,invoice_id,id,operator,reviewer, sum(return_quantity2) as return_quantity2  FROM dm_machine_record where type=2  and machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}'  GROUP BY invoice_id) mr on oi.order_no=mr.invoice_id 
                    INNER JOIN drug_info di on od.drug_id=di.drug_id
                    LEFT JOIN (SELECT manu_no,invoice_id,id,operator,reviewer,get_id  from dm_machine_record where type=32  and machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') re on re.get_id=mr.id 
                    LEFT JOIN (SELECT recordId,operatorid,reviewerid,machine_id FROM destory_detail WHERE machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') ddl on re.id=ddl.recordId 
                    -- LEFT JOIN (SELECT User_name,machine_id,id FROM user_list  WHERE machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') ul0 on mr.operator=ul0.id
                    -- LEFT JOIN (SELECT User_name,machine_id,id FROM user_list  WHERE machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') ul00 on re.reviewer=ul00.id 
                    LEFT JOIN (SELECT User_name,machine_id,id FROM user_list  WHERE machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') ul on re.operator=ul.id 
                    LEFT JOIN (SELECT User_name,machine_id,id FROM user_list  WHERE machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') u2 on re.reviewer=u2.id 
                    LEFT JOIN (SELECT User_name,machine_id,id FROM user_list  WHERE machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') u3 on ddl.operatorid=u3.id 
                    LEFT JOIN  (SELECT User_name,machine_id,id FROM user_list  WHERE machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') u4 on ddl.reviewerid=u4.id 
                    WHERE
                    oi.Pharmacy='{ConfigurationManager.AppSettings["storage"] ?? ""}' and oi.Order_Date>'{startDate}' and oi.Order_Date<'{endDate}' GROUP BY Order_Date";
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
        }
        /// 
        /// 发药登记表
        /// 
        /// 
        /// 
        public static void OrderUseReport(DateTime? startDate,DateTime? endDate, string drug_id)
        { 
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            string SQL = string.Empty;
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "orderUse_template.grf");
            SQL = $@"
                    SELECT oi.p_name,oi.age,oi.sex,oi.id_number,oi.patientno,oi.disease,od.drug_id,oi.doctor_name,oi.order_no,oi.order_date,
	                    dmr.id,dmr.`drawer_no` AS drawerNo,dmr.`col_no` AS colNo,dmr.`type` AS `type`,dmr.`quantity` AS quantity,
                      dmr.`manu_no` AS manuNo,dmr.`eff_date` AS effDate,dmr.`operation_time` AS operationTime,
                      di.`drug_name` AS drugName,di.`drug_spec` AS drugSpec,di.`pack_unit` AS packUnit,
                      di.`manufactory` AS manuFactory,di.`max_stock` AS baseQuantity,dmr.`drug_id` AS drugId,
                      ul.`user_name` AS nickname,U2.`user_name` AS reviewNickname FROM dm_machine_record dmr 
					  
					  INNER JOIN ORDER_INFO oi on dmr.invoice_id=oi.order_no
					  INNER JOIN order_detail od on oi.order_no=od.order_no and oi.order_id=od.order_id
					  
					  LEFT JOIN drug_info di ON di.`drug_id` = dmr.`drug_id`
                      LEFT JOIN (select id,user_name from user_list where machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') ul ON ul.`id` = dmr.`Operator` 
                     LEFT JOIN (select id,user_name from user_list where machine_id='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}') U2 ON U2.ID=dmr.reviewer
                     WHERE  dmr.`type` = 2  and oi.Pharmacy='{ConfigurationManager.AppSettings["storage"] ?? ""}'
                     AND dmr.`machine_id` ='{ConfigurationManager.AppSettings["machineId"] ?? "DM3"}'   AND oi.`order_date` > '{startDate}'
                     AND oi.`order_date` < '{endDate}'";
            if (!string.IsNullOrEmpty(drug_id))
            {
                SQL += " AND ac.drug_id='" + drug_id + "' ";
            }
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
        }
        /// 
        /// 使用登记册
        /// 能按麻醉师名字、时间结合起来查找
        /// 
        public static void UserAccount(DateTime? startDate,DateTime? endDate,string Name,string box)
        {
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            string SQL = string.Empty;
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "account_use_temp.grf");
            SQL = $@"                     
                     SELECT re.create_time as OptDate, di.drug_name as DrugName,di.Drug_spec as DrugSpec,dt.Set_manu_no as ManuNo,re.patient_name as PName,
                     CONCAT(use_dose,dose_unit) as UDose,CONCAT(residual_dose,dose_unit) as ReDose,if(residual_dose>0,'是','否') as Disposal,
                     re.anaesthetist_name as AName,re.operator_name as OName,re.supervisor_name as CName,of.operator as EmpRecive,'彭蕾' as EmpMedicRecive,re.disposal_time as DisposalTime,SUBSTRING_INDEX(of.win_no, '号', 1) as WinNo,re.card_no as cardNo
	                 from surgical_residual re inner join drug_info di on re.drug_id=di.drug_id inner join hkc_order_finish of on re.order_no=of.order_no and of.state=2  left join order_detail_sm dt on re.order_no=dt.order_no 
                     where re.create_time  > '{startDate}' and re.create_time< '{endDate}'";
            if (!string.IsNullOrEmpty(Name))
            {
                SQL += " AND re.anaesthetist_name='" + Name + "' ";
            }
            if(!string.IsNullOrEmpty(box))
            {
                SQL+= " AND of.win_no='" + box + "' ";
            }
            SQL += " ORDER BY re.create_time";
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
        }
        public static void PrintReportAccountBook(DateTime? startDate, DateTime? endDate, string drug_id)
        {
            // 定义Grid++Report报表主对象
            GridppReport Report = new GridppReport();
            // 加载模板文件
            Report.LoadFromFile(new FileInfo(AppDomain.CurrentDomain.BaseDirectory) + "ReportTemp//" + "account_book_new.grf");
            Report.DetailGrid.Recordset.ConnectionString = gridConnectionString;
            DateTime? p_startDate = startDate ?? Convert.ToDateTime("2010-1-1");
            DateTime? p_endDate = endDate ?? DateTime.Now.AddDays(1);
            string p_machine_id = (ConfigurationManager.AppSettings["machineId"] ?? "DM1");
            string SQL = $@"  select ab.drug_id, ab.type,
		                      di.drug_name AS DrugName,di.Drug_spec AS DrugSpec,di.big_unit AS BigUnit,di.small_unit AS SmallUnit, 
		                      DATE_FORMAT(ab.create_date,'%Y/%m/%d') AS YearMD,ab.manu_no AS ManuNo,DATE_FORMAT(ab.eff_date,'%Y%m%d') AS effDate,IF(ab.type=2,'',ab.add_quantity) AS InQuantity,ab.shoushuJian AS shoushuJian,
		                      re.Patient_name AS PName,re.sex AS Sex,re.age AS Age,IF(ab.type=3,ab.use_dose,re.use_dose) AS UseDose,IF(ab.type=3,ab.residual_dose,re.residual_dose) AS ResidualDose,re.create_time AS DiposalTime
                              ,re.operator_name, ab.manu_stock AS Stock,ab.total_stock AS empty,ab.total_stock,UL.User_name  AS SendUser,
							  IF(ab.type=1,UL.User_name,UL2.User_name) AS InCheckUser,
                                re.supervisor_name AS CheckUser,ab.manu_stock,ab.total_stock,ab.user_id1,ab.user_id2,ab.out_Quantity 
                              ,DB.BASEQUANTITY AS BaseQuantity,re.card_no AS ZYH,oi.dept_name AS KS,re.anaesthetist_name AS YS,
                              IF(ab.`type`=1,'',UL.User_name) AS emptyUser,
                              (SELECT sum(quantity) from channel_stock cs where cs.drug_id=ab.drug_id and cs.manu_no=ab.manu_no and cs.machine_id in('DM3','DM5')) AS CurrentStock
		                      from account_book_g2 ab inner join drug_info di on ab.drug_id=di.Drug_ID 
                              LEFT JOIN DRUG_BASE DB ON di.DRUG_ID=DB.DRUGID AND DB.MACHINE_ID='DM3'
                              LEFT JOIN order_info_sm oi on ab.invoice_no=oi.order_no
		                      LEFT JOIN user_list UL ON ab.user_id1=UL.ID  
		                      LEFT JOIN user_list UL2 ON ab.user_id2=UL.ID 
		                      LEFT JOIN surgical_residual re on ab.invoice_no=re.order_no  WHERE ab.machine_id='DM3' and ab.type in(1,2,3) and 		                      
		                      ab.create_time>'{p_startDate}' AND ab.create_time<'{p_endDate}' ";
            if (!string.IsNullOrEmpty(drug_id))
            {
                SQL += " AND ab.drug_id='" + drug_id + "' ";
            }
            SQL += " ORDER BY ab.create_date asc,ab.drug_id,ab.Manu_No,ab.id ";
            Report.DetailGrid.Recordset.QuerySQL = SQL;
            Report.PrintPreview(true);
        }
    }
}