using ASHermed.AdminInterface.Api.ContractModel;
using ASHermed.SinoInterface.Api.ContractModel.App;
using ASHermed.SinoInterface.Api.IRepository;
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;

namespace ASHermed.SinoInterface.Api.MySqlRepository
{
    public class OnlineBillRepository : BaseRepositoryToASHermed_SinoInterface<Online_Bill>, IOnlineBillRepository
    {
        public int InsertOnlineBill(Online_Bill bill)
        {
            var sql = @" INSERT INTO `online_bill`(`PatId`, `OrderNo`, `PrescriptionOrderNo`, `BillNo`, `BillCreateTime`, `BillPrice`, `DocId`, `DeptId`, `ConsultationFee`, `DrugCost`, `ChannelCode`, `ChannelPayType`, `BillType`, `AptType`) VALUES(@PatId, @OrderNo, @PrescriptionOrderNo, @BillNo, @BillCreateTime,@BillPrice, @DocId, @DeptId, @ConsultationFee, @DrugCost, @ChannelCode, @ChannelPayType, @BillType, @AptType); ";
            return Execute(sql, bill);
        }
        public PageListModel<OnlineBillList> GetOnlineBillList(int billType, string search, DateTime begin, DateTime end, int channelCode, int channelPayType, int pageindex, int pagesize)
        {
            PageListModel<OnlineBillList> response = new PageListModel<OnlineBillList>();
            var sql = @" SELECT SQL_CALC_FOUND_ROWS
	                            b.PAT_NAME AS PatName,
	                            b.PAT_MRN AS Pid,
	                            b.PHONE_NO AS Phone,
	                            c.CN_NAME AS DocName,
	                            d.CN_NAME AS DeptName,
	                            a.* 
                            FROM
	                            online_bill a
	                            INNER JOIN pub_pat_info b ON a.PatId = b.Id
	                            LEFT JOIN dic_doctor c ON a.DocId = c.ID
	                            LEFT JOIN dic_dept d ON a.DeptId = d.ID WHERE a.BillType=@BillType ";
            if (!string.IsNullOrEmpty(search))
            {
                sql += " And (b.PAT_NAME Like CONCAT('%',@Search,'%') OR b.PAT_MRN Like CONCAT('%',@Search,'%') OR a.OrderNo Like CONCAT('%',@Search,'%') OR a.PrescriptionOrderNo Like CONCAT('%',@Search,'%') OR a.BillNo Like CONCAT('%',@Search,'%')) ";
            }
            if (begin != DateTime.MinValue && end != DateTime.MaxValue)
            {
                sql += " And a.BillCreateTime>=@BeginDate ";
            }
            if (end != DateTime.MinValue && end != DateTime.MaxValue)
            {
                sql += " And a.BillCreateTime<=@EndDate ";
            }
            if (channelCode != 0)
            {
                sql += " And a.ChannelCode=@ChannelCode ";
            }
            if (channelPayType != 0)
            {
                sql += " And a.ChannelPayType=@ChannelPayType ";
            }
            sql += " ORDER BY a.BillCreateTime Desc  limit @PageIndex,@PageSize; ";
            var result = QueryPageList<OnlineBillList>(sql, "select FOUND_ROWS() AS Count", new { BillType = billType, BeginDate = begin, EndDate = end, ChannelCode = channelCode, ChannelPayType = channelPayType, PageIndex = ((pageindex - 1) * pagesize), PageSize = pagesize });
            response.PageList = result.Data.ToList().DeEncrypt();
            response.TotalCount = (int)result.Count;
            return response;
        }

        public Online_Bill GetOnlineBill(string billNo)
        {
            var sql = @" Select * from online_bill Where BillNo=@BillNo ";
            return Query<Online_Bill>(sql, new { BillNo = billNo })?.FirstOrDefault();
        }

        public PatInfoDetail GetPatInfoForBill(string orderNo)
        {
            var sql = @" SELECT
	                            b.ID AS PatId,
	                            b.PAT_NAME AS PatName,
	                            b.GENDER AS Gender,
	                            b.PAT_MRN AS Pid,
	                            b.BIRTHDAY AS BirthDay,
	                            b.CARD_ID AS CardId,
	                            b.PHONE_NO AS Phone,
	                            b.EMAIL AS Email,
	                            c.InsuranceCard,
	                            c.InsuranceCompany,
	                            c.InsuranceName,
                              c.ID AS InsuranceId
                            FROM
                              online_order a 
                              INNER JOIN	pub_pat_info b ON a.PatId = b.ID
                               LEFT JOIN pub_insurance c ON c.ID = a.InsuranceId
                            WHERE
	                            a.OrderNo = @OrderNo ";
            return Query<PatInfoDetail>(sql, new { OrderNo = orderNo })?.FirstOrDefault().DeEncrypt();
        }

        public AptInfoDetail GetAptInfoForBill(string orderNo)
        {
            var sql = @"select   a.OrderNo,
			                     a.AptTime,
			                     a.StartVisitTime,
			                     a.PayPrice,
			                     a.AptPrice,
			                     d.CN_NAME AS DeptName,
			                     f.CN_NAME AS DocName,
			                     a.AptType,
			                     c.CheifComplaint,
			                     c.HistoryPresentIllness,
			                     c.PastMedicalHistory,
			                     c.AllergyHistory,
			                     c.Diagnosis,
			                     c.DealWith,
			                     b.Suggest,
			                     b.Note
                    from online_order a 
                    INNER JOIN online_apt_info b on a.AptId = b.Id
                    LEFT JOIN dic_diagnosis c ON a.OrderNo = c.OutTradeNo
                    LEFT JOIN dic_dept d ON b.DeptId = d.ID 
                    LEFT JOIN dic_doctor f ON b.DocId = f.ID
                    WHERE a.OrderNo = @OrderNo ";
            return Query<AptInfoDetail>(sql, new { OrderNo = orderNo })?.FirstOrDefault();
        }

        public PrescriptionDetail GetPrescription(string prescriptionOrderNo)
        {
            var sql = @" SELECT
	                            a.OrderNo AS PrescriptionOrderNo,
	                            b.APPT_NUMBER AS OrderNo,
	                            a.CreateTime,
	                            b.TOTAL_AMOUNT AS TotalAmount,
	                            b.DEPT_NAME AS DeptName,
	                            b.DOC_NAME AS DocName,
	                            b.AdminAuditor,
	                            b.DIAGNOSIS AS Diagnosis,
	                            b.PRESCRIPTION_NO AS PrescriptionNo 
                            FROM
	                            online_order a
	                            INNER JOIN out_internet_prescription_info b ON a.AptId = b.ID
	                            WHERE a.AptType = 3 AND a.OrderNo = @OrderNo ";
            return Query<PrescriptionDetail>(sql, new { OrderNo = prescriptionOrderNo })?.FirstOrDefault();
        }
    }
}
