using PoJun.Dapper;
using ASHermed.SinoInterface.Api.IRepository.Test;
using ASHermed.SinoInterface.Entity.Test;
using ASHermed.SinoInterface.Repository.MySql;
using ASHermed.SinoInterface.Tools;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ASHermed.SinoInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.IRepository;
using ASHermed.SinoInterface.Api.MySqlRepository.OnlineAptInfo;

namespace ASHermed.SinoInterface.Api.MySqlRepository
{

    public class PrescriptionInfoRepository : BaseRepositoryToASHermed_SinoInterface<Out_Internet_Prescription_Info>, IPrescriptionInfoRepository
    {
        //public List<Dic_Coupon> SelectInId(string ids)
        //{
        //    var parms = new Dictionary<string, object>();
        //    parms.Add("@couponId", ids);
        //    var selectSql = @"select ID, COUPON_TYPE, CN_COUPON_NAME, EN_COUPON_NAME, CN_IMAGE, EN_IMAGE, PRICE,
        //       PERIOD_OF_VALIDITY,PERIOD_VALIDITY_UNIT,END_VALIDITY_DATE, TOTAL_COUNT, PER_COUNT,
        //       SINGLE_PERSON_LIMITED_UNIT,TIMES_LIMIT,EVERY_USING,CN_TEXT_ST,EN_TEXT_ST,CN_TEXT_ND,EN_TEXT_ND,
        //       STATUS, CREATE_USER,CREATE_TIME,
        //       UPDATE_TIME,REMARK,CN_DESCRIPTION,EN_DESCRIPTION
        //        from dic_coupon
        //        where ID in(@couponId)";
        //    var result = Query<Dic_Coupon>(selectSql, parms);
        //    return result.ToList();
        //}
        public int PrescriptionSign(string prescriptionNo, int status)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update out_internet_prescription_info set ");
            str.Append(@"STATUS=@STATUS");
            str.Append(@" where PRESCRIPTION_NO=@PRESCRIPTION_NO");
            var parms = new Dictionary<string, object>();
            parms.Add("@STATUS", status);
            parms.Add("@PRESCRIPTION_NO", prescriptionNo);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int UpdatePrescriptionStatus(int id, int status)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update out_internet_prescription_info set ");
            str.Append(@"STATUS=@STATUS");
            str.Append(@" where Id=@Id");
            var parms = new Dictionary<string, object>();
            parms.Add("@STATUS", status);
            parms.Add("@Id", id);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int UpdatePrescriptionStatusForOrder(string orderNo, int status)
        {
            StringBuilder str = new StringBuilder();
            str.Append("update out_internet_prescription_info set ");
            str.Append(@"STATUS=@STATUS");
            str.Append(@" where APPT_NUMBER=@APPTNUMBER");
            var parms = new Dictionary<string, object>();
            parms.Add("@STATUS", status);
            parms.Add("@APPTNUMBER", orderNo);
            var result = Execute(str.ToString(), parms);
            return result;
        }
        public int InsertPrescriptionInfo(PrescriptionReq req)
        {
            StringBuilder str = new StringBuilder();
            str.Append("insert into out_internet_prescription_info ");
            str.Append(@"(PatId,APPT_NUMBER,PRESCRIPTION_NO,PRESCRIPTION_DATE,PATIENT_NAME,PATIENT_SEX,PATIENT_AGE,PATIENT_BIRTHDAY,FEE_ZYPE,PATIENT_TEL,PATIENT_CARDNO,DEPT_NAME,DIAGNOSIS,DIAGNOSTICLNSTRUCTIONS_DETAILR,DRUG_ALLERGY_HISTORY,DOC_NAME,AUDITOR_NAME,RECEIPT_NAME,RECEIPT_PHONE,RECEIPT_ADDRESS,RECEIPT_REMARK,STATUS,AUDIT_STATUS,TOTAL_AMOUNT,AllergyHistory,Remark,Mrn,TCDelivery,InsuranceStatus,AdminAuditor) ");
            str.Append(" values ");
            str.Append(@"(@PatId,@APPT_NUMBER,@PRESCRIPTION_NO,@PRESCRIPTION_DATE,@PATIENT_NAME,@PATIENT_SEX,@PATIENT_AGE,@PATIENT_BIRTHDAY,@FEE_ZYPE,@PATIENT_TEL,@PATIENT_CARDNO,@DEPT_NAME,@DIAGNOSIS,@DIAGNOSTICLNSTRUCTIONS_DETAILR,@DRUG_ALLERGY_HISTORY,@DOC_NAME,@AUDITOR_NAME,@RECEIPT_NAME,@RECEIPT_PHONE,@RECEIPT_ADDRESS,@RECEIPT_REMARK,@STATUS,@AUDIT_STATUS,@TOTAL_AMOUNT,@AllergyHistory,@Remark,@Mrn,@TCDelivery,@InsuranceStatus,@AdminAuditor); ");
            var parms = new Dictionary<string, object>();
            parms.Add("@PatId", req.PatId);
            parms.Add("@APPT_NUMBER", req.OutRecordNo);
            parms.Add("@PRESCRIPTION_NO", req.PrescriptionNo);
            parms.Add("@PRESCRIPTION_DATE", req.PrescriptionDate);
            parms.Add("@PATIENT_NAME", req.PatientName);
            parms.Add("@PATIENT_SEX", req.PatientSex);

            parms.Add("@PATIENT_AGE", req.PatientAge);
            parms.Add("@PATIENT_BIRTHDAY", req.PatientBirthday);
            parms.Add("@FEE_ZYPE", req.FeeType);
            parms.Add("@PATIENT_TEL", req.PatientTel);
            parms.Add("@PATIENT_CARDNO", req.PatientCardno);

            parms.Add("@DEPT_NAME", req.DeptName);
            parms.Add("@DIAGNOSIS", req.Diagnosis);
            parms.Add("@DIAGNOSTICLNSTRUCTIONS_DETAILR", req.DiagnosticInstructionsDetailStr);
            parms.Add("@DRUG_ALLERGY_HISTORY", req.DrugAllergyHistory);
            parms.Add("@DOC_NAME", req.DocName);

            parms.Add("@AUDITOR_NAME", req.AuditorName);
            parms.Add("@RECEIPT_NAME", req.ReceiptName);
            parms.Add("@RECEIPT_PHONE", req.ReceiptPhone);
            parms.Add("@RECEIPT_ADDRESS", req.ReceiptAddrss);
            parms.Add("@RECEIPT_REMARK", req.ReceiptRemark);
            parms.Add("@Mrn", req.PID);

            parms.Add("@STATUS", 0);
            parms.Add("@AUDIT_STATUS", 0);
            parms.Add("@TOTAL_AMOUNT", req.TotalAmount);
            parms.Add("@AllergyHistory", string.IsNullOrEmpty(req.AllergyHistory) ? "" : req.AllergyHistory);
            parms.Add("@Remark", string.IsNullOrEmpty(req.Remark) ? "" : req.Remark);
            parms.Add("@TCDelivery", false);
            parms.Add("@InsuranceStatus", 0);
            parms.Add("@AdminAuditor", "");
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public int UpdatePrescription(string prescription)
        {
            var sql = @" update out_internet_prescription_info set IsDelete = 1 WHERE PRESCRIPTION_NO=@prescription";
            return Execute(sql, new { prescription = prescription });
        }

        public int InsertPrescriptionDrug(DrugsInfo req)
        {
            StringBuilder str = new StringBuilder();
            str.Append("insert into out_internet_prescription_drug ");
            str.Append(@"(DRUG_NAME,DRUG_SPEC,CNT,PACKAGE_UNIT,USELNTO,FREQUENCY,USE_DAY_SIZE,SINGLE_DOSAGE,DOSAGE_UNIT,`USAGE`,PRESCRIPTION_NO,UniqueCode,PackageUnitCode,FrequencyCode,DosageUnitCode,UsageCode,Remark,UseDaySizeUnit) ");
            str.Append(" values ");
            str.Append(@"(@DRUG_NAME,@DRUG_SPEC,@CNT,@PACKAGE_UNIT,@USELNTO,@FREQUENCY,@USE_DAY_SIZE,@SINGLE_DOSAGE,@DOSAGE_UNIT,@USAGE,@PRESCRIPTION_NO,@UniqueCode,@PackageUnitCode,@FrequencyCode,@DosageUnitCode,@UsageCode,@Remark,@UseDaySizeUnit) ");
            var parms = new Dictionary<string, object>();
            parms.Add("@DRUG_NAME", req.DrugName);
            parms.Add("@DRUG_SPEC", req.DrugSpec);
            parms.Add("@CNT", req.Cnt);
            parms.Add("@PACKAGE_UNIT", req.PackageUnit);
            parms.Add("@USELNTO", req.UseInfo);

            parms.Add("@FREQUENCY", req.Frequency);
            parms.Add("@USE_DAY_SIZE", req.UseDaySize);
            parms.Add("@SINGLE_DOSAGE", req.SingleDosage.ToString("0.##"));
            parms.Add("@DOSAGE_UNIT", req.DosageUnit);
            parms.Add("@USAGE", req.Usage);
            parms.Add("@UniqueCode", string.IsNullOrEmpty(req.UniqueCode) ? "" : req.UniqueCode);
            parms.Add("@PackageUnitCode", string.IsNullOrEmpty(req.PackageUnitCode) ? "" : req.PackageUnitCode);
            parms.Add("@FrequencyCode", string.IsNullOrEmpty(req.FrequencyCode) ? "" : req.FrequencyCode);
            parms.Add("@DosageUnitCode", string.IsNullOrEmpty(req.DosageUnitCode) ? "" : req.DosageUnitCode);
            parms.Add("@UsageCode", string.IsNullOrEmpty(req.UsageCode) ? "" : req.UsageCode);
            parms.Add("@Remark", string.IsNullOrEmpty(req.Remark) ? "" : req.Remark);
            parms.Add("@UseDaySizeUnit", string.IsNullOrEmpty(req.UseDaySizeUnit) ? "" : req.UseDaySizeUnit);

            parms.Add("@PRESCRIPTION_NO", req.PrescriptionNo);
            var result = Execute(str.ToString(), parms);
            return result;
        }

        public IEnumerable<Out_Internet_Prescription_Info> GetPrescription(int userid, int status, int prescriptionId, string useragent = "sino")
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT 	
                                        a.ID AS Id,
	                                    Mrn AS PID,
	                                    APPT_NUMBER AS Appt_Number,
	                                    PRESCRIPTION_NO AS Prescription_No,
	                                    PRESCRIPTION_DATE AS Prescription_Date,
	                                    PATIENT_NAME AS Patient_Name,
	                                    PATIENT_SEX AS Patient_Sex,
	                                    PATIENT_AGE AS Patient_Age,
	                                    PATIENT_BIRTHDAY AS Patient_Birthday,
	                                    FEE_ZYPE AS Fee_Zype,
	                                    PATIENT_TEL AS Patient_Tel,
	                                    PATIENT_CARDNO AS Patient_Cardno,
	                                    DEPT_NAME AS Dept_Name,
	                                    DIAGNOSIS AS Diagnosis,
	                                    DIAGNOSTICLNSTRUCTIONS_DETAILR AS Diagnosticlnstructions_Detailr,
	                                    DRUG_ALLERGY_HISTORY AS Drug_Allergy_History,
	                                    DOC_NAME AS Doc_Name,
	                                    AUDITOR_NAME AS Auditor_Name,
	                                    RECEIPT_NAME AS Receipt_Name,
	                                    RECEIPT_PHONE AS Receipt_Phone,
	                                    RECEIPT_ADDRESS AS Receipt_Address,
	                                    RECEIPT_REMARK AS Receipt_Remark,
	                                    a.STATUS AS Status,
	                                    AUDIT_STATUS AS Audit_Status,
	                                    TOTAL_AMOUNT  AS Total_Amount  
                            FROM out_internet_prescription_info a
                            INNER JOIN online_order b ON a.APPT_NUMBER=b.OrderNo
        	WHERE b.PatId IN (SELECT PAT_ID FROM pub_map_user_pat  WHERE USER_ID = @Userid) AND a.AUDIT_STATUS = 1 and a.IsDelete=0 ");
            if (status != -2)
            {
                if (status == 2)
                {
                    selectSql.Append(" AND a.`STATUS` in (2,3) ");
                }
                else
                {
                    selectSql.Append(" AND a.`STATUS` = @status ");
                }
            }//-2全部，0待支付 1待发货，2已发货
            else
            {
                if (useragent == "cigna")
                {
                    selectSql.Append(" AND (b.IsInsuranceUser = 1 and a.`STATUS` != 0)");
                }
            }
            if (prescriptionId != 0)
            {
                selectSql.Append(" AND a.ID=@PrescriptionId ");
            }
            selectSql.Append("  order by PRESCRIPTION_DATE DESC ");
            return Query<Out_Internet_Prescription_Info>(selectSql.ToString(), new { Userid = userid, Status = status, PrescriptionId = prescriptionId });
        }

        public IEnumerable<Out_Internet_Prescription_Info> GetPrescriptionForPatId(int patId, int status)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT 	
                                        a.ID AS Id,
	                                    Mrn AS PID,
	                                    APPT_NUMBER AS Appt_Number,
	                                    PRESCRIPTION_NO AS Prescription_No,
	                                    PRESCRIPTION_DATE AS Prescription_Date,
	                                    PATIENT_NAME AS Patient_Name,
	                                    PATIENT_SEX AS Patient_Sex,
	                                    PATIENT_AGE AS Patient_Age,
	                                    PATIENT_BIRTHDAY AS Patient_Birthday,
	                                    FEE_ZYPE AS Fee_Zype,
	                                    PATIENT_TEL AS Patient_Tel,
	                                    PATIENT_CARDNO AS Patient_Cardno,
	                                    DEPT_NAME AS Dept_Name,
	                                    DIAGNOSIS AS Diagnosis,
	                                    DIAGNOSTICLNSTRUCTIONS_DETAILR AS Diagnosticlnstructions_Detailr,
	                                    DRUG_ALLERGY_HISTORY AS Drug_Allergy_History,
	                                    DOC_NAME AS Doc_Name,
	                                    AUDITOR_NAME AS Auditor_Name,
	                                    RECEIPT_NAME AS Receipt_Name,
	                                    RECEIPT_PHONE AS Receipt_Phone,
	                                    RECEIPT_ADDRESS AS Receipt_Address,
	                                    RECEIPT_REMARK AS Receipt_Remark,
	                                    a.STATUS AS Status,
	                                    AUDIT_STATUS AS Audit_Status,
	                                    TOTAL_AMOUNT  AS Total_Amount  
                            FROM out_internet_prescription_info a
                            INNER JOIN online_order b ON a.APPT_NUMBER=b.OrderNo
        	WHERE b.PatId=@PatId And a.AUDIT_STATUS = 1 and a.IsDelete=0 ");
            if (status != -2)
            {
                if (status == 2)
                {
                    selectSql.Append(" AND a.`STATUS` in (2,3) ");
                }
                else
                {
                    selectSql.Append(" AND a.`STATUS` = @status ");
                }
            }
            else
            {
                //去掉状态不等于0是因为选择全部的时候，不需要看状态了
                //selectSql.Append(" AND (b.IsInsuranceUser = 1 and a.`STATUS` != 0)");
            }
            selectSql.Append(" order by PRESCRIPTION_DATE DESC ");
            return Query<Out_Internet_Prescription_Info>(selectSql.ToString(), new { PatId = patId, Status = status });
        }



        public IEnumerable<Out_Internet_Prescription_Drug> GetPrescriptionDrug(List<string> prescription)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT 	a.ID AS Id,
	                                    a.DRUG_NAME AS Drug_Name,
	                                    a.DRUG_SPEC AS Drug_Spec,
	                                    a.CNT AS Cnt,
	                                    a.PACKAGE_UNIT AS Package_Unit,
	                                    a.USELNTO AS Uselnto,
	                                    a.FREQUENCY AS Frequency,
	                                    a.USE_DAY_SIZE AS Use_Day_Size,
	                                    a.SINGLE_DOSAGE AS Single_Dosage,
	                                    a.DOSAGE_UNIT AS Dosage_Unit,
	                                    a.`USAGE` AS `Usage`,
	                                    a.PRESCRIPTION_NO  AS Prescripton_No,
                                        a.UniqueCode 
                                       -- b.Price
                               FROM out_internet_prescription_drug a 
                               -- inner join dic_medicine b on a.UniqueCode = b.UniqueCode
        	                    WHERE PRESCRIPTION_NO IN @Prescription ");
            var res = Query<Out_Internet_Prescription_Drug>(selectSql.ToString(), new { Prescription = prescription });
            DrugDetailEnum drug = new DrugDetailEnum();
            foreach (var item in res)
            {
                var drugdetail = drug.DrugList.Where(w => w.UniqueCode == item.UniqueCode || w.ARCIMDesc == item.UniqueCode)?.FirstOrDefault();
                if (drugdetail != null)
                {
                    item.DrugPrice = drugdetail.DrugPrice;
                }
            }
            return res;
        }

        public Out_Internet_Prescription_Info GetPrescriptionForId(string orderNo, int language = 1)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT 	
                                        a.ID AS Id,
	                                    Mrn AS PID,
	                                    APPT_NUMBER AS Appt_Number,
	                                    PRESCRIPTION_NO AS Prescription_No,
	                                    PRESCRIPTION_DATE AS Prescription_Date,
	                                    PATIENT_NAME AS Patient_Name,
	                                    PATIENT_SEX AS Patient_Sex,
	                                    PATIENT_AGE AS Patient_Age,
	                                    PATIENT_BIRTHDAY AS Patient_Birthday,
	                                    FEE_ZYPE AS Fee_Zype,
	                                    PATIENT_TEL AS Patient_Tel,
	                                    PATIENT_CARDNO AS Patient_Cardno, ");
            if (language == 1)
            {
                selectSql.Append(@"     d.CN_NAME AS Dept_Name,
	                                    DIAGNOSIS AS Diagnosis,
	                                    DIAGNOSTICLNSTRUCTIONS_DETAILR AS Diagnosticlnstructions_Detailr,
	                                    AllergyHistory AS AllergyHistory,
	                                    e.CN_NAME AS Doc_Name, ");
            }
            else
            {
                selectSql.Append(@"     d.EN_NAME AS Dept_Name,
	                                    DIAGNOSIS AS Diagnosis,
	                                    DIAGNOSTICLNSTRUCTIONS_DETAILR AS Diagnosticlnstructions_Detailr,
	                                    AllergyHistory AS AllergyHistory,
	                                    e.EN_NAME AS Doc_Name, ");
            }
            selectSql.Append(@"         AUDITOR_NAME AS Auditor_Name,
	                                    RECEIPT_NAME AS Receipt_Name,
	                                    RECEIPT_PHONE AS Receipt_Phone,
	                                    RECEIPT_ADDRESS AS Receipt_Address,
	                                    RECEIPT_REMARK AS Receipt_Remark,
	                                    a.STATUS AS Status,
	                                    AUDIT_STATUS AS Audit_Status,
	                                    TOTAL_AMOUNT  AS Total_Amount  
                            FROM out_internet_prescription_info a
                            LEFT JOIN online_order b ON a.APPT_NUMBER = b.OrderNo
                            LEFT JOIN online_apt_info c ON c.ID = b.AptId 
                            LEFT JOIN dic_dept d ON d.ID = c.DeptId 
                            LEFT JOIN dic_doctor e ON e.ID = b.DocId 
        	WHERE a.APPT_NUMBER=@APPT_NUMBER and a.IsDelete=0 ");
            var res = Query<Out_Internet_Prescription_Info>(selectSql.ToString(), new { APPT_NUMBER = orderNo }).FirstOrDefault();
            if (res != null)
            {
                if (language != 1)
                {
                    res.Patient_Sex = res.Patient_Sex == "男" ? "Male" : "Female";
                }
            }
            return res;
        }
        public List<Out_Internet_Prescription_Info> GetPrescriptionForIds(List<int> ids)
        {
            StringBuilder selectSql = new StringBuilder();
            selectSql.Append(@"SELECT 	
                                        a.ID AS Id,
	                                    Mrn AS PID,
	                                    APPT_NUMBER AS Appt_Number,
	                                    PRESCRIPTION_NO AS Prescription_No,
	                                    PRESCRIPTION_DATE AS Prescription_Date,
	                                    PATIENT_NAME AS Patient_Name,
	                                    PATIENT_SEX AS Patient_Sex,
	                                    PATIENT_AGE AS Patient_Age,
	                                    PATIENT_BIRTHDAY AS Patient_Birthday,
	                                    FEE_ZYPE AS Fee_Zype,
	                                    PATIENT_TEL AS Patient_Tel,
	                                    PATIENT_CARDNO AS Patient_Cardno,
	                                    DEPT_NAME AS Dept_Name,
	                                    DIAGNOSIS AS Diagnosis,
	                                    DIAGNOSTICLNSTRUCTIONS_DETAILR AS Diagnosticlnstructions_Detailr,
	                                    DRUG_ALLERGY_HISTORY AS Drug_Allergy_History,
	                                    DOC_NAME AS Doc_Name,
	                                    AUDITOR_NAME AS Auditor_Name,
	                                    RECEIPT_NAME AS Receipt_Name,
	                                    RECEIPT_PHONE AS Receipt_Phone,
	                                    RECEIPT_ADDRESS AS Receipt_Address,
	                                    RECEIPT_REMARK AS Receipt_Remark,
	                                    a.STATUS AS Status,
	                                    AUDIT_STATUS AS Audit_Status,
	                                    TOTAL_AMOUNT  AS Total_Amount  
                            FROM out_internet_prescription_info a
        	WHERE a.IsDelete=0 and a.ID IN @Ids ");
            return Query<Out_Internet_Prescription_Info>(selectSql.ToString(), new { Ids = ids }).ToList();
        }
        public int UpdateReceipt(int id, string name, string phone, string addr)
        {
            var sql = @" update out_internet_prescription_info set RECEIPT_NAME=@Name,RECEIPT_PHONE=@Phone,RECEIPT_ADDRESS=@Addr where ID=@ID ";
            return Execute(sql, new { ID = id, Name = name, Phone = phone, Addr = addr });
        }
    }
}
