package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gdyb/models"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"
	_ "unsafe"
)

// 人员基本信息
func ZHGdyb1101(certNo string, org_name string, doctor string, fixmedins_code string, insuplc_admdvs string, mdtrtarea_admvs string, secret_key string, id_card_type int64, card_sn string, certificates int64, name string) (string, string, string) {
	//生成签名
	var requestLog string
	var resultLog string
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)
	//生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "1101" // 交易编码

	if certificates == 3 {
		inputData["mdtrt_cert_type"] = "99" // 就诊凭证类型
		inputData["certno"] = certNo        // 证件号码
		inputData["psn_cert_type"] = "99"   // 人员证件类型

	} else {
		if id_card_type == 1 {
			inputData["mdtrt_cert_type"] = "03" // 就诊凭证类型
			inputData["card_sn"] = card_sn      // 卡识别码
			inputData["certno"] = certNo        // 证件号码
			inputData["psn_cert_type"] = "1"    // 人员证件类型

		} else {
			inputData["mdtrt_cert_type"] = "02" // 就诊凭证类型
			inputData["card_sn"] = ""           // 卡识别码
			inputData["certno"] = certNo        // 证件号码
			inputData["psn_cert_type"] = "1"    // 人员证件类型
		}
	}

	inputData["mdtrt_cert_no"] = certNo // 就诊凭证编号
	inputData["begntime"] = ""          // 开始时间
	inputData["psn_name"] = name        // 人员姓名
	input["data"] = inputData
	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	requestLog = string(bytesData)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), "", ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")
	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/1101"
	url := gdyb_url + "1101"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/1101"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), "", ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), "", ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), "", ""
	}
	fmt.Println(string(respBytes))
	str := string(respBytes)
	resultLog = str
	return str, requestLog, resultLog
}

type DiseinfoStruct struct {
	PsnNo        string
	DiagType     string
	MaindiagFlag string
	DiagSrtNo    string
	DiagCode     string
	DiagName     string
	DiagDept     string
	DiseDorNo    string
	DiseDorName  string
	DiagTime     string
}
type Struct2401 struct {
	PsnNo            string
	Insutype         string
	MdtrtCertType    string
	MdtrtCertNo      string
	MedType          string
	IptNo            string
	AtddrNo          string
	ChfpdrName       string
	AdmDiagDscr      string
	AdmDeptCodg      string
	AdmDeptName      string
	AdmBed           string
	DscgMaindiagCode string
	DscgMaindiagName string
	Diseinfo         []DiseinfoStruct
	Begntime         string
	DiseCodg         string
	DiseName         string
}

// 住院登记
func ZHGdyb2401(struct2401 Struct2401, secret_key string, org_name string, fixmedins_code string, doctor string, insuplc_admdvs string, mdtrtarea_admvs string) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)
	//tempTime := time.Unix(timestamp, 0)
	//timeFormatOne := tempTime.Format("2006-01-02 15:04:05")

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2401"              // 交易编码
	inputData["psn_no"] = struct2401.PsnNo      // 人员编号 （来自1101接口返回）
	inputData["insutype"] = struct2401.Insutype // 险种类型（来自1101接口返回）
	inputData["tel"] = ""
	inputData["coner_name"] = ""
	inputData["begntime"] = struct2401.Begntime         // 开始时间
	inputData["mdtrt_cert_type"] = "02"                 // 就诊凭证类型
	inputData["mdtrt_cert_no"] = struct2401.MdtrtCertNo // 就诊凭证编号
	inputData["med_type"] = struct2401.MedType          // 就诊凭证编号
	inputData["ipt_no"] = struct2401.IptNo              // 住院/门诊号
	inputData["medrcdno"] = ""
	inputData["atddr_no"] = struct2401.AtddrNo
	inputData["chfpdr_name"] = struct2401.ChfpdrName
	inputData["adm_diag_dscr"] = struct2401.AdmDiagDscr
	inputData["adm_dept_codg"] = struct2401.AdmDeptCodg
	inputData["adm_dept_name"] = struct2401.AdmDeptName
	inputData["adm_bed"] = struct2401.AdmBed
	inputData["dscg_maindiag_code"] = struct2401.DscgMaindiagCode
	inputData["dscg_maindiag_name"] = struct2401.DscgMaindiagName
	inputData["main_cond_dscr"] = ""
	inputData["dise_codg"] = struct2401.DiseCodg
	inputData["dise_name"] = struct2401.DiseName
	inputData["oprn_oprt_code"] = ""
	inputData["oprn_oprt_name"] = ""
	inputData["fpsc_no"] = ""
	inputData["matn_type"] = ""
	inputData["birctrl_type"] = ""
	inputData["latechb_flag"] = ""
	inputData["geso_val"] = ""
	inputData["fetts"] = ""
	inputData["fetus_cnt"] = ""
	inputData["pret_flag"] = ""
	inputData["birctrl_matn_date"] = ""
	inputData["dise_type_code"] = ""

	inputDataArr := make([]map[string]interface{}, 0)
	for _, item := range struct2401.Diseinfo {
		inputDataTwo := make(map[string]interface{})
		inputDataTwo["psn_no"] = item.PsnNo
		inputDataTwo["diag_type"] = item.DiagType
		inputDataTwo["maindiag_flag"] = item.MaindiagFlag
		inputDataTwo["diag_srt_no"] = item.DiagSrtNo
		inputDataTwo["diag_code"] = item.DiagCode
		inputDataTwo["diag_name"] = item.DiagName
		inputDataTwo["adm_cond"] = ""
		inputDataTwo["diag_dept"] = item.DiagDept
		inputDataTwo["dise_dor_no"] = item.DiseDorNo
		inputDataTwo["dise_dor_name"] = item.DiseDorName
		inputDataTwo["diag_time"] = item.DiagTime
		inputDataArr = append(inputDataArr, inputDataTwo)
	}
	input["mdtrtinfo"] = inputData
	input["diseinfo"] = inputDataArr
	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	requestLog := string(bytesData)

	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")
	url := gdyb_url + "2401"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""

	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""

	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""

	}
	str := string(respBytes)
	fmt.Println(str)
	return str, requestLog
}

//住院撤销
func ZHGdyb2404(mdtrt_id string, psn_no string, secret_key string, org_name string, fixmedins_code string, doctor string, insuplc_admdvs string, mdtrtarea_admvs string) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2404"   // 交易编码
	inputData["mdtrt_id"] = mdtrt_id // 人员编号 （来自1101接口返回）
	inputData["psn_no"] = psn_no     // 人员编号 （来自1101接口返回）
	input["data"] = inputData
	inputMessage["input"] = input //交易输入
	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	requestLog := string(bytesData)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")
	url := gdyb_url + "2404"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	str := string(respBytes)
	fmt.Println(str)
	return str, requestLog
}

//出院撤销
func ZHGdyb2405(mdtrt_id string, psn_no string, secret_key string, org_name string, fixmedins_code string, doctor string, insuplc_admdvs string, mdtrtarea_admvs string) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2405"   // 交易编码
	inputData["mdtrt_id"] = mdtrt_id // 人员编号 （来自1101接口返回）
	inputData["psn_no"] = psn_no     // 人员编号 （来自1101接口返回）
	input["data"] = inputData
	inputMessage["input"] = input //交易输入
	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	requestLog := string(bytesData)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")
	url := gdyb_url + "2405"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	str := string(respBytes)
	fmt.Println(str)
	return str, requestLog
}

type Diseinfo2402Struct struct {
	MdtrtId      string
	PsnNo        string
	DiagType     string
	MaindiagFlag string
	DiagSrtNo    string
	DiagCode     string
	DiagName     string
	DiagDept     string
	DiseDorNo    string
	DiseDorName  string
	DiagTime     string
}
type Struct2402 struct {
	MdtrtId      string
	PsnNo        string
	Insutype     string
	Endtime      string
	DscgDeptCodg string
	DscgDeptName string
	DscgWay      string
	Diseinfo     []Diseinfo2402Struct
	DiseName     string
	DiseCode     string
}

// 出院
func ZHGdyb2402(struct2402 Struct2402, org_name string, doctor string, insuplc_admdvs string, mdtrtarea_admvs string, secret_key string, fixmedins_code string) (string, string) {

	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)
	//tempTime := time.Unix(timestamp, 0)
	//timeFormatOne := tempTime.Format("2006-01-02 15:04:05")

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2402"               // 交易编码
	inputData["mdtrt_id"] = struct2402.MdtrtId   // 人员编号 （来自1101接口返回）
	inputData["psn_no"] = struct2402.PsnNo       // 人员编号 （来自1101接口返回）
	inputData["insutype"] = struct2402.Insutype  // 险种类型（来自1101接口返回）
	inputData["endtime"] = struct2402.Endtime    // 结束时间
	inputData["dise_codg"] = struct2402.DiseCode // 就诊凭证类型

	inputData["dise_name"] = struct2402.DiseName // 就诊凭证类型
	inputData["oprn_oprt_code"] = ""             // 就诊凭证类型
	inputData["oprn_oprt_name"] = ""             // 就诊凭证类型
	inputData["fpsc_no"] = ""                    // 就诊凭证类型

	inputData["matn_type"] = ""    // 就诊凭证类型
	inputData["birctrl_type"] = "" // 就诊凭证类型
	inputData["latechb_flag"] = "" // 就诊凭证类型
	inputData["geso_val"] = ""
	inputData["fetts"] = ""
	inputData["fetus_cnt"] = ""
	inputData["pret_flag"] = ""
	inputData["birctrl_matn_date"] = ""
	inputData["cop_flag"] = ""

	inputData["dscg_dept_codg"] = struct2402.DscgDeptCodg
	inputData["dscg_dept_name"] = struct2402.DscgDeptName
	inputData["dscg_bed"] = "待定"
	inputData["dscg_way"] = struct2402.DscgWay
	inputData["die_date"] = ""

	inputDataArr := make([]map[string]interface{}, 0)
	for _, item := range struct2402.Diseinfo {
		inputDataTwo := make(map[string]interface{})
		inputDataTwo["psn_no"] = item.PsnNo
		inputDataTwo["mdtrt_id"] = item.MdtrtId
		inputDataTwo["diag_type"] = item.DiagType
		inputDataTwo["maindiag_flag"] = item.MaindiagFlag
		inputDataTwo["diag_srt_no"] = item.DiagSrtNo
		inputDataTwo["diag_code"] = item.DiagCode
		inputDataTwo["diag_name"] = item.DiagName
		inputDataTwo["diag_dept"] = item.DiagDept
		inputDataTwo["dise_dor_no"] = item.DiseDorNo
		inputDataTwo["dise_dor_name"] = item.DiseDorName
		inputDataTwo["diag_time"] = item.DiagTime
		inputDataArr = append(inputDataArr, inputDataTwo)
	}

	input["dscginfo"] = inputData
	input["diseinfo"] = inputDataArr

	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	request_log := string(bytesData)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)

	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")
	url := gdyb_url + "2402"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}
	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/2202"
	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2202"

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2202"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	//request.Header.Set("x-tif-paasid", "test_hosp")
	request.Header.Set("x-tif-paasid", gdyb_paasid)

	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	str := string(respBytes)
	fmt.Println(str)
	return str, request_log
}

type ZHCustom struct {
	DetItemFeeSumamt string
	Cut              string
	FeedetlSn        string
	Price            string
	MedListCodg      string
	LmtUsedFlag      int64
	HospApprFlag     int64
}
type ZHRequestResult struct {
	Output      ZHOutput `json:"output" form:"output"`
	Infcode     int64    `gorm:"column:infcode" json:"infcode" form:"infcode"`
	WarnMsg     string   `gorm:"column:warn_msg" json:"warn_msg" form:"warn_msg"`
	Cainfo      string   `gorm:"column:cainfo" json:"cainfo" form:"cainfo"`
	ErrMsg      string   `gorm:"column:err_msg" json:"err_msg" form:"err_msg"`
	RespondTime string   `gorm:"column:respond_time" json:"respond_time" form:"respond_time"`
	InfRefmsgid string   `gorm:"column:inf_refmsgid" json:"inf_refmsgid" form:"inf_refmsgid"`
}
type ZHOutput struct {
	Result Result `json:"result" form:"result"`
}
type ZHResult struct {
	BasMednFlag      string  `json:"bas_medn_flag" form:"bas_medn_flag"`
	MedChrgitmType   string  `json:"med_chrgitm_type" form:"med_chrgitm_type"`
	DetItemFeeSumamt int64   `json:"det_item_fee_sumamt" form:"det_item_fee_sumamt"`
	HiNegoDrugFlag   string  `json:"hi_nego_drug_flag" form:"hi_nego_drug_flag"`
	FulamtOwnpayAmt  float64 `json:"fulamt_ownpay_amt" form:"fulamt_ownpay_amt"`

	FeedtlSn       int64   `json:"feedtl_sn" form:"feedtl_sn"`
	UploadDate     int64   `json:"upload_date" form:"upload_date"`
	AdviceId       int64   `json:"advice_id" form:"advice_id"`
	Cnt            int64   `json:"cnt" form:"cnt"`
	Pric           float64 `json:"pric" form:"pric"`
	PatientId      int64   `json:"patient_id" form:"patient_id"`
	PricUplmtAmt   float64 `json:"pric_uplmt_amt" form:"pric_uplmt_amt"`
	SelfpayProp    float64 `json:"selfpay_prop" form:"selfpay_prop"`
	OverlmtAmt     float64 `json:"overlmt_amt" form:"overlmt_amt"`
	PreselfpayAmt  float64 `json:"preselfpay_amt" form:"preselfpay_amt"`
	Status         int64   `json:"status" form:"status"`
	Memo           string  `json:"memo" form:"memo"`
	FeedetlSn      string  `json:"feedetl_sn" form:"feedetl_sn"`
	Mtime          int64   `json:"mtime" form:"mtime"`
	InscpScpAmt    float64 `json:"inscp_scp_amt" form:"inscp_scp_amt"`
	DrtReimFlag    string  `json:"drt_reim_flag" form:"drt_reim_flag"`
	Ctime          int64   `json:"ctime" form:"ctime"`
	ListSpItemFlag string  `json:"list_sp_item_flag" form:"list_sp_item_flag"`
	ChldMedcFlag   string  `json:"chld_medc_flag" form:"chld_medc_flag"`
	LmtUsedFlag    string  `json:"lmt_used_flag" form:"lmt_used_flag"`
	ChrgitmLv      string  `json:"chrgitm_lv" form:"chrgitm_lv"`
	UserOrgId      int64   `json:"user_org_id" form:"user_org_id"`
	HisPatientId   int64   `json:"his_patient_id" form:"his_patient_id"`
	OrderId        int64   `json:"order_id" form:"order_id"`
}

//  住院费用明细信息上传
func ZHGdyb2301(psnNo string, mdtrtId string, hisPrescription []*models.NewCustom, chrg_bchno string, org_name string, doctor string, dept string, fixmedins_code string, dept_code string, doctor_id string, insuplc_admdvs string, mdtrtarea_admvs string, secret_key string, med_type string) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)
	//tempTime := time.Unix(timestamp, 0)
	//timeFormat := tempTime.Format("20060102150405")
	//timeFormatOne := tempTime.Format("2006-01-02 15:04:05")
	//chrgBchno := rand.Intn(100000) + 10000

	var customs []*models.NewCustom

	customs = hisPrescription
	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	feedetail := make([]map[string]interface{}, 0)
	inputMessage["infno"] = "2301" // 交易编码

	//chrg_bchno := timeFormat + strconv.FormatInt(int64(chrgBchno), 10)
	for _, item := range customs {
		feedetailInfo := make(map[string]interface{})
		feedetailInfo["feedetl_sn"] = item.FeedetlSn
		feedetailInfo["mdtrt_id"] = mdtrtId // 就诊 ID（来自2201接口返回）
		feedetailInfo["psn_no"] = psnNo     // 人员编号 （来自1101接口返回）
		feedetailInfo["med_type"] = med_type
		feedetailInfo["fee_ocur_time"] = item.FeeOcurTime            // 费用发生时间
		feedetailInfo["med_list_codg"] = item.MedListCodg            // 医疗目录编码
		feedetailInfo["medins_list_codg"] = fixmedins_code           // 医药机构目录编码
		feedetailInfo["det_item_fee_sumamt"] = item.DetItemFeeSumamt // 明细项目费用总额
		feedetailInfo["cnt"] = item.Cut                              // 数量
		feedetailInfo["pric"] = item.Price                           // 单价
		feedetailInfo["bilg_dept_codg"] = dept_code                  // 开单科室编码
		feedetailInfo["bilg_dept_name"] = dept                       // 开单科室名称
		feedetailInfo["bilg_dr_codg"] = doctor_id                    // 开单医生编码
		feedetailInfo["bilg_dr_name"] = doctor
		feedetailInfo["acord_dept_codg"] = ""    // 受单科室编码
		feedetailInfo["acord_dept_name"] = ""    // 受单科室名称
		feedetailInfo["orders_dr_code"] = ""     // 受单医生编码
		feedetailInfo["orders_dr_name"] = ""     // 受单医生姓名
		feedetailInfo["chrg_bchno"] = chrg_bchno // 收费批次号
		feedetailInfo["dise_codg"] = ""          // 病种编码
		feedetailInfo["rxno"] = ""               // 处方号
		feedetailInfo["rx_circ_flag"] = "0"      // 外购处方标志
		feedetailInfo["sin_dos_dscr"] = ""       // 单次剂量描述
		feedetailInfo["used_frqu_dscr"] = ""     // 使用频次描述
		feedetailInfo["prd_days"] = "0"          // 周期天数
		feedetailInfo["medc_way_dscr"] = ""      // 用药途径描述
		// 开单医师姓名

		if item.HospApprFlag != -1 {
			if item.HospApprFlag == 1 {
				feedetailInfo["hosp_appr_flag"] = "0" // 医院审批标志
			} else if item.HospApprFlag == 2 {
				feedetailInfo["hosp_appr_flag"] = "1" // 医院审批标志
			} else if item.HospApprFlag == 3 {
				feedetailInfo["hosp_appr_flag"] = "2" // 医院审批标志
			} else {
				feedetailInfo["hosp_appr_flag"] = "1" // 医院审批标志
			}
		} else {
			feedetailInfo["hosp_appr_flag"] = "1" // 医院审批标志
		}

		feedetailInfo["tcmdrug_used_way"] = "" // 中药使用方式
		feedetailInfo["etip_flag"] = ""        // 外检标志
		feedetailInfo["etip_hosp_code"] = ""   // 外检医院编码
		feedetailInfo["dscg_tkdrug_flag"] = "" // 出院带药标志
		feedetailInfo["matn_fee_flag"] = ""    // 生育费用标志
		feedetail = append(feedetail, feedetailInfo)
	}
	input["feedetail"] = feedetail
	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println("----------")
	fmt.Println(string(bytesData))
	fmt.Println("----------")
	requestLog := string(bytesData)

	if err != nil {
		fmt.Println(err.Error())
		return "", ""
	}
	reader := bytes.NewReader(bytesData)

	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")
	url := gdyb_url + "2301"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return "", ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return "", ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return "", ""
	}
	return string(respBytes), requestLog

}

//  住院费用明细信息撤销
func Gdyb2302(psnNo string, mdtrtId string, org_name string, doctor string, insuplc_admdvs string, mdtrtarea_admvs string, secret_key string, fixmedins_code string, number string, refund_type int64) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2302" // 交易编码
	if refund_type == 1 {
		inputData["feedetl_sn"] = number //

	} else {
		inputData["feedetl_sn"] = "0000" //
	}

	inputData["mdtrt_id"] = mdtrtId // 就诊 ID
	inputData["psn_no"] = psnNo     // 人员编号

	input["data"] = inputData
	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	requestLog := string(bytesData)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/1101"
	url := gdyb_url + "2302"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}
	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/2205"
	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2205"

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2205"
	request, err := http.NewRequest("POST", url, reader)
	fmt.Println(err)

	fmt.Println(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	str := string(respBytes)
	fmt.Println(str)
	return str, requestLog
}

func ZHGdyb2303(psnNo string, mdtrtId string, chrgBchno string, certNo string, insutype string, total string, org_name string, doctor string, fixmedins_code string, insuplc_admdvs string, mdtrtarea_admvs string, secret_key string, mid_setl_flag string, id_card_type int64, fulamt_ownpay_amt float64, overlmt_selfpay float64, preselfpay_amt float64, inscp_scp_amt float64, certificates int64) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2303" // 交易编码
	inputData["psn_no"] = psnNo    // 人员编号 （来自1101接口返回）
	if certificates == 3 {
		inputData["mdtrt_cert_type"] = "99" // 就诊凭证类型
		inputData["mdtrt_cert_no"] = certNo // 就诊凭证编号
	} else {
		if id_card_type == 1 {
			inputData["mdtrt_cert_type"] = "03" // 就诊凭证类型
			inputData["mdtrt_cert_no"] = certNo // 就诊凭证编号
		} else {
			inputData["mdtrt_cert_type"] = "02" // 就诊凭证类型
			inputData["mdtrt_cert_no"] = certNo // 就诊凭证编号
		}
	}
	inputData["mdtrt_cert_sn"] = ""
	inputData["mid_setl_flag"] = mid_setl_flag // 中途退费标志
	inputData["medfee_sumamt"] = total         // 医疗费总额
	inputData["psn_setlway"] = "02"            // 个人结算方式 01 按项目结 02 按定额结算
	inputData["mdtrt_id"] = mdtrtId            // 就诊 ID（来自2201接口返回）
	inputData["acct_used_flag"] = "1"          // 个人账户使用标志 0否 1是
	inputData["insutype"] = insutype           // 险种类型
	inputData["invono"] = ""                   // 发票号
	inputData["dise_codg"] = "M07803"          // 发票号

	input["data"] = inputData
	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/1101"
	url := gdyb_url + "2303"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/2207"
	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2207"

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2207"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	str := string(respBytes)
	fmt.Println(str)
	mjson, _ := json.Marshal(inputMessage)
	str2 := string(mjson)

	return str, str2
}

//  住院结算
func ZHGdyb2304(psnNo string, mdtrtId string, chrgBchno string, certNo string, insutype string, total string, org_name string, doctor string, fixmedins_code string, insuplc_admdvs string, mdtrtarea_admvs string, secret_key string, mid_setl_flag string, id_card_type int64, fulamt_ownpay_amt float64, overlmt_selfpay float64, preselfpay_amt float64, inscp_scp_amt float64, certificates int64) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2304" // 交易编码
	inputData["psn_no"] = psnNo    // 人员编号 （来自1101接口返回）
	if certificates == 3 {
		inputData["mdtrt_cert_type"] = "99" // 就诊凭证类型
		inputData["mdtrt_cert_no"] = certNo // 就诊凭证编号
	} else {
		if id_card_type == 1 {
			inputData["mdtrt_cert_type"] = "03" // 就诊凭证类型
			inputData["mdtrt_cert_no"] = certNo // 就诊凭证编号
		} else {
			inputData["mdtrt_cert_type"] = "02" // 就诊凭证类型
			inputData["mdtrt_cert_no"] = certNo // 就诊凭证编号
		}
	}
	inputData["mdtrt_cert_sn"] = ""
	inputData["mid_setl_flag"] = mid_setl_flag // 中途退费标志
	inputData["medfee_sumamt"] = total         // 医疗费总额
	inputData["psn_setlway"] = "01"            // 个人结算方式 01 按项目结 02 按定额结算
	inputData["mdtrt_id"] = mdtrtId            // 就诊 ID（来自2201接口返回）
	inputData["acct_used_flag"] = "1"          // 个人账户使用标志 0否 1是
	inputData["insutype"] = insutype           // 险种类型
	inputData["invono"] = ""                   // 发票号

	input["data"] = inputData
	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/1101"
	url := gdyb_url + "2304"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_api/prd/hsa/hgs/2207"
	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2207"

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/2207"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	str := string(respBytes)
	fmt.Println(str)
	mjson, _ := json.Marshal(inputMessage)
	str2 := string(mjson)

	return str, str2
}

//  住院结算撤销
func Gdyb2305(psnNo string, mdtrtId string, setlId string, org_name string, doctor string, secret_key string, fixmedins_code string, insuplc_admdvs string, mdtrtarea_admvs string) (string, string) {
	// 生成签名
	nonce := GetRandomString(32)
	timestamp := time.Now().Unix()
	signature := setSignature(timestamp, nonce, secret_key)

	// 生成输入报文
	inputMessage := SetInputMessage(nonce, timestamp, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputMessage["infno"] = "2305" // 交易编码

	inputData["psn_no"] = psnNo     // 人员编号 （来自1101接口返回）
	inputData["mdtrt_id"] = mdtrtId // 就诊 ID（来自2201接口返回）
	inputData["setl_id"] = setlId   // 结算 ID

	input["data"] = inputData
	inputMessage["input"] = input //交易输入

	bytesData, err := json.Marshal(inputMessage)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	gdyb_url := beego.AppConfig.String("gdyb_url")
	gdyb_paasid := beego.AppConfig.String("gdyb_paasid")
	url := gdyb_url + "2305"
	if mdtrtarea_admvs == "150499" {
		url = gdyb_url
	}
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("x-tif-paasid", gdyb_paasid)
	request.Header.Set("x-tif-signature", signature)
	request.Header.Set("x-tif-timestamp", strconv.FormatInt(timestamp, 10))
	request.Header.Set("x-tif-nonce", nonce)

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	str := string(respBytes)
	fmt.Println(str)
	mjson, _ := json.Marshal(inputMessage)
	str2 := string(mjson)
	return str, str2
}

func CreateHospitalRecord(record *models.HisHospitalCheckRecord) (err error) {
	err = writeDb.Save(&record).Error
	return
}

func GetInHospitalRecord(id int64) (record models.HisHospitalCheckRecord, err error) {
	err = readDb.Model(&models.HisHospitalCheckRecord{}).Where("id = ? AND status = 1", id).First(&record).Error
	return
}

func GetInHospitalRecordByNumber(number string) (record models.HisHospitalCheckRecord, err error) {
	err = readDb.Model(&models.HisHospitalCheckRecord{}).Where("number = ? AND status = 1", number).First(&record).Error
	return
}

func GetLastHospitalRecord(id int64, user_org_id int64) (record models.HisHospitalCheckRecord, err error) {
	err = readDb.Model(&models.HisHospitalCheckRecord{}).Where("id = ? AND status = 1 AND user_org_id = ?", id, user_org_id).Last(&record).Error
	return
}

func GetZHHisPrescription(org_id int64, patient_id int64, record_date int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1").Preload("GoodInfo", "status = 1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status <> 2 AND order_status <> 4 AND p_type = 1", org_id, record_date, patient_id).
		Find(&prescription).Error
	return
}

func GetZHMonthHisPrescription(org_id int64, patient_id int64, start_time int64, end_time int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1").Preload("GoodInfo", "status = 1")
		}).
		Where("user_org_id = ? AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status <> 2 AND order_status <> 4 AND status = 1 AND p_type = 1 ", org_id, start_time, end_time, patient_id).
		Find(&prescription).Error
	return
}

func GetZHHisUploadPrescription(org_id int64, patient_id int64, record_date int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status = 4 AND p_type = 1", org_id, record_date, patient_id).
		Find(&prescription).Error
	return
}

func GetZHMonthHisUploadPrescription(org_id int64, patient_id int64, start_time int64, end_time int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1")
		}).
		Where("user_org_id = ? AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status == 4 AND status = 1 AND p_type = 1 ", org_id, start_time, end_time, patient_id).
		Find(&prescription).Error
	return
}

func GetZHHisUploadOrderInfo(org_id int64, patient_id int64, record_date int64, record_end_date int64, number string) (infos []*models.HisOrderInfo, err error) {
	err = readDb.Model(&models.HisOrderInfo{}).
		Where("user_org_id = ? AND status = 1 AND upload_date <= ? AND upload_date >= ? AND patient_id = ? AND order_number = ? ", org_id, record_end_date, record_date, patient_id, number).
		Find(&infos).Error
	return
}

func UpDateOrderInfoStatus(patient_id int64, record_date int64, org_id int64, record_two_date int64) (err error) {
	err = writeDb.Model(&models.HisOrderInfo{}).Where("user_org_id = ? AND status = 1 AND upload_date <= ? AND upload_date >= ? AND patient_id = ?", org_id, record_two_date, record_date, patient_id).Updates(map[string]interface{}{"status": 0}).Error
	return
}

func UpDatePrescriptionOrderStatusTwo(patient_id int64, record_date int64, org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescription{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND p_type = 1", org_id, record_date, patient_id).Updates(map[string]interface{}{"order_status": 1}).Error
	return
}

//func GetAllOrderInfoByNumber(number string) (infos []*models.HisOrderInfo, err error){
//
//	err = readDb.Model(&models.HisOrderInfo{}).Where("user_org_id = ? AND ")
//}

func GetZHSettleMonthHisPrescription(org_id int64, patient_id int64, start_time int64, end_time int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1").Preload("GoodInfo", "status = 1")
		}).
		Where("user_org_id = ? AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status <> 2 AND order_status <> 4 AND status = 1 AND p_type = 1 ", org_id, start_time, end_time, patient_id).
		Find(&prescription).Error
	return
}
