package zh

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gdyb/controllers"
	"gdyb/enums"
	"gdyb/models"
	"gdyb/service"
	"gdyb/utils"
	"github.com/astaxie/beego"
	"github.com/axgle/mahonia"
	"github.com/jinzhu/gorm"
	"io/ioutil"
	"math"
	"math/rand"
	"net/http"
	"os"
	"regexp"
	"strconv"
	"strings"
	"syscall"
	"time"
	"unsafe"
)

type ZHHisApiController struct {
	controllers.BaseAuthAPIController
}
type ResultSix struct {
	Cainfo      interface{} `json:"cainfo"`
	ErrMsg      string      `json:"err_msg"`
	InfRefmsgid string      `json:"inf_refmsgid"`
	Infcode     int64       `json:"infcode"`
	Output      struct {
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

type ResultTwo struct {
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Baseinfo struct {
			Age         float64 `json:"age"`
			Brdy        string  `json:"brdy"`
			Certno      string  `json:"certno"`
			Gend        string  `json:"gend"`
			Naty        string  `json:"naty"`
			PsnCertType string  `json:"psn_cert_type"`
			PsnName     string  `json:"psn_name"`
			PsnNo       string  `json:"psn_no"`
		} `json:"baseinfo"`
		Idetinfo []interface{} `json:"idetinfo"`
		Iinfo    []struct {
			Balc                   float64 `json:"balc"`
			CvlservFlag            string  `json:"cvlserv_flag"`
			EmpName                string  `json:"emp_name"`
			InsuplcAdmdvs          string  `json:"insuplc_admdvs"`
			Insutype               string  `json:"insutype"`
			PausInsuDansuplcAdmdvs string  `json:"paus_insu_dansuplc_admdvs"`
			PausInsuDate           string  `json:"paus_insu_date"`
			PsnInsuDate            string  `json:"psn_insu_date"`
			PsnInsuStas            string  `json:"psn_insu_stas"`
			PsnType                string  `json:"psn_type"`
		} `json:"insuinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnInfo    interface{} `json:"warn_info"`
}
type ResultTwo10265 struct {
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     string `json:"infcode"`
	Output      struct {
		Baseinfo struct {
			Age         float64 `json:"age"`
			Brdy        string  `json:"brdy"`
			Certno      string  `json:"certno"`
			Gend        string  `json:"gend"`
			Naty        string  `json:"naty"`
			PsnCertType string  `json:"psn_cert_type"`
			PsnName     string  `json:"psn_name"`
			PsnNo       string  `json:"psn_no"`
		} `json:"baseinfo"`
		Idetinfo []interface{} `json:"idetinfo"`
		Iinfo    []struct {
			Balc                   float64 `json:"balc"`
			CvlservFlag            string  `json:"cvlserv_flag"`
			EmpName                string  `json:"emp_name"`
			InsuplcAdmdvs          string  `json:"insuplc_admdvs"`
			Insutype               string  `json:"insutype"`
			PausInsuDansuplcAdmdvs string  `json:"paus_insu_dansuplc_admdvs"`
			PausInsuDate           string  `json:"paus_insu_date"`
			PsnInsuDate            string  `json:"psn_insu_date"`
			PsnInsuStas            string  `json:"psn_insu_stas"`
			PsnType                string  `json:"psn_type"`
		} `json:"insuinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnInfo    interface{} `json:"warn_info"`
}

type ResultThree struct {
	Cainfo      interface{} `json:"cainfo"`
	ErrMsg      string      `json:"err_msg"`
	InfRefmsgid string      `json:"inf_refmsgid"`
	Infcode     int64       `json:"infcode"`
	Output      struct {
		Result struct {
			MdtrtID string `json:"mdtrt_id"`
		} `json:"result"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}
type ResultThree10265 struct {
	Cainfo      interface{} `json:"cainfo"`
	ErrMsg      string      `json:"err_msg"`
	InfRefmsgid string      `json:"inf_refmsgid"`
	Infcode     string      `json:"infcode"`
	Output      struct {
		Result struct {
			MdtrtID string `json:"mdtrt_id"`
		} `json:"result"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

type ResultFour struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Result []struct {
			BasMednFlag      string  `json:"bas_medn_flag"`
			ChldMedcFlag     string  `json:"chld_medc_flag"`
			ChrgitmLv        string  `json:"chrgitm_lv"`
			Cnt              float64 `json:"cnt"`
			DetItemFeeSumamt float64 `json:"det_item_fee_sumamt"`
			DrtReimFlag      string  `json:"drt_reim_flag"`
			FeedetlSn        string  `json:"feedetl_sn"`
			FulamtOwnpayAmt  float64 `json:"fulamt_ownpay_amt"`
			HiNegoDrugFlag   string  `json:"hi_nego_drug_flag"`
			InscpScpAmt      float64 `json:"inscp_scp_amt"`
			ListSpItemFlag   string  `json:"list_sp_item_flag"`
			LmtUsedFlag      string  `json:"lmt_used_flag"`
			MedChrgitmType   string  `json:"med_chrgitm_type"`
			Memo             string  `json:"memo"`
			OverlmtAmt       float64 `json:"overlmt_amt"`
			PreselfpayAmt    float64 `json:"preselfpay_amt"`
			Pric             float64 `json:"pric"`
			PricUplmtAmt     float64 `json:"pric_uplmt_amt"`
			SelfpayProp      float64 `json:"selfpay_prop"`
		} `json:"result"`
	} `json:"output"`
	RefmsgTime  string `json:"refmsg_time"`
	RespondTime string `json:"respond_time"`
	Signtype    string `json:"signtype"`
	WarnMsg     string `json:"warn_msg"`
}
type ResultFour10265 struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     string `json:"infcode"`
	Output      struct {
		Result []struct {
			BasMednFlag      string  `json:"bas_medn_flag"`
			ChldMedcFlag     string  `json:"chld_medc_flag"`
			ChrgitmLv        string  `json:"chrgitm_lv"`
			Cnt              float64 `json:"cnt"`
			DetItemFeeSumamt float64 `json:"det_item_fee_sumamt"`
			DrtReimFlag      string  `json:"drt_reim_flag"`
			FeedetlSn        string  `json:"feedetl_sn"`
			FulamtOwnpayAmt  float64 `json:"fulamt_ownpay_amt"`
			HiNegoDrugFlag   string  `json:"hi_nego_drug_flag"`
			InscpScpAmt      float64 `json:"inscp_scp_amt"`
			ListSpItemFlag   string  `json:"list_sp_item_flag"`
			LmtUsedFlag      string  `json:"lmt_used_flag"`
			MedChrgitmType   string  `json:"med_chrgitm_type"`
			Memo             string  `json:"memo"`
			OverlmtAmt       float64 `json:"overlmt_amt"`
			PreselfpayAmt    float64 `json:"preselfpay_amt"`
			Pric             float64 `json:"pric"`
			PricUplmtAmt     float64 `json:"pric_uplmt_amt"`
			SelfpayProp      float64 `json:"selfpay_prop"`
		} `json:"result"`
	} `json:"output"`
	RefmsgTime  string `json:"refmsg_time"`
	RespondTime string `json:"respond_time"`
	Signtype    string `json:"signtype"`
	WarnMsg     string `json:"warn_msg"`
}

type ResultFive struct {
	Balc                   float64 `json:"balc"`
	CvlservFlag            string  `json:"cvlserv_flag"`
	EmpName                string  `json:"emp_name"`
	InsuplcAdmdvs          string  `json:"insuplc_admdvs"`
	Insutype               string  `json:"insutype"`
	PausInsuDansuplcAdmdvs string  `json:"paus_insu_dansuplc_admdvs"`
	PausInsuDate           string  `json:"paus_insu_date"`
	PsnInsuDate            string  `json:"psn_insu_date"`
	PsnInsuStas            string  `json:"psn_insu_stas"`
	PsnType                string  `json:"psn_type"`
}
type ResultSeven struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Setldetail []interface{} `json:"setldetail"`
		Setlinfo   struct {
			AcctMulaidPay   float64 `json:"acct_mulaid_pay"`
			AcctPay         float64 `json:"acct_pay"`
			ActPayDedc      float64 `json:"act_pay_dedc"`
			Age             float64 `json:"age"`
			Balc            float64 `json:"balc"`
			Brdy            string  `json:"brdy"`
			Certno          string  `json:"certno"`
			ClrOptins       string  `json:"clr_optins"`
			ClrType         string  `json:"clr_type"`
			ClrWay          string  `json:"clr_way"`
			CvlservFlag     string  `json:"cvlserv_flag"`
			CvlservPay      float64 `json:"cvlserv_pay"`
			FulamtOwnpayAmt float64 `json:"fulamt_ownpay_amt"`
			FundPaySumamt   float64 `json:"fund_pay_sumamt"`
			Gend            string  `json:"gend"`
			HifesPay        float64 `json:"hifes_pay"`
			HifmiPay        float64 `json:"hifmi_pay"`
			HifpPay         float64 `json:"hifp_pay"`
			HospPartAmt     float64 `json:"hosp_part_amt"`
			InscpScpAmt     float64 `json:"inscp_scp_amt"`
			Insutype        string  `json:"insutype"`
			MafPay          float64 `json:"maf_pay"`
			MdtrtCertType   string  `json:"mdtrt_cert_type"`
			HifobPay        float64 `json:"hifob_pay"`

			MdtrtID         string  `json:"mdtrt_id"`
			MedType         string  `json:"med_type"`
			MedfeeSumamt    float64 `json:"medfee_sumamt"`
			MedinsSetlID    string  `json:"medins_setl_id"`
			Naty            string  `json:"naty"`
			OthPay          float64 `json:"oth_pay"`
			OverlmtSelfpay  float64 `json:"overlmt_selfpay"`
			PoolPropSelfpay float64 `json:"pool_prop_selfpay"`
			PreselfpayAmt   float64 `json:"preselfpay_amt"`
			PsnCashPay      float64 `json:"psn_cash_pay"`
			PsnCertType     string  `json:"psn_cert_type"`
			PsnName         string  `json:"psn_name"`
			PsnNo           string  `json:"psn_no"`
			PsnPartAmt      float64 `json:"psn_part_amt"`
			PsnType         string  `json:"psn_type"`
			SetlID          string  `json:"setl_id"`
			SetlTime        string  `json:"setl_time"`
		} `json:"setlinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}
type ResultSeven10265 struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     string `json:"infcode"`
	Output      struct {
		Setldetail []interface{} `json:"setldetail"`
		Setlinfo   struct {
			AcctMulaidPay   float64 `json:"acct_mulaid_pay"`
			AcctPay         float64 `json:"acct_pay"`
			ActPayDedc      float64 `json:"act_pay_dedc"`
			Age             float64 `json:"age"`
			Balc            float64 `json:"balc"`
			Brdy            string  `json:"brdy"`
			Certno          string  `json:"certno"`
			ClrOptins       string  `json:"clr_optins"`
			ClrType         string  `json:"clr_type"`
			ClrWay          string  `json:"clr_way"`
			CvlservFlag     string  `json:"cvlserv_flag"`
			CvlservPay      float64 `json:"cvlserv_pay"`
			FulamtOwnpayAmt float64 `json:"fulamt_ownpay_amt"`
			FundPaySumamt   float64 `json:"fund_pay_sumamt"`
			Gend            string  `json:"gend"`
			HifesPay        float64 `json:"hifes_pay"`
			HifmiPay        float64 `json:"hifmi_pay"`
			HifpPay         float64 `json:"hifp_pay"`
			HospPartAmt     float64 `json:"hosp_part_amt"`
			InscpScpAmt     float64 `json:"inscp_scp_amt"`
			Insutype        string  `json:"insutype"`
			MafPay          float64 `json:"maf_pay"`
			MdtrtCertType   string  `json:"mdtrt_cert_type"`
			HifobPay        float64 `json:"hifob_pay"`

			MdtrtID         string  `json:"mdtrt_id"`
			MedType         string  `json:"med_type"`
			MedfeeSumamt    float64 `json:"medfee_sumamt"`
			MedinsSetlID    string  `json:"medins_setl_id"`
			Naty            string  `json:"naty"`
			OthPay          float64 `json:"oth_pay"`
			OverlmtSelfpay  float64 `json:"overlmt_selfpay"`
			PoolPropSelfpay float64 `json:"pool_prop_selfpay"`
			PreselfpayAmt   float64 `json:"preselfpay_amt"`
			PsnCashPay      float64 `json:"psn_cash_pay"`
			PsnCertType     string  `json:"psn_cert_type"`
			PsnName         string  `json:"psn_name"`
			PsnNo           string  `json:"psn_no"`
			PsnPartAmt      float64 `json:"psn_part_amt"`
			PsnType         string  `json:"psn_type"`
			SetlID          string  `json:"setl_id"`
			SetlTime        string  `json:"setl_time"`
		} `json:"setlinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

type ResultSixteen struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Setldetail []interface{} `json:"setldetail"`
		Setlinfo   struct {
			MdtrtID         string  `json:"mdtrt_id"`
			SetlID          string  `json:"setl_id"`
			ClrOptins       string  `json:"clr_optins"`
			SetlTime        string  `json:"setl_time"`
			MedfeeSumamt    float64 `json:"medfee_sumamt"`
			FulamtOwnpayAmt float64 `json:"fulamt_ownpay_amt"`
			OverlmtSelfpay  float64 `json:"overlmt_selfpay"`
			PreselfpayAmt   float64 `json:"preselfpay_amt"`
			InscpScpAmt     float64 `json:"inscp_scp_amt"`
			ActPayDedc      float64 `json:"act_pay_dedc"`
			HifpPay         float64 `json:"hifp_pay"`
			PoolPropSe      float64 `json:"pool_prop_selfpay"`
			Lfpay           float64 `json:"selfpay"`
			CvlservPay      float64 `json:"cvlserv_pay"`
			HifesPay        float64 `json:"hifes_pay"`
			HifmiPay        float64 `json:"hifmi_pay"`
			HifobPay        float64 `json:"hifob_pay"`
			MafPay          float64 `json:"maf_pay"`
			OthPay          float64 `json:"oth_pay"`
			FundPaySumamt   float64 `json:"fund_pay_sumamt"`
			PsnPartAmt      float64 `json:"psn_part_amt"`
			AcctPay         float64 `json:"acct_pay"`
			Balc            float64 `json:"balc"`
			AcctMulaidPay   float64 `json:"acct_mulaid_pay"`
			HospPartAmt     float64 `json:"hosp_part_amt"`
			MedinsSetlID    string  `json:"medins_setl_id"`
			PdnCashPay      string  `json:"pdn_cash_pay"`
		} `json:"setlinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}
type ResultSixteen10265 struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     string `json:"infcode"`
	Output      struct {
		Setldetail []interface{} `json:"setldetail"`
		Setlinfo   struct {
			MdtrtID         string  `json:"mdtrt_id"`
			SetlID          string  `json:"setl_id"`
			ClrOptins       string  `json:"clr_optins"`
			SetlTime        string  `json:"setl_time"`
			MedfeeSumamt    float64 `json:"medfee_sumamt"`
			FulamtOwnpayAmt float64 `json:"fulamt_ownpay_amt"`
			OverlmtSelfpay  float64 `json:"overlmt_selfpay"`
			PreselfpayAmt   float64 `json:"preselfpay_amt"`
			InscpScpAmt     float64 `json:"inscp_scp_amt"`
			ActPayDedc      float64 `json:"act_pay_dedc"`
			HifpPay         float64 `json:"hifp_pay"`
			PoolPropSe      float64 `json:"pool_prop_selfpay"`
			Lfpay           float64 `json:"selfpay"`
			CvlservPay      float64 `json:"cvlserv_pay"`
			HifesPay        float64 `json:"hifes_pay"`
			HifmiPay        float64 `json:"hifmi_pay"`
			HifobPay        float64 `json:"hifob_pay"`
			MafPay          float64 `json:"maf_pay"`
			OthPay          float64 `json:"oth_pay"`
			FundPaySumamt   float64 `json:"fund_pay_sumamt"`
			PsnPartAmt      float64 `json:"psn_part_amt"`
			AcctPay         float64 `json:"acct_pay"`
			Balc            float64 `json:"balc"`
			AcctMulaidPay   float64 `json:"acct_mulaid_pay"`
			HospPartAmt     float64 `json:"hosp_part_amt"`
			MedinsSetlID    string  `json:"medins_setl_id"`
			PdnCashPay      string  `json:"pdn_cash_pay"`
		} `json:"setlinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

type Custom struct {
	DetItemFeeSumamt string
	Cut              string
	FeedetlSn        string
	Price            string
	MedListCodg      string
	Type             int64
	AdviceId         int64
	ProjectId        int64
	ItemId           int64
}

type ResultEmpty struct {
	Cainfo      interface{} `json:"cainfo"`
	ErrMsg      string      `json:"err_msg"`
	InfRefmsgid string      `json:"inf_refmsgid"`
	Infcode     int64       `json:"infcode"`
	Output      struct {
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}
type ResultEmpty10265 struct {
	Cainfo      interface{} `json:"cainfo"`
	ErrMsg      string      `json:"err_msg"`
	InfRefmsgid string      `json:"inf_refmsgid"`
	Infcode     string      `json:"infcode"`
	Output      struct {
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

type CustomResult struct {
	BasMednFlag      string  `json:"bas_medn_flag"`
	ChldMedcFlag     string  `json:"chld_medc_flag"`
	ChrgitmLv        string  `json:"chrgitm_lv"`
	Cnt              float64 `json:"cnt"`
	DetItemFeeSumamt float64 `json:"det_item_fee_sumamt"`
	DrtReimFlag      string  `json:"drt_reim_flag"`
	FeedetlSn        string  `json:"feedetl_sn"`
	FulamtOwnpayAmt  float64 `json:"fulamt_ownpay_amt"`
	HiNegoDrugFlag   string  `json:"hi_nego_drug_flag"`
	InscpScpAmt      float64 `json:"inscp_scp_amt"`
	ListSpItemFlag   string  `json:"list_sp_item_flag"`
	LmtUsedFlag      string  `json:"lmt_used_flag"`
	MedChrgitmType   string  `json:"med_chrgitm_type"`
	Memo             string  `json:"memo"`
	OverlmtAmt       float64 `json:"overlmt_amt"`
	PreselfpayAmt    float64 `json:"preselfpay_amt"`
	Pric             float64 `json:"pric"`
	PricUplmtAmt     float64 `json:"pric_uplmt_amt"`
	SelfpayProp      float64 `json:"selfpay_prop"`
}

func ZHHisManagerApiRegistRouters() {
	beego.Router("/zh/api/inhopitalcheck/get", &ZHHisApiController{}, "get:GetZHInHospitalCheck")
	beego.Router("/zh/api/outhopitalcheck/get", &ZHHisApiController{}, "get:GetZHOutHospitalCheck")
	beego.Router("/zh/api/uploadinfo/get", &ZHHisApiController{}, "get:GetUploadInfo")
	beego.Router("/zh/api/presettle/get", &ZHHisApiController{}, "get:GetPreSettleInfo")
	beego.Router("/zh/api/settle/get", &ZHHisApiController{}, "get:GetSettleInfo")
	beego.Router("/zh/api/inthopitaluncheck/get", &ZHHisApiController{}, "get:GetZHInHospitalUnCheck")
	beego.Router("/zh/api/outhopitaluncheck/get", &ZHHisApiController{}, "get:GetZHOutHospitalUnCheck")
	beego.Router("/zh/api/refund", &ZHHisApiController{}, "get:ZHRefund")
	beego.Router("/zh/api/refunddetail", &ZHHisApiController{}, "get:ZHRefundDetail")
	beego.Router("/zh/api/patient/info", &ZHHisApiController{}, "get:GetZHPatientInfo")
	beego.Router("/zh/api/readcard", &ZHHisApiController{}, "get:ReadCard")

	beego.Router("/zh/api/clearsettle", &ZHHisApiController{}, "get:ClearSettle")

}
func (c *ZHHisApiController) ClearSettle() {
	order_id, _ := c.GetInt64("order_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	adminUser := c.GetAdminUserInfo()
	var order models.HisOrder
	order, _ = service.GetHisOrderByID(order_id)
	record, _ := service.GetInHospitalRecordByNumber(order.MdtrtId)
	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	if config.IsOpen == 1 { //对接了医保,走医保流程
		var result string
		var requestLog string
		result, requestLog = service.Gdyb90306(order.PsnNo, order.MdtrtId, order.SetlId, miConfig.OrgName, roles.UserName, miConfig.SecretKey, miConfig.Code, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs)
		saveLog(result, requestLog, "90306", "撤销结算清单")

		var dat map[string]interface{}
		if err := json.Unmarshal([]byte(result), &dat); err == nil {
			fmt.Println(dat)
		} else {
			fmt.Println(err)
		}

		userJSONBytes, _ := json.Marshal(dat)

		var res ResultSix
		//var resSixteen ResultSixteen10265
		if miConfig.Code == "H15049901371" {
			//if err := json.Unmarshal(userJSONBytes, &resSixteen); err != nil {
			//	utils.ErrorLog("解析失败:%v", err)
			//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			//	return
			//}
			//res.Cainfo = resSixteen.Cainfo
			//res.WarnMsg = resSixteen.WarnMsg
			//res.Output = resSixteen.Output
			//res.ErrMsg = resSixteen.ErrMsg
			//res.RespondTime = resSixteen.RespondTime
			//Infcode, _ := strconv.ParseInt(resSixteen.Infcode, 10, 64)
			//res.Infcode = Infcode

		} else {

			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

		}
		if res.Infcode == 0 {
			record, _ := service.GetUploadRecord(order_id)
			record.Status = 0
			service.UpdateRecord(&record)
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "撤销成功",
			})
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"code": -10,
				"msg":  res.ErrMsg,
			})
		}

	}

}

func (c *ZHHisApiController) GetZHPatientInfo() {
	id_card_no := c.GetString("id_card_no")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	patient, _ := service.GetPatientByIDCard(id_card_no, c.GetAdminUserInfo().CurrentOrgId)

	if patient.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}

	role, _ := service.GetAdminUserInfoByID(c.GetAdminUserInfo().CurrentOrgId, admin_user_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(c.GetAdminUserInfo().CurrentOrgId)
	if config.IsOpen == 1 {

		var result string
		var request_log string
		var result_log string

		if miConfig.MdtrtareaAdmvs == "150499" {
			//请求内网数据
			api := "http://172.16.13.254:9532/" + "nmyb/1101?cert_no=" + patient.IdCardNo +
				"&org_name=" + miConfig.OrgName + "&doctor=" + role.UserName + "&fixmedins_code=" + miConfig.Code +
				"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&id_card_type=" + strconv.FormatInt(2, 10) + "&card_sn=" + "" + "&certificates=" + strconv.FormatInt(1, 10) + "&name=" + patient.Name

			resp, requestErr := http.Get(api)
			if requestErr != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			body, ioErr := ioutil.ReadAll(resp.Body)

			if ioErr != nil {
				utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			var respJSON map[string]interface{}

			if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
				utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
			result_byte, _ := json.Marshal(respJSON)
			result = string(result_byte)
			saveLog(result_log, request_log, "1101", "人员基本信息获取")

		} else {
			result, request_log, result_log = service.ZHGdyb1101(patient.IdCardNo, miConfig.OrgName, role.UserName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, 2, "", 1, patient.Name)
			saveLog(result_log, request_log, "1101", "人员基本信息获取")

		}

		//result := service.Gdyb1101A(id_card_no, miConfig.OrgName, role.UserName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, patient.Name)
		var dat map[string]interface{}
		if err := json.Unmarshal([]byte(result), &dat); err == nil {
			fmt.Println(dat)
		} else {
			fmt.Println(err)
		}

		userJSONBytes, _ := json.Marshal(dat)
		var res ResultTwo
		var resTwo10265 ResultTwo10265

		if miConfig.Code == "H15049901371" {
			if err := json.Unmarshal(userJSONBytes, &resTwo10265); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			Infcode, _ := strconv.ParseInt(resTwo10265.Infcode, 10, 64)
			res.Infcode = Infcode
			res.ErrMsg = resTwo10265.ErrMsg
			res.Output = resTwo10265.Output
			res.InfRefmsgid = resTwo10265.InfRefmsgid
			res.RespondTime = resTwo10265.RespondTime
			res.WarnInfo = resTwo10265.WarnInfo

		} else {
			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

		}

		var insutypes []string
		var insutype string
		var is390 int = 0
		var is310 int = 0
		for _, item := range res.Output.Iinfo {
			if (item.Insutype == "390" && item.PsnInsuStas == "1") || (item.Insutype == "310" && item.PsnInsuStas == "1") {
				insutypes = append(insutypes, item.Insutype)
			}
		}
		if len(insutypes) == 1 {
			insutype = insutypes[0]
		} else {
			for _, i := range insutypes {
				if i == "390" {
					is390 = 1
				}

				if i == "310" {
					is310 = 1
				}
			}
		}
		if is390 == 1 {
			insutype = "390"
		}
		if is310 == 1 {
			insutype = "310"
		}
		if len(insutypes) == 0 {
			insutype = "310"
		}
		if res.Infcode != 0 {
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res.ErrMsg,
			})
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": 0,
				"info":        res,
				"insutype":    insutype,
			})
		}
	}
}

func (c *ZHHisApiController) GetZHInHospitalCheck() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	name := c.GetString("name")
	phone := c.GetString("phone")
	id_card_type, _ := c.GetInt64("id_card_type")
	certificates, _ := c.GetInt64("certificates")
	id_card_no := c.GetString("id_card_no")
	doctor, _ := c.GetInt64("doctor")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	department, _ := c.GetInt64("department")
	adm_bed, _ := c.GetInt64("adm_bed")
	diagnosis_ids := c.GetString("diagnosis")
	sick_type, _ := c.GetInt64("sick_type")
	start_time := c.GetString("start_time")
	insuplc_admdvs := c.GetString("insuplc_admdvs")
	balance_accounts_type, _ := c.GetInt64("balance_accounts_type")

	social_type, _ := c.GetInt64("social_type")
	psn_type, _ := c.GetInt64("psn_type")

	//reg_type, _ := c.GetInt64("p_type")
	med_type, _ := c.GetInt64("med_type")
	diagnosis_ids_arr := strings.Split(diagnosis_ids, "-")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminInfo := c.GetAdminUserInfo()
	record, _ := service.GetLastHospitalRecord(id, adminInfo.CurrentOrgId)
	if record.ID != 0 {
		if record.InHospitalStatus == 1 && record.OutHospitalStatus != 1 {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHospitalExistDataException)
			return
		}
	}
	var patient service.Patients
	if id == 0 {
		patient, _ = service.GetPatientByIDCard(id_card_no, adminInfo.CurrentOrgId)
	} else {
		patient, _ = service.GetPatientByIDTwo(adminInfo.CurrentOrgId, id)
	}
	diagnosisConfig, _ := service.FindDiagnoseByIds(diagnosis_ids_arr)
	sickConfig, _ := service.FindSickById(sick_type)
	departmentInfo, _ := service.GetDepartMentDetail(department)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)
	role, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, admin_user_id)

	var result string
	var request_log string
	var result_log string
	var res2 ResultTwo
	var resTwo10265 ResultTwo10265
	psn_info, _ := service.GetPsnByPatientId(patient.ID)

	if miConfig.MdtrtareaAdmvs == "150499" {
		if id_card_type == 2 {
			mdtrt_cert_no := ""
			card_sn := ""

			if record.IdCardType == 1 {
				bas := strings.Split(psn_info.CardInfo, "|")
				cardNumber := bas[2]
				mdtrt_cert_no = cardNumber
				card_sn = bas[3]
			} else {
				mdtrt_cert_no = id_card_no
			}
			//请求内网数据
			api := "http://172.16.13.254:9532/" + "nmyb/1101?cert_no=" + mdtrt_cert_no +
				"&org_name=" + miConfig.OrgName + "&doctor=" + role.UserName + "&fixmedins_code=" + miConfig.Code +
				"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&id_card_type=" + strconv.FormatInt(id_card_type, 10) + "&card_sn=" + card_sn + "&certificates=" + strconv.FormatInt(certificates, 10) + "&name=" + patient.Name
			resp, requestErr := http.Get(api)
			if requestErr != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			body, ioErr := ioutil.ReadAll(resp.Body)

			if ioErr != nil {
				utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			var respJSON map[string]interface{}

			if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
				utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
			result_byte, _ := json.Marshal(respJSON)
			result = string(result_byte)

			var dat map[string]interface{}
			if err := json.Unmarshal([]byte(result), &dat); err == nil {
				fmt.Println(dat)
			} else {
				fmt.Println(err)
			}
			userJSONBytes, _ := json.Marshal(dat)
			if err := json.Unmarshal(userJSONBytes, &resTwo10265); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			Infcode, _ := strconv.ParseInt(resTwo10265.Infcode, 10, 64)
			res2.Infcode = Infcode
			res2.ErrMsg = resTwo10265.ErrMsg
			res2.Output = resTwo10265.Output
			res2.InfRefmsgid = resTwo10265.InfRefmsgid
			res2.RespondTime = resTwo10265.RespondTime
			res2.WarnInfo = resTwo10265.WarnInfo
		} else {
			res2.Infcode = 0
			res2.Output.Baseinfo.PsnNo = psn_info.PsnNo
			res2.Output.Baseinfo.Certno = patient.IdCardNo
		}
	} else {
		result, request_log, result_log = service.ZHGdyb1101(patient.IdCardNo, miConfig.OrgName, role.UserName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, id_card_type, "", certificates, name)
		saveLog(result_log, request_log, "1101", "人员基本信息获取")
	}

	doctorInfo, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, doctor)
	deviceNumber, _ := service.GetDeviceNumberByID(adm_bed, adminInfo.CurrentOrgId)

	if miConfig.MdtrtareaAdmvs != "150499" {
		var dat map[string]interface{}
		if err := json.Unmarshal([]byte(result), &dat); err == nil {
			fmt.Println(dat)
		} else {
			fmt.Println(err)
		}
		userJSONBytes, _ := json.Marshal(dat)
		if err := json.Unmarshal(userJSONBytes, &res2); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	}

	var infoStr string
	if miConfig.MdtrtareaAdmvs == "150499" {
		if id_card_type == 2 {
			Iinfos, _ := json.Marshal(res2.Output.Iinfo)
			infoStr = string(Iinfos)
		} else {
			infoStr = psn_info.Insuinfo
		}
	} else {
		Iinfos, _ := json.Marshal(res2.Output.Iinfo)
		infoStr = string(Iinfos)
	}

	var rf []*ResultFive
	json.Unmarshal([]byte(infoStr), &rf)
	var insutypes []*ResultFive
	var insutype string
	var is390 int = 0
	var is310 int = 0

	for _, item := range rf {
		if (item.Insutype == "390" && item.PsnInsuStas == "1") || (item.Insutype == "310" && item.PsnInsuStas == "1") {
			insutypes = append(insutypes, item)
		}
	}

	if len(insutypes) == 1 {
		insutype = insutypes[0].Insutype
		//insuplc_admdvs = insutypes[0].InsuplcAdmdvs
	} else {
		for _, i := range insutypes {
			if i.Insutype == "390" {
				is390 = 1
			}

			if i.Insutype == "310" {
				is310 = 1
			}
		}
	}
	if is390 == 1 {
		insutype = "390"
	}

	if is310 == 1 {
		insutype = "310"
	}

	if len(insutypes) == 0 {
		insutype = "310"
	}

	if len(insutypes) == 2 {
		insutype = strconv.FormatInt(social_type, 10)
	}
	//for _, item := range rf {
	//	if item.Insutype == insutype {
	//		insuplc_admdvs = item.InsuplcAdmdvs
	//	}
	//}

	if res2.Infcode == 0 {

		//var insutypes []string
		//
		//var insutype string
		//var is390 int = 0
		//var is310 int = 0
		//for _, item := range res2.Output.Iinfo {
		//	if (item.Insutype == "390" && item.PsnInsuStas == "1") || (item.Insutype == "310" && item.PsnInsuStas == "1") {
		//		insutypes = append(insutypes, item.Insutype)
		//	}
		//}
		//if len(insutypes) == 1 {
		//	insutype = insutypes[0]
		//} else {
		//	for _, i := range insutypes {
		//		if i == "390" {
		//			is390 = 1
		//		}
		//
		//		if i == "310" {
		//			is310 = 1
		//		}
		//	}
		//}
		//if is390 == 1 {
		//	insutype = "390"
		//}
		//if is310 == 1 {
		//	insutype = "310"
		//}
		//
		//if len(insutypes) == 0 {
		//	insutype = "310"
		//}

		if len(insuplc_admdvs) == 0 {
			insuplc_admdvs = miConfig.InsuplcAdmdvs
		}

		timestamp := time.Now().Unix()
		tempTime := time.Unix(timestamp, 0)
		timeFormat := tempTime.Format("20060102150405")
		chrgBchno := rand.Intn(100000) + 10000
		ipt_otp_no := timeFormat + strconv.FormatInt(int64(chrgBchno), 10) + strconv.FormatInt(id, 10)

		timeFormatOne := tempTime.Format("2006-01-02 15:04:05")
		var struct2401 service.Struct2401
		struct2401.PsnNo = res2.Output.Baseinfo.PsnNo
		struct2401.Insutype = insutype
		psn_info, _ := service.GetPsnByPatientId(patient.ID)

		if id_card_type == 1 {
			struct2401.MdtrtCertType = "03"
			bas := strings.Split(psn_info.CardInfo, "|")
			cardNumber := bas[2]
			struct2401.MdtrtCertNo = cardNumber
		} else {
			struct2401.MdtrtCertType = "02"
			struct2401.MdtrtCertNo = res2.Output.Baseinfo.Certno
		}

		if miConfig.Code == "H15049901371" {
			if med_type == 14 {
				if insutype == "390" {

					struct2401.MedType = "9933"

				} else if insutype == "310" {

					struct2401.MedType = "990502"

				}
			} else if med_type == 11 {
				struct2401.MedType = "11"
			}
		} else {
			struct2401.MedType = strconv.FormatInt(int64(med_type), 10)
		}
		struct2401.IptNo = ipt_otp_no
		struct2401.AtddrNo = strconv.FormatInt(int64(doctorInfo.AdminUserId), 10)
		struct2401.ChfpdrName = doctorInfo.UserName
		struct2401.AdmDiagDscr = diagnosisConfig[0].ClassName
		struct2401.AdmDeptCodg = strconv.FormatInt(int64(departmentInfo.ID), 10)
		struct2401.AdmDeptName = departmentInfo.Name
		struct2401.AdmBed = deviceNumber.Number
		struct2401.AdmBed = "待定"

		struct2401.DscgMaindiagName = diagnosisConfig[0].ClassName
		struct2401.DscgMaindiagCode = diagnosisConfig[0].CountryCode
		struct2401.Begntime = start_time
		struct2401.DiseCodg = sickConfig.CountryCode
		struct2401.DiseName = sickConfig.ClassName

		var dises []service.DiseinfoStruct

		for index, item := range diagnosisConfig {
			var dise service.DiseinfoStruct

			dise.PsnNo = res2.Output.Baseinfo.PsnNo
			dise.DiagType = "1"
			if index == 0 {
				dise.MaindiagFlag = "1"
			} else {
				dise.MaindiagFlag = "2"
			}

			dise.DiagSrtNo = strconv.FormatInt(int64(index), 10)
			dise.DiseDorName = doctorInfo.UserName
			dise.DiagCode = item.CountryCode
			dise.DiagName = item.ClassName
			dise.DiagDept = departmentInfo.Name
			dise.DiseDorNo = strconv.FormatInt(int64(doctorInfo.AdminUserId), 10)
			dise.DiagTime = timeFormatOne

			dises = append(dises, dise)
		}
		struct2401.Diseinfo = dises

		var result string
		var request_log string
		if miConfig.MdtrtareaAdmvs == "150499" {
			data := make(map[string]interface{})
			data["org_name"] = miConfig.OrgName
			data["doctor"] = role.UserName
			data["fixmedins_code"] = miConfig.Code
			data["insuplc_admdvs"] = insuplc_admdvs
			data["mdtrtarea_admvs"] = miConfig.MdtrtareaAdmvs
			data["secret_key"] = miConfig.SecretKey
			data["struct_2401"] = struct2401

			var req *http.Request
			bytesData, _ := json.Marshal(data)
			req, _ = http.NewRequest("POST", "http://172.16.13.254:9532/"+"nmyb/2401", bytes.NewReader(bytesData))
			client := &http.Client{}
			resp, _ := client.Do(req)
			defer resp.Body.Close()
			body, ioErr := ioutil.ReadAll(resp.Body)
			if ioErr != nil {
				utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			var respJSON map[string]interface{}
			if err := json.Unmarshal([]byte(body), &respJSON); err != nil {
				utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
			result_byte, _ := json.Marshal(respJSON)
			result = string(result_byte)
		} else {
			result, request_log = service.ZHGdyb2401(struct2401, miConfig.SecretKey, miConfig.OrgName, miConfig.Code, role.UserName, insuplc_admdvs, miConfig.MdtrtareaAdmvs)
			saveLog(result, request_log, "2401", "入院登记")
		}
		var dat map[string]interface{}
		if err := json.Unmarshal([]byte(result), &dat); err == nil {
			fmt.Println(dat)
		} else {
			fmt.Println(err)
		}
		userJSONBytes, _ := json.Marshal(dat)
		var res ResultThree
		var resThree10265 ResultThree10265

		if miConfig.Code == "H15049901371" {

			if err := json.Unmarshal(userJSONBytes, &resThree10265); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			Infcode, _ := strconv.ParseInt(resThree10265.Infcode, 10, 64)
			res.Infcode = Infcode
			res.ErrMsg = resThree10265.ErrMsg
			res.Output = resThree10265.Output
			res.InfRefmsgid = resThree10265.InfRefmsgid
			res.RespondTime = resThree10265.RespondTime

		} else {

			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

		}

		if res.Infcode == 0 {
			//result2 := service.Gdyb5301Two(res2.Output.Baseinfo.PsnNo, miConfig.OrgName, role.UserName, miConfig.Code, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey)
			//fmt.Println(result2)
			Iinfos, _ := json.Marshal(res2.Output.Iinfo)
			Idetinfos, _ := json.Marshal(res2.Output.Idetinfo)
			infoStr := string(Iinfos)
			idetinfoStr := string(Idetinfos)
			inHospital := &models.HisHospitalCheckRecord{
				PatientId:            id,
				Name:                 name,
				MedicalTreatmentType: med_type,
				RecordDate:           recordDateTime,
				IdCardNo:             id_card_no,
				AdminUserId:          admin_user_id,
				Departments:          department,
				UserOrgId:            adminInfo.CurrentOrgId,
				Status:               1,
				Ctime:                time.Now().Unix(),
				Mtime:                time.Now().Unix(),
				Number:               res.Output.Result.MdtrtID,
				Doctor:               doctor,
				PsnNo:                res2.Output.Baseinfo.PsnNo,
				PsnCertType:          res2.Output.Baseinfo.PsnCertType,
				Certno:               res2.Output.Baseinfo.Certno,
				PsnName:              res2.Output.Baseinfo.PsnName,
				Gend:                 res2.Output.Baseinfo.Gend,
				Naty:                 res2.Output.Baseinfo.Naty,
				MedType:              med_type,
				InsutypeType:         insutype,
				Brdy:                 res2.Output.Baseinfo.Brdy,
				Iinfo:                infoStr,
				Idetinfo:             idetinfoStr,
				IptOtpNo:             ipt_otp_no,
				AdmBed:               adm_bed,
				IdCardType:           id_card_type,
				Diagnosis:            diagnosis_ids,
				SickType:             sick_type,
				MdtrtCertType:        "02",
				InHosptialTime:       start_time,
				OutHosptialTime:      "",
				InHospitalStatus:     1,
				Certificates:         certificates,
				Phone:                phone,
				BalanceAccountsType:  balance_accounts_type,
				PsnType:              psn_type,
				InsuplcAdmdvs:        insuplc_admdvs,
			}
			service.CreateHospitalRecord(inHospital)
			c.ServeSuccessJSON(map[string]interface{}{
				"msg":  "办理入院成功",
				"info": inHospital,
			})

		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res.ErrMsg,
			})
		}

	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         res2.ErrMsg,
		})
		return
	}

}
func (this *ZHHisApiController) GetZHOutHospitalCheck() {
	id, _ := this.GetInt64("id")
	patient_id, _ := this.GetInt64("patient_id")
	admin_user_id, _ := this.GetInt64("admin_user_id")
	record_time := this.GetString("record_time")
	out_time := this.GetString("out_time")

	adminInfo := this.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)
	role, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, admin_user_id)

	record, _ := service.GetInHospitalRecord(id)
	if record.ID == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeInHospitalNoExistDataException)
		return
	}

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()

	var patient service.Patients
	if patient_id == 0 {
		patient, _ = service.GetPatientByIDCard(record.IdCardNo, adminInfo.CurrentOrgId)
	} else {
		patient, _ = service.GetPatientByIDTwo(adminInfo.CurrentOrgId, id)
	}
	fmt.Println(patient)
	diagnosis_ids_arr := strings.Split(record.Diagnosis, "-")

	diagnosisConfig, _ := service.FindDiagnoseByIds(diagnosis_ids_arr)
	departmentInfo, _ := service.GetDepartMentDetail(record.Departments)
	doctorInfo, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, record.Doctor)
	//deviceNumber, _ := service.GetDeviceNumberByID(record.AdmBed, adminInfo.CurrentOrgId)
	sickConfig, _ := service.FindSickById(record.SickType)

	var struct2402 service.Struct2402
	timestamp := time.Now().Unix()
	tempTime := time.Unix(timestamp, 0)
	//timeFormat := tempTime.Format("20060102150405")
	timeFormatOne := tempTime.Format("2006-01-02 15:04:05")

	struct2402.PsnNo = record.PsnNo
	struct2402.Insutype = record.InsutypeType
	struct2402.DscgWay = "1"
	struct2402.Endtime = out_time
	struct2402.DscgDeptName = departmentInfo.Number
	struct2402.DscgDeptCodg = strconv.FormatInt(int64(departmentInfo.ID), 10)
	struct2402.MdtrtId = record.Number

	var dises []service.Diseinfo2402Struct

	for index, item := range diagnosisConfig {
		var dise service.Diseinfo2402Struct

		dise.PsnNo = record.PsnNo
		dise.DiagType = "1"
		if index == 0 {
			dise.MaindiagFlag = "1"
		} else {
			dise.MaindiagFlag = "2"
		}

		dise.MdtrtId = record.Number
		dise.DiagSrtNo = strconv.FormatInt(int64(item.ID), 10)
		dise.DiseDorName = doctorInfo.UserName
		dise.DiagCode = item.CountryCode
		dise.DiagName = item.ClassName
		dise.DiagDept = departmentInfo.Name
		dise.DiseDorNo = strconv.FormatInt(int64(doctorInfo.AdminUserId), 10)
		dise.DiagTime = timeFormatOne

		dises = append(dises, dise)
	}
	struct2402.Diseinfo = dises
	struct2402.DiseName = sickConfig.ClassName
	struct2402.DiseCode = sickConfig.CountryCode

	var result string
	var request_log string
	if miConfig.MdtrtareaAdmvs == "150499" {
		data := make(map[string]interface{})
		data["org_name"] = miConfig.OrgName
		data["doctor"] = role.UserName
		data["fixmedins_code"] = miConfig.Code
		data["insuplc_admdvs"] = record.InsuplcAdmdvs
		data["mdtrtarea_admvs"] = miConfig.MdtrtareaAdmvs
		data["secret_key"] = miConfig.SecretKey
		data["struct_2402"] = struct2402
		var req *http.Request
		bytesData, _ := json.Marshal(data)
		req, _ = http.NewRequest("POST", "http://172.16.13.254:9532/"+"nmyb/2402", bytes.NewReader(bytesData))
		client := &http.Client{}
		resp, _ := client.Do(req)
		defer resp.Body.Close()
		body, ioErr := ioutil.ReadAll(resp.Body)
		if ioErr != nil {
			utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		var respJSON map[string]interface{}
		if err := json.Unmarshal([]byte(body), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		result_byte, _ := json.Marshal(respJSON)
		result = string(result_byte)
	} else {
		result, request_log = service.ZHGdyb2402(struct2402, miConfig.OrgName, role.UserName, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, miConfig.Code)
		saveLog(result, request_log, "2402", "出院")
	}

	var dat map[string]interface{}
	if err := json.Unmarshal([]byte(result), &dat); err == nil {
		fmt.Println(dat)
	} else {
		fmt.Println(err)
	}
	userJSONBytes, _ := json.Marshal(dat)
	var res ResultEmpty
	var resEmpty10265 ResultEmpty10265

	if miConfig.Code == "H15049901371" {

		if err := json.Unmarshal(userJSONBytes, &resEmpty10265); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Infcode, _ := strconv.ParseInt(resEmpty10265.Infcode, 10, 64)
		res.Infcode = Infcode
		res.RespondTime = resEmpty10265.RespondTime
		res.ErrMsg = resEmpty10265.ErrMsg
		res.Output = resEmpty10265.Output
		res.WarnMsg = resEmpty10265.WarnMsg

	} else {
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	}

	if res.Infcode == 0 {
		record.OutHospitalStatus = 1
		record.OutHosptialTime = struct2402.Endtime
		record.OutWay = 1
		service.CreateHospitalRecord(&record)

		orders, _ := service.GetHisOrderInfoByNumberFour(record.Number)
		var total float64
		for _, item := range orders {
			total = total + item.DetItemFeeSumamt
		}

		order := &models.HisOrder{
			UserOrgId:           adminInfo.CurrentOrgId,
			HisPatientId:        record.ID,
			PatientId:           record.PatientId,
			SettleAccountsDate:  recordDateTime,
			Ctime:               time.Now().Unix(),
			Mtime:               time.Now().Unix(),
			Status:              1,
			Number:              record.Number,
			Infcode:             0,
			WarnMsg:             "",
			Cainfo:              "",
			ErrMsg:              "",
			RespondTime:         "",
			InfRefmsgid:         "",
			OrderStatus:         1,
			MdtrtId:             record.Number,
			IsMedicineInsurance: 1,
			PType:               1,
			MedfeeSumamt:        total,
		}
		err = service.CreateOrder(order)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreatePreOrderException)
			return
		}

		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "出院成功",
		})

	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         res.ErrMsg,
		})
	}

}
func (c *ZHHisApiController) GetSettleInfo() {
	order_id, _ := c.GetInt64("order_id")
	patient_id, _ := c.GetInt64("patient_id")
	in_hospital_id, _ := c.GetInt64("in_hospital_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	pay_way, _ := c.GetInt64("pay_way")
	pay_price, _ := c.GetFloat("pay_price")
	pay_card_no := c.GetString("pay_card_no")
	discount_price, _ := c.GetFloat("discount_price")
	preferential_price, _ := c.GetFloat("preferential_price")
	reality_price, _ := c.GetFloat("reality_price")
	found_price, _ := c.GetFloat("found_price")
	medical_insurance_price, _ := c.GetFloat("medical_insurance_price")
	private_price, _ := c.GetFloat("private_price")
	fapiao_code := c.GetString("fapiao_code")
	fapiao_number := c.GetString("fapiao_number")

	record, _ := service.GetInHospitalRecord(in_hospital_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)
	roles, _ := service.GetAdminUserInfoByID(c.GetAdminUserInfo().CurrentOrgId, admin_user_id)
	order, _ := service.GetHisOrderByID(order_id)

	//dec_way := c.GetString("dec_way") //是否使用押金支付bool类型
	//tmp_decimal := c.GetString("tmp_decimal")
	//var decimal float64 //本次使用的押金

	dec_way := c.GetString("dec_way") //是否使用押金支付bool类型
	tmp_decimal := c.GetString("tmp_decimal")
	var decimal float64 //本次使用的押金
	var errmsg error

	if dec_way == "true" && tmp_decimal == "0" || dec_way == "true" && tmp_decimal == "" {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金不能为0")
		return
	}
	if len(tmp_decimal) > 0 {
		if tmp_decimal[0] == 45 {
			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金不能为负数")
			return
		}
	}
	tt, errs := strconv.ParseFloat(tmp_decimal, 64)
	if errs != nil {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金金额错误")
		return
	}
	decimal = tt

	var rf []*ResultFive
	json.Unmarshal([]byte(record.Iinfo), &rf)
	chrg_bchno := order.Number
	cert_no := record.Certno
	if record.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	if record.InHospitalStatus == 1 && record.OutHospitalStatus == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHospitalNoExistDataException)
		return
	}
	if record.IdCardType == 1 {
	} else {
		cert_no = record.Certno
	}
	var result string
	var src_resquest string

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record.InHosptialTime, loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordStartDateTime := theTime.Unix()

	theTimeEnd, err := time.ParseInLocation(timeLayout+" 15:04:05", record.OutHosptialTime, loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordEndDateTime := theTimeEnd.Unix()

	prescriptions, _ := service.GetZHSettleMonthHisPrescription(c.GetAdminUserInfo().CurrentOrgId, patient_id, recordStartDateTime, recordEndDateTime)

	var total float64
	for _, item := range prescriptions {
		if item.Type == 1 { //药品
			for _, subItem := range item.HisDoctorAdviceInfo {
				total = total + (subItem.Price * subItem.PrescribingNumber)
			}
		}
		if item.Type == 2 { //项目
			for _, subItem := range item.HisPrescriptionProject {
				cnt, _ := strconv.ParseFloat(subItem.Count, 64)
				total = total + (subItem.Price * cnt)
			}
		}
	}
	//allTotal := fmt.Sprintf("%.2f", total)

	var allTotal string
	if record.OutHospitalStatus == 0 && order.ID == 0 {
		orders, _ := service.GetHisOrderInfoByNumberFour(record.Number)
		var total float64
		for _, item := range orders {
			total = total + item.DetItemFeeSumamt
		}
		allTotal = fmt.Sprintf("%.4f", total)

	} else {

		allTotal = fmt.Sprintf("%.4f", order.MedfeeSumamt)

	}

	if miConfig.MdtrtareaAdmvs == "150499" {
		psn_info, _ := service.GetPsnByPatientId(patient_id)
		mdtrt_cert_no := ""
		if record.IdCardType == 1 {
			bas := strings.Split(psn_info.CardInfo, "|")
			cardNumber := bas[2]
			mdtrt_cert_no = cardNumber

		} else {
			mdtrt_cert_no = record.Certno
		}
		var acct_used_flag string
		if pay_way == 5 {
			acct_used_flag = "1"
		} else {
			acct_used_flag = "0"
		}

		//请求内网数据
		api := "http://172.16.13.254:9532/" + "nmyb/2304?psn_no=" + record.PsnNo + "&mdtrt_id=" + record.Number + "&chrg_bchno=" + chrg_bchno +
			"&insutype_type=" + record.InsutypeType + "&total=" + allTotal +
			"&org_name=" + miConfig.OrgName + "&doctor=" + roles.UserName + "&fixmedins_code=" + miConfig.Code +
			"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&id_card_type=" + strconv.FormatInt(record.IdCardType, 10) + "&card_sn=" + "" + "&certificates=" + strconv.FormatInt(record.Certificates, 10) + "&name=" + record.Name + "&cert_no=" + mdtrt_cert_no + "&fapiao_number=" + fapiao_number + "&acct_used_flag=" + acct_used_flag
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		body, ioErr := ioutil.ReadAll(resp.Body)
		if ioErr != nil {
			utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		var respJSON map[string]interface{}

		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		result_byte, _ := json.Marshal(respJSON)
		result = string(result_byte)

	} else {

		result, src_resquest = service.ZHGdyb2304(record.PsnNo, record.Number, chrg_bchno, cert_no, record.InsutypeType, allTotal, miConfig.OrgName, roles.UserName, miConfig.Code, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, "0", record.IdCardType, 0, 0, 0, 0, record.Certificates, "", "1")
		saveLog(result, src_resquest, "2304", "住院结算")
	}

	var dat map[string]interface{}
	if err := json.Unmarshal([]byte(result), &dat); err == nil {
		fmt.Println(dat)
	} else {
		fmt.Println(err)
	}
	userJSONBytes, _ := json.Marshal(dat)
	var res ResultSeven
	var resSeven10265 ResultSeven10265
	if miConfig.Code == "H15049901371" {
		if err := json.Unmarshal(userJSONBytes, &resSeven10265); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Infcode, _ := strconv.ParseInt(resSeven10265.Infcode, 10, 64)
		res.Infcode = Infcode
		res.InfRefmsgid = resSeven10265.InfRefmsgid
		res.RespondTime = resSeven10265.RespondTime
		res.ErrMsg = resSeven10265.ErrMsg
		res.Output = resSeven10265.Output
		res.WarnMsg = resSeven10265.WarnMsg
		res.Cainfo = resSeven10265.Cainfo

	} else {
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

	}

	if res.Infcode != 0 {
		errlog := &models.HisOrderError{
			UserOrgId:  c.GetAdminUserInfo().CurrentOrgId,
			Ctime:      time.Now().Unix(),
			Mtime:      time.Now().Unix(),
			Number:     chrg_bchno,
			ErrMsg:     res.ErrMsg,
			Status:     1,
			PatientId:  patient_id,
			RecordTime: time.Now().Unix(),
			Stage:      6,
		}
		service.CreateErrMsgLog(errlog)
		c.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         res.ErrMsg,
		})
		return
	} else {
		//order, _ := service.GetHisOrderTwo(adminUser.CurrentOrgId, chrg_bchno, id)
		order.OrderStatus = 2
		order.DiscountPrice = discount_price
		order.MedicalInsurancePrice = medical_insurance_price
		order.FaPiaoNumber = fapiao_number
		order.FaPiaoCode = fapiao_code
		order.PayWay = pay_way
		order.PayPrice = pay_price
		order.PayCardNo = pay_card_no
		order.PreferentialPrice = preferential_price
		order.RealityPrice = reality_price
		order.FoundPrice = found_price
		order.PrivatePrice = private_price
		order.MdtrtId = res.Output.Setlinfo.MdtrtID
		order.SetlId = res.Output.Setlinfo.SetlID
		order.PsnNo = res.Output.Setlinfo.PsnNo
		order.PsnName = res.Output.Setlinfo.PsnName
		order.PsnCertType = res.Output.Setlinfo.PsnCertType
		order.Certno = res.Output.Setlinfo.Certno
		order.Gend = res.Output.Setlinfo.Gend
		order.Naty = res.Output.Setlinfo.Naty
		order.Age = res.Output.Setlinfo.Age
		order.Insutype = res.Output.Setlinfo.Insutype
		order.PsnType = res.Output.Setlinfo.PsnType
		order.CvlservFlag = res.Output.Setlinfo.CvlservFlag
		order.SetlTime = res.Output.Setlinfo.SetlTime
		order.MdtrtCertType = res.Output.Setlinfo.MdtrtCertType
		if res.Output.Setlinfo.MedType == "140104" {

			order.MedType = "14"

		} else {

			order.MedType = res.Output.Setlinfo.MedType

		}
		order.MedfeeSumamt = res.Output.Setlinfo.MedfeeSumamt
		order.FulamtOwnpayAmt = res.Output.Setlinfo.FulamtOwnpayAmt
		order.OverlmtSelfPay = res.Output.Setlinfo.OverlmtSelfpay
		order.PreselfpayAmt = res.Output.Setlinfo.PreselfpayAmt
		order.InscpScpAmt = res.Output.Setlinfo.InscpScpAmt
		order.ActPayDedc = res.Output.Setlinfo.ActPayDedc
		order.HifpPay = res.Output.Setlinfo.HifpPay
		order.CvlservPay = res.Output.Setlinfo.CvlservPay
		order.PoolPropSelfpay = res.Output.Setlinfo.PoolPropSelfpay
		order.HifesPay = res.Output.Setlinfo.HifesPay
		order.HifobPay = res.Output.Setlinfo.HifobPay
		order.MafPay = res.Output.Setlinfo.MafPay
		order.OthPay = res.Output.Setlinfo.OthPay
		order.FundPaySumamt = res.Output.Setlinfo.FundPaySumamt
		order.PsnPartAmt = res.Output.Setlinfo.PsnPartAmt
		order.AcctPay = res.Output.Setlinfo.AcctPay
		order.PsnCashPay = res.Output.Setlinfo.PsnCashPay
		order.HospPartAmt = res.Output.Setlinfo.HospPartAmt
		order.Balc = res.Output.Setlinfo.Balc
		order.AcctMulaidPay = res.Output.Setlinfo.AcctMulaidPay
		order.MedinsSetlId = res.Output.Setlinfo.MedinsSetlID
		order.ClrOptins = res.Output.Setlinfo.ClrOptins
		order.ClrWay = res.Output.Setlinfo.ClrWay
		order.Creator = order.Creator
		order.Modify = roles.AdminUserId
		order.RequestLog = src_resquest
		setlDetail, _ := json.Marshal(res.Output.Setldetail)
		detailStr := string(setlDetail)
		order.SetlDetail = detailStr
		err := service.UpdataOrderStatusTwo(chrg_bchno, c.GetAdminUserInfo().CurrentOrgId)
		err = service.UpDateOrder(order)
		if err == nil {
			//判断是否使用了押金
			if dec_way == "true" {
				tmpstring := strconv.FormatInt(order.ID, 10)
				order.Decimal = decimal
				err = service.UpDateOrder(order)
				//扣押金
				errmsg = service.SpendDeposit(c.GetAdminUserInfo().CurrentOrgId, patient_id, c.GetAdminUserInfo().AdminUser.Id, tmpstring, decimal)
				if errmsg != nil {
					c.ServeFailJsonSend(enums.ErrorCodeParamWrong, errmsg.Error())
					//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateOrderException)
					return
				}
			}

			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "结算成功",
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAmountAccountException)
			return
		}
	}

}
func (c *ZHHisApiController) GetPreSettleInfo() {
	order_id, _ := c.GetInt64("order_id")
	patient_id, _ := c.GetInt64("patient_id")
	in_hospital_id, _ := c.GetInt64("in_hospital_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	record, _ := service.GetInHospitalRecord(in_hospital_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)
	roles, _ := service.GetAdminUserInfoByID(c.GetAdminUserInfo().CurrentOrgId, admin_user_id)
	order, _ := service.GetHisOrderByID(order_id)

	var allTotal string
	if record.OutHospitalStatus == 0 && order.ID == 0 {

		orders, _ := service.GetHisOrderInfoByNumberFour(record.Number)
		var total float64
		for _, item := range orders {
			total = total + item.DetItemFeeSumamt
		}
		allTotal = fmt.Sprintf("%.4f", total)

	} else {

		allTotal = fmt.Sprintf("%.4f", order.MedfeeSumamt)

	}

	var rf []*ResultFive
	json.Unmarshal([]byte(record.Iinfo), &rf)
	chrg_bchno := order.Number
	cert_no := record.Certno
	if record.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	//if record.InHospitalStatus == 1 && record.OutHospitalStatus == 0 {
	//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHospitalNoExistDataException)
	//	return
	//}
	psn_info, _ := service.GetPsnByPatientId(patient_id)

	if record.IdCardType == 1 {
		bas := strings.Split(psn_info.CardInfo, "|")
		cardNumber := bas[2]
		cert_no = cardNumber

	} else {
		cert_no = record.Certno
	}
	var result string
	var src_resquest string

	if miConfig.MdtrtareaAdmvs == "150499" {
		//请求内网数据
		api := "http://172.16.13.254:9532/" + "nmyb/2303?psn_no=" + record.PsnNo + "&mdtrt_id=" + record.Number + "&chrg_bchno=" + chrg_bchno +
			"&insutype_type=" + record.InsutypeType + "&total=" + allTotal +
			"&org_name=" + miConfig.OrgName + "&doctor=" + roles.UserName + "&fixmedins_code=" + miConfig.Code +
			"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&id_card_type=" + strconv.FormatInt(record.IdCardType, 10) + "&card_sn=" + "" + "&certificates=" + strconv.FormatInt(record.Certificates, 10) + "&name=" + record.Name + "&cert_no=" + cert_no
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		body, ioErr := ioutil.ReadAll(resp.Body)
		if ioErr != nil {
			utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		var respJSON map[string]interface{}

		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		result_byte, _ := json.Marshal(respJSON)
		result = string(result_byte)

	} else {
		result, src_resquest = service.ZHGdyb2303(record.PsnNo, record.Number, chrg_bchno, cert_no, record.InsutypeType, allTotal, miConfig.OrgName, roles.UserName, miConfig.Code, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, "0", record.IdCardType, 0, 0, 0, 0, record.Certificates)
		saveLog(result, src_resquest, "2303", "住院预结算")

	}

	var dat map[string]interface{}
	if err := json.Unmarshal([]byte(result), &dat); err == nil {
		fmt.Println(dat)
	} else {
		fmt.Println(err)
	}
	userJSONBytes, _ := json.Marshal(dat)
	var res ResultSeven
	var resSeven10265 ResultSeven10265
	if miConfig.Code == "H15049901371" {
		if err := json.Unmarshal(userJSONBytes, &resSeven10265); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Infcode, _ := strconv.ParseInt(resSeven10265.Infcode, 10, 64)
		res.Infcode = Infcode
		res.InfRefmsgid = resSeven10265.InfRefmsgid
		res.RespondTime = resSeven10265.RespondTime
		res.ErrMsg = resSeven10265.ErrMsg
		res.Output = resSeven10265.Output
		res.WarnMsg = resSeven10265.WarnMsg
		res.Cainfo = resSeven10265.Cainfo

	} else {
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

	}

	if res.Infcode != 0 {
		errlog := &models.HisOrderError{
			UserOrgId:  c.GetAdminUserInfo().CurrentOrgId,
			Ctime:      time.Now().Unix(),
			Mtime:      time.Now().Unix(),
			Number:     chrg_bchno,
			ErrMsg:     res.ErrMsg,
			Status:     1,
			PatientId:  patient_id,
			RecordTime: time.Now().Unix(),
			Stage:      6,
		}
		service.CreateErrMsgLog(errlog)
		c.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         res.ErrMsg,
		})
		return
	} else {
		//order, _ := service.GetHisOrderTwo(adminUser.CurrentOrgId, chrg_bchno, id)
		order.OrderStatus = 1
		order.MdtrtId = res.Output.Setlinfo.MdtrtID
		order.SetlId = res.Output.Setlinfo.SetlID
		order.PsnNo = res.Output.Setlinfo.PsnNo
		order.PsnName = res.Output.Setlinfo.PsnName
		order.PsnCertType = res.Output.Setlinfo.PsnCertType
		order.Certno = res.Output.Setlinfo.Certno
		order.Gend = res.Output.Setlinfo.Gend
		order.Naty = res.Output.Setlinfo.Naty
		order.Age = res.Output.Setlinfo.Age
		order.Insutype = res.Output.Setlinfo.Insutype
		order.PsnType = res.Output.Setlinfo.PsnType
		order.CvlservFlag = res.Output.Setlinfo.CvlservFlag
		order.SetlTime = res.Output.Setlinfo.SetlTime
		order.MdtrtCertType = res.Output.Setlinfo.MdtrtCertType
		if res.Output.Setlinfo.MedType == "140104" {

			order.MedType = "14"

		} else {

			order.MedType = res.Output.Setlinfo.MedType

		}
		order.MedfeeSumamt = res.Output.Setlinfo.MedfeeSumamt
		order.FulamtOwnpayAmt = res.Output.Setlinfo.FulamtOwnpayAmt
		order.OverlmtSelfPay = res.Output.Setlinfo.OverlmtSelfpay
		order.PreselfpayAmt = res.Output.Setlinfo.PreselfpayAmt
		order.InscpScpAmt = res.Output.Setlinfo.InscpScpAmt
		order.ActPayDedc = res.Output.Setlinfo.ActPayDedc
		order.HifmiPay = res.Output.Setlinfo.HifmiPay
		order.HifpPay = res.Output.Setlinfo.HifpPay
		order.HifesPay = res.Output.Setlinfo.HifesPay
		order.HifobPay = res.Output.Setlinfo.HifobPay
		order.MafPay = res.Output.Setlinfo.MafPay
		order.OthPay = res.Output.Setlinfo.OthPay
		order.CvlservPay = res.Output.Setlinfo.CvlservPay
		order.PoolPropSelfpay = res.Output.Setlinfo.PoolPropSelfpay
		order.FundPaySumamt = res.Output.Setlinfo.FundPaySumamt
		order.PsnPartAmt = res.Output.Setlinfo.PsnPartAmt
		order.AcctPay = res.Output.Setlinfo.AcctPay
		order.PsnCashPay = res.Output.Setlinfo.PsnCashPay
		order.HospPartAmt = res.Output.Setlinfo.HospPartAmt
		order.Balc = res.Output.Setlinfo.Balc
		order.AcctMulaidPay = res.Output.Setlinfo.AcctMulaidPay
		order.MedinsSetlId = res.Output.Setlinfo.MedinsSetlID
		order.ClrOptins = res.Output.Setlinfo.ClrOptins
		order.ClrWay = res.Output.Setlinfo.ClrWay
		order.Creator = order.Creator
		order.Modify = roles.AdminUserId
		order.RequestLog = src_resquest
		setlDetail, _ := json.Marshal(res.Output.Setldetail)
		detailStr := string(setlDetail)
		order.SetlDetail = detailStr
		//err := service.UpdataOrderStatusTwo(chrg_bchno, c.GetAdminUserInfo().CurrentOrgId)
		if record.OutHospitalStatus == 1 && order.ID > 0 {
			err := service.UpDateOrder(order)
			if err == nil {
				c.ServeSuccessJSON(map[string]interface{}{
					"msg":       "预结算成功",
					"order_way": 1,
				})
			} else {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAmountAccountException)
				return
			}
		} else if record.OutHospitalStatus == 0 && order.ID == 0 {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg":       "预结算成功",
				"order":     order,
				"order_way": 2,
			})
		}
	}

}

func (c *ZHHisApiController) GetUploadInfo() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	in_hospital_id, _ := c.GetInt64("in_hospital_id")
	settle_accounts_type, _ := c.GetInt64("settle_accounts_type")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminUser := c.GetAdminUserInfo()
	var prescriptions []*models.HisPrescription
	data := make(map[string]interface{})
	if settle_accounts_type == 1 { //日结
		prescriptions, _ = service.GetZHHisPrescription(adminUser.CurrentOrgId, id, recordDateTime)

	} else { //月结
		start_time_str := c.GetString("start_time")
		end_time_str := c.GetString("end_time")
		timeLayout := "2006-01-02"
		loc, _ := time.LoadLocation("Local")
		theStartTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time_str+" 00:00:00", loc)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		recordStartTime := theStartTime.Unix()
		theEndTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time_str+" 00:00:00", loc)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		recordEndTime := theEndTime.Unix()
		prescriptions, _ = service.GetZHMonthHisPrescription(adminUser.CurrentOrgId, id, recordStartTime, recordEndTime)

	}
	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	record, _ := service.GetInHospitalRecord(in_hospital_id)
	if record.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

	timestamp := time.Now().Unix()
	tempTime := time.Unix(timestamp, 0)
	timeFormat := tempTime.Format("20060102150405")
	chrgBchno := rand.Intn(100000) + 10000
	chrg_bchno := timeFormat + strconv.FormatInt(int64(chrgBchno), 10) + strconv.FormatInt(record.PatientId, 10)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	patientPrescription, _ := service.FindPatientPrescriptionInfo(adminUser.CurrentOrgId, id, recordDateTime)
	department, _ := service.GetDepartMentDetail(record.Departments)
	strconv.FormatInt(record.PatientId, 10)

	doctor_info, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, record.Doctor)

	//client := &http.Client{}
	data["psn_no"] = record.PsnNo
	data["mdtrt_id"] = record.Number
	data["chrg_bchno"] = chrg_bchno
	data["org_name"] = miConfig.OrgName
	data["doctor"] = roles.UserName
	data["doctor_id"] = strconv.FormatInt(roles.AdminUserId, 10)
	data["dept"] = strconv.FormatInt(department.ID, 10)
	data["fixmedins_code"] = miConfig.Code
	if (department.ID == 0 && adminUser.CurrentOrgId == 9919) || (department.ID == 0 && adminUser.CurrentOrgId == 10106) {
		data["dept_code"] = "15"
	} else {
		data["dept_code"] = department.Number
	}
	if miConfig.Code == "H15049901371" {
		if record.MedType == 14 {
			if record.InsutypeType == "390" {

				data["med_type"] = "9933"

			} else if record.InsutypeType == "310" {

				data["med_type"] = "990502"

			}

		} else if record.MedType == 11 {

			data["med_type"] = strconv.FormatInt(record.MedType, 10)

		}

	} else {
		if record.MedType == 1112 {
			data["med_type"] = strconv.FormatInt(11, 10)
		} else {
			data["med_type"] = strconv.FormatInt(record.MedType, 10)
		}

	}
	data["insuplc_admdvs"] = record.InsuplcAdmdvs
	data["mdtrtarea_admvs"] = miConfig.MdtrtareaAdmvs
	data["secret_key"] = miConfig.SecretKey
	var ids []int64

	fmt.Println(data)

	for _, item := range prescriptions {
		ids = append(ids, item.ID)
	}
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	if config.IsOpen == 1 { //对接了医保,走医保流程

		var pagesize int = 100
		var start int = 1
		var stop int
		var pagecount int
		var curpage int
		var isSuccess bool = true

		var customs []*models.NewCustom

		for _, item := range prescriptions {
			tm := time.Unix(item.PreTime, 0)
			if item.Type == 1 { //药品
				for _, subItem := range item.HisDoctorAdviceInfo {
					if len(subItem.BaseDrugLib.MedicalInsuranceNumber) > 0 && subItem.BaseDrugLib.IsUser != 1 {
						//var randNum int
						//randNum = rand.Intn(10000) + 1000
						cus := &models.NewCustom{
							DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*subItem.PrescribingNumber),
							Cut:              fmt.Sprintf("%.4f", subItem.PrescribingNumber),
							FeedetlSn:        subItem.FeedetlSn,
							Price:            fmt.Sprintf("%.4f", subItem.Price),
							MedListCodg:      subItem.BaseDrugLib.MedicalInsuranceNumber,
							HospApprFlag:     subItem.BaseDrugLib.HospApprFlag,
							FeeOcurTime:      tm.Format("2006-01-02 15:04:05"),
						}

						customs = append(customs, cus)
					}
				}
			}

			if item.Type == 2 { //项目
				for _, subItem := range item.HisPrescriptionProject {
					//var randNum int
					//randNum = rand.Intn(10000) + 1000
					if subItem.Type == 2 {
						if len(subItem.HisProject.MedicalCode) > 0 {
							cnt, _ := strconv.ParseFloat(subItem.Count, 64)
							cus := &models.NewCustom{
								DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*cnt),
								Cut:              fmt.Sprintf("%.4f", cnt),
								FeedetlSn:        subItem.FeedetlSn,
								Price:            fmt.Sprintf("%.4f", float64(subItem.Price)),
								MedListCodg:      subItem.HisProject.MedicalCode,
								HospApprFlag:     -1,
								FeeOcurTime:      tm.Format("2006-01-02 15:04:05"),
							}
							customs = append(customs, cus)
						}
					} else if subItem.Type == 3 {
						if len(subItem.GoodInfo.MedicalInsuranceNumber) > 0 && subItem.GoodInfo.IsUser != 1 {
							cnt, _ := strconv.ParseFloat(subItem.Count, 64)

							cus := &models.NewCustom{
								DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*cnt),
								Cut:              fmt.Sprintf("%.4f", cnt),
								FeedetlSn:        subItem.FeedetlSn,
								Price:            fmt.Sprintf("%.4f", float64(subItem.Price)),
								MedListCodg:      subItem.GoodInfo.MedicalInsuranceNumber,
								HospApprFlag:     -1,
								FeeOcurTime:      tm.Format("2006-01-02 15:04:05"),
							}
							customs = append(customs, cus)
						}
					}
				}
			}

		}

		//总页数,向上取整,注意除之前要先转换类型为float64
		pagecount = int(math.Ceil(float64(len(customs)) / float64(pagesize)))
		var ress []*ResultFour
		for curpage = 1; curpage <= pagecount; curpage++ {
			if curpage == 1 {
				start = 1
			} else {
				start = (curpage-1)*pagesize + 1
			}
			stop = curpage * pagesize
			if stop > len(customs) {
				stop = len(customs)
			}

			var result string
			var requestLog string
			if miConfig.MdtrtareaAdmvs == "150499" {
				data := make(map[string]interface{})
				if record.MedType == 14 {
					if record.InsutypeType == "390" {

						data["med_type"] = "9933"

					} else if record.InsutypeType == "310" {

						data["med_type"] = "990502"

					}

				} else if record.MedType == 11 {

					data["med_type"] = strconv.FormatInt(record.MedType, 10)

				}
				data["psn_no"] = record.PsnNo
				data["number"] = record.Number
				data["customs"] = customs[start-1 : stop]
				data["chrg_bchno"] = chrg_bchno
				data["dept"] = strconv.FormatInt(department.ID, 10)
				data["dept_code"] = department.Number
				data["doctor_code"] = strconv.FormatInt(doctor_info.ID, 10)
				data["doctor_name"] = doctor_info.UserName
				data["org_name"] = miConfig.OrgName
				data["opertor"] = roles.UserName
				data["fixmedins_code"] = miConfig.Code
				data["insuplc_admdvs"] = record.InsuplcAdmdvs
				data["mdtrtarea_admvs"] = miConfig.MdtrtareaAdmvs
				data["secret_key"] = miConfig.SecretKey

				var req *http.Request
				bytesData, _ := json.Marshal(data)
				req, _ = http.NewRequest("POST", "http://172.16.13.254:9532/"+"nmyb/2301", bytes.NewReader(bytesData))
				client := &http.Client{}
				resp, _ := client.Do(req)
				defer resp.Body.Close()
				body, ioErr := ioutil.ReadAll(resp.Body)
				if ioErr != nil {
					utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				var respJSON map[string]interface{}
				if err := json.Unmarshal([]byte(body), &respJSON); err != nil {
					utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
				result_byte, _ := json.Marshal(respJSON)
				result = string(result_byte)
			} else {
				result, requestLog = service.ZHGdyb2301(record.PsnNo, record.Number, customs[start-1:stop], chrg_bchno, miConfig.OrgName, roles.UserName, strconv.FormatInt(department.ID, 10), miConfig.Code, department.Number, strconv.FormatInt(roles.AdminUserId, 10), record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, data["med_type"].(string))
				saveLog(result, requestLog, "2301", "上传明细")
			}

			var dat map[string]interface{}
			if err := json.Unmarshal([]byte(result), &dat); err == nil {
				fmt.Println(dat)
			} else {
				fmt.Println(err)
			}
			userJSONBytes, _ := json.Marshal(dat)
			var res ResultFour
			var resFour10265 ResultFour10265
			if miConfig.Code == "H15049901371" {
				if err := json.Unmarshal(userJSONBytes, &resFour10265); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				res.WarnMsg = resFour10265.WarnMsg
				res.Output = resFour10265.Output
				res.ErrMsg = resFour10265.ErrMsg
				res.RespondTime = resFour10265.RespondTime
				res.InfRefmsgid = resFour10265.InfRefmsgid
				Infcode, _ := strconv.ParseInt(resFour10265.Infcode, 10, 64)
				res.Infcode = Infcode

			} else {
				if err := json.Unmarshal(userJSONBytes, &res); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
			}

			if res.Infcode == 0 {
				ress = append(ress, &res)
			} else {
				isSuccess = false
				errlog := &models.HisOrderError{
					UserOrgId:  adminUser.CurrentOrgId,
					Ctime:      time.Now().Unix(),
					Mtime:      time.Now().Unix(),
					Number:     chrg_bchno,
					ErrMsg:     "",
					Status:     1,
					PatientId:  id,
					RecordTime: recordDateTime,
					Stage:      4,
				}
				service.CreateErrMsgLog(errlog)
				c.ServeSuccessJSON(map[string]interface{}{
					"failed_code": -10,
					"msg":         "上传明细错误,请联系his厂商",
				})
				return
			}
		}

		if isSuccess == true {
			if settle_accounts_type == 1 {
				for _, subItem := range ress {
					for _, item := range subItem.Output.Result {
						temp := strings.Split(item.FeedetlSn, "-")
						var advice_id int64 = 0
						var project_id int64 = 0
						var types int64 = 0

						id, _ := strconv.ParseInt(temp[2], 10, 64)
						types, _ = strconv.ParseInt(temp[1], 10, 64)

						if temp[1] == "1" {
							advice_id = id
							project_id = 0
						} else if temp[1] == "2" {
							advice_id = 0
							project_id = id
						}
						info := &models.HisOrderInfo{
							OrderNumber:      record.Number,
							FeedetlSn:        item.FeedetlSn,
							UploadDate:       recordDateTime,
							AdviceId:         advice_id,
							DetItemFeeSumamt: item.DetItemFeeSumamt,
							Cnt:              item.Cnt,
							Pric:             float64(item.Pric),
							PatientId:        record.PatientId,
							PricUplmtAmt:     item.PricUplmtAmt,
							SelfpayProp:      item.SelfpayProp,
							FulamtOwnpayAmt:  item.FulamtOwnpayAmt,
							OverlmtAmt:       item.OverlmtAmt,
							PreselfpayAmt:    item.PreselfpayAmt,
							BasMednFlag:      item.BasMednFlag,
							MedChrgitmType:   item.MedChrgitmType,
							HiNegoDrugFlag:   item.HiNegoDrugFlag,
							Status:           1,
							Memo:             item.Memo,
							Mtime:            time.Now().Unix(),
							InscpScpAmt:      item.InscpScpAmt,
							DrtReimFlag:      item.DrtReimFlag,
							Ctime:            time.Now().Unix(),
							ListSpItemFlag:   item.ListSpItemFlag,
							ChldMedcFlag:     item.ChldMedcFlag,
							LmtUsedFlag:      item.LmtUsedFlag,
							ChrgitmLv:        item.ChrgitmLv,
							UserOrgId:        adminUser.CurrentOrgId,
							HisPatientId:     record.ID,
							OrderId:          0,
							ProjectId:        project_id,
							Type:             types,
							SettleType:       settle_accounts_type,
						}
						service.CreateOrderInfo(info)
					}
				}

				err := service.UpDatePrescriptionOrderStatus(adminUser.CurrentOrgId, ids)
				service.UpDatePrescriptionNumber(adminUser.CurrentOrgId, ids, record.Number)
				service.UpDatePrescriptionInfoNumber(adminUser.CurrentOrgId, patientPrescription.PatientId, record.Number, recordDateTime)
				if err == nil {
					c.ServeSuccessJSON(map[string]interface{}{
						"msg": "上传费用明细成功",
					})
					return
				} else {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
					return
				}

			} else {

				for _, subItem := range ress {
					for _, item := range subItem.Output.Result {
						temp := strings.Split(item.FeedetlSn, "-")
						var advice_id int64 = 0
						var project_id int64 = 0
						var types int64 = 0

						id, _ := strconv.ParseInt(temp[2], 10, 64)
						types, _ = strconv.ParseInt(temp[1], 10, 64)

						if temp[1] == "1" {
							advice_id = id
							project_id = 0
						} else if temp[1] == "2" {
							advice_id = 0
							project_id = id
						}
						info := &models.HisOrderInfo{
							OrderNumber:      record.Number,
							FeedetlSn:        item.FeedetlSn,
							UploadDate:       time.Now().Unix(),
							AdviceId:         advice_id,
							DetItemFeeSumamt: item.DetItemFeeSumamt,
							Cnt:              item.Cnt,
							Pric:             float64(item.Pric),
							PatientId:        record.PatientId,
							PricUplmtAmt:     item.PricUplmtAmt,
							SelfpayProp:      item.SelfpayProp,
							FulamtOwnpayAmt:  item.FulamtOwnpayAmt,
							OverlmtAmt:       item.OverlmtAmt,
							PreselfpayAmt:    item.PreselfpayAmt,
							BasMednFlag:      item.BasMednFlag,
							MedChrgitmType:   item.MedChrgitmType,
							HiNegoDrugFlag:   item.HiNegoDrugFlag,
							Status:           1,
							Memo:             item.Memo,
							Mtime:            time.Now().Unix(),
							InscpScpAmt:      item.InscpScpAmt,
							DrtReimFlag:      item.DrtReimFlag,
							Ctime:            time.Now().Unix(),
							ListSpItemFlag:   item.ListSpItemFlag,
							ChldMedcFlag:     item.ChldMedcFlag,
							LmtUsedFlag:      item.LmtUsedFlag,
							ChrgitmLv:        item.ChrgitmLv,
							UserOrgId:        adminUser.CurrentOrgId,
							HisPatientId:     record.ID,
							ProjectId:        project_id,
							Type:             types,
							SettleType:       settle_accounts_type,
						}
						service.CreateOrderInfo(info)
					}
				}
				service.UpDatePrescriptionOrderStatus(adminUser.CurrentOrgId, ids)
				service.UpDatePrescriptionNumber(adminUser.CurrentOrgId, ids, record.Number)
				service.UpDatePrescriptionInfoNumber(adminUser.CurrentOrgId, patientPrescription.PatientId, record.Number, recordDateTime)
				c.ServeSuccessJSON(map[string]interface{}{
					"msg": "上传费用明细成功",
				})

			}

		}

	}
}
func (c *ZHHisApiController) ZHRefund() {
	order_id, _ := c.GetInt64("order_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	adminUser := c.GetAdminUserInfo()
	var order models.HisOrder
	order, _ = service.GetHisOrderByID(order_id)
	record, _ := service.GetInHospitalRecordByNumber(order.MdtrtId)
	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	if config.IsOpen == 1 { //对接了医保,走医保流程

		var result string
		var requestLog string
		if miConfig.MdtrtareaAdmvs == "150499" {
			//请求内网数据
			api := "http://172.16.13.254:9532/" + "nmyb/2305?mdtrt_id=" + record.Number + "&psn_no=" + record.PsnNo + "&setl_id=" + order.SetlId +
				"&org_name=" + miConfig.OrgName + "&doctor=" + roles.UserName + "&fixmedins_code=" + miConfig.Code +
				"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
			resp, requestErr := http.Get(api)
			if requestErr != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			body, ioErr := ioutil.ReadAll(resp.Body)

			if ioErr != nil {
				utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			var respJSON map[string]interface{}

			if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
				utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
			result_byte, _ := json.Marshal(respJSON)
			result = string(result_byte)
			//saveLog(result, requestLog, "2404", "入院登记撤销")
			saveLog(result, requestLog, "2305", "退费")

		} else {
			result, requestLog := service.Gdyb2305(order.PsnNo, order.MdtrtId, order.SetlId, miConfig.OrgName, roles.UserName, miConfig.SecretKey, miConfig.Code, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs)
			saveLog(result, requestLog, "2305", "退费")

		}

		var dat map[string]interface{}
		if err := json.Unmarshal([]byte(result), &dat); err == nil {
			fmt.Println(dat)
		} else {
			fmt.Println(err)
		}

		userJSONBytes, _ := json.Marshal(dat)

		var res ResultSixteen
		var resSixteen ResultSixteen10265
		if miConfig.Code == "H15049901371" {
			if err := json.Unmarshal(userJSONBytes, &resSixteen); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			res.Cainfo = resSixteen.Cainfo
			res.WarnMsg = resSixteen.WarnMsg
			res.Output = resSixteen.Output
			res.ErrMsg = resSixteen.ErrMsg
			res.RespondTime = resSixteen.RespondTime
			Infcode, _ := strconv.ParseInt(resSixteen.Infcode, 10, 64)
			res.Infcode = Infcode

		} else {

			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

		}

		if res.Infcode == 0 {
			err := service.UpdataOrderStatusThree(order_id, order.Number, adminUser.CurrentOrgId, "", result)
			////不同地区退费流程不一样,肇庆那边退费就包括撤销出院,内蒙古退费不包括撤销明细,所以下面需要根据不同情况进行判断
			//if miConfig.UserOrgId == 10215 {
			//	record.OutHospitalStatus = 0
			//	service.CreateHospitalRecord(&record)
			//}
			service.UpdataOrderStatusByNumber(record.Number)
			if err == nil {
				////当押金不为零时产生退费记录
				if order.Decimal != 0 {
					tmp := strconv.FormatInt(order.ID, 10)
					err = service.MoneyIncrease(adminUser.CurrentOrgId, order.PatientId, tmp, order.Decimal)
					if err != nil {
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
						return
					}
				}

				c.ServeSuccessJSON(map[string]interface{}{
					"msg": "退费成功",
				})
			} else {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"code": -10,
				"msg":  res.ErrMsg,
			})
		}

	} else {
		err := service.UpdataOrderStatus(order_id, order.Number, adminUser.CurrentOrgId, "", "")
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "退费成功",
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	}

}
func (c *ZHHisApiController) ZHRefundDetail() {
	patient_id, _ := c.GetInt64("patient_id")
	his_patient_id, _ := c.GetInt64("his_patient_id")
	record_time := c.GetString("record_time")
	settle_accounts_type, _ := c.GetInt64("settle_accounts_type")
	//order_id, _ := c.GetInt64("order_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminUser := c.GetAdminUserInfo()

	theTimeTwo, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 23:59:59", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTimeTwo := theTimeTwo.Unix()

	//var prescriptions []*models.HisPrescription
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)

	if settle_accounts_type == 1 { //日结
		record, _ := service.GetInHospitalRecord(his_patient_id)
		infos, _ := service.GetZHHisUploadOrderInfo(adminUser.CurrentOrgId, patient_id, recordDateTime, recordDateTimeTwo, record.Number)
		var isSuccess bool = true

		for _, item := range infos {
			var result string
			var requestLog string
			if miConfig.MdtrtareaAdmvs == "150499" {
				//请求内网数据
				api := "http://172.16.13.254:9532/" + "nmyb/2302?psn_no=" + record.PsnNo + "&mdtrtId=" + record.Number + "&feedetl_sn=" + item.FeedetlSn +
					"&org_name=" + miConfig.OrgName + "&doctor=" + roles.UserName + "&fixmedins_code=" + miConfig.Code +
					"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&refund_type=" + "1"
				resp, requestErr := http.Get(api)
				if requestErr != nil {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				body, ioErr := ioutil.ReadAll(resp.Body)
				if ioErr != nil {
					utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				var respJSON map[string]interface{}
				if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
					utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
				result_byte, _ := json.Marshal(respJSON)
				result = string(result_byte)
				saveLog(result, requestLog, "2302", "日结退明细")

			} else {
				result, requestLog := service.Gdyb2302(record.PsnNo, record.Number, miConfig.OrgName, roles.UserName, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, miConfig.Code, item.FeedetlSn, 1)
				saveLog(result, requestLog, "2302", "日结退明细")

			}

			var dat map[string]interface{}
			if err := json.Unmarshal([]byte(result), &dat); err == nil {
				fmt.Println(dat)
			} else {
				fmt.Println(err)
			}
			userJSONBytes, _ := json.Marshal(dat)
			var res2 ResultEmpty
			var resEmpty10265 ResultEmpty10265
			if miConfig.Code == "H15049901371" {
				if err := json.Unmarshal(userJSONBytes, &resEmpty10265); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				Infcode, _ := strconv.ParseInt(resEmpty10265.Infcode, 10, 64)
				res2.Infcode = Infcode
				res2.RespondTime = resEmpty10265.RespondTime
				res2.ErrMsg = resEmpty10265.ErrMsg
				res2.Output = resEmpty10265.Output
				res2.WarnMsg = resEmpty10265.WarnMsg
			} else {
				if err := json.Unmarshal(userJSONBytes, &res2); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
			}

			if res2.Infcode == -1 {
				isSuccess = false
			}
		}
		if isSuccess {
			err := service.UpDateOrderInfoStatus(patient_id, recordDateTime, adminUser.CurrentOrgId, recordDateTimeTwo)

			if err != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			err1 := service.UpDatePrescriptionOrderStatusTwo(patient_id, recordDateTime, adminUser.CurrentOrgId)
			if err1 != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "撤销明细成功",
			})

		}

	} else {
		//prescriptions, _ = service.GetZHMonthHisUploadPrescription(adminUser.CurrentOrgId, patient_id, recordDateTime)
		//var order models.HisOrder
		//order, _ = service.GetHisOrderByID(order_id)
		//record, _ := service.GetInHospitalRecordByNumber(order.MdtrtId)
		var result string
		var requestLog string
		record, _ := service.GetInHospitalRecord(his_patient_id)
		config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
		if config.IsOpen == 1 { //对接了医保,走医保流程

			if miConfig.MdtrtareaAdmvs == "150499" {
				//请求内网数据
				api := "http://172.16.13.254:9532/" + "nmyb/2302?psn_no=" + record.PsnNo + "&mdtrtId=" + record.Number + "&number=0000" +
					"&org_name=" + miConfig.OrgName + "&doctor=" + roles.UserName + "&fixmedins_code=" + miConfig.Code +
					"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&refund_type=" + "1"
				resp, requestErr := http.Get(api)
				if requestErr != nil {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				body, ioErr := ioutil.ReadAll(resp.Body)
				if ioErr != nil {
					utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				var respJSON map[string]interface{}
				if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
					utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
				result_byte, _ := json.Marshal(respJSON)
				result = string(result_byte)
				//saveLog(result, requestLog, "2302", "日结退明细")

			} else {
				result, requestLog = service.Gdyb2302(record.PsnNo, record.Number, miConfig.OrgName, roles.UserName, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, miConfig.Code, "0000", 0)
				saveLog(result, requestLog, "2302", "月结退明细")
			}

			var dat map[string]interface{}
			if err := json.Unmarshal([]byte(result), &dat); err == nil {
				fmt.Println(dat)
			} else {
				fmt.Println(err)
			}

			userJSONBytes, _ := json.Marshal(dat)

			var res2 ResultEmpty
			var resEmpty10265 ResultEmpty10265
			if miConfig.Code == "H15049901371" {
				if err := json.Unmarshal(userJSONBytes, &resEmpty10265); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				Infcode, _ := strconv.ParseInt(resEmpty10265.Infcode, 10, 64)
				res2.Infcode = Infcode
				res2.RespondTime = resEmpty10265.RespondTime
				res2.ErrMsg = resEmpty10265.ErrMsg
				res2.Output = resEmpty10265.Output
				res2.WarnMsg = resEmpty10265.WarnMsg
			} else {
				if err := json.Unmarshal(userJSONBytes, &res2); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
			}

			if res2.Infcode == 0 {
				err := service.UpdataHospitalOrderStatus(record.Number, adminUser.CurrentOrgId)
				if err == nil {
					c.ServeSuccessJSON(map[string]interface{}{
						"msg": "撤销明细成功",
					})
				} else {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
			} else {
				c.ServeSuccessJSON(map[string]interface{}{
					"code": -10,
					"msg":  res2.ErrMsg,
				})
			}
		}
	}

}

func (this *ZHHisApiController) GetZHOutHospitalUnCheck() {
	id, _ := this.GetInt64("id")
	admin_user_id, _ := this.GetInt64("admin_user_id")

	adminInfo := this.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)
	role, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, admin_user_id)

	record, _ := service.GetInHospitalRecord(id)
	if record.ID == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeInHospitalNoExistDataException)
		return
	}

	var result string
	var requestLog string
	if miConfig.MdtrtareaAdmvs == "150499" {
		//请求内网数据
		api := "http://172.16.13.254:9532/" + "nmyb/2405?mdtrt_id=" + record.Number + "&psn_no=" + record.PsnNo +
			"&org_name=" + miConfig.OrgName + "&doctor=" + role.UserName + "&fixmedins_code=" + miConfig.Code +
			"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
		fmt.Println(api)
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		body, ioErr := ioutil.ReadAll(resp.Body)

		if ioErr != nil {
			utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		var respJSON map[string]interface{}

		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		result_byte, _ := json.Marshal(respJSON)
		result = string(result_byte)

	} else {
		result, requestLog = service.ZHGdyb2405(record.Number, record.PsnNo, miConfig.SecretKey, miConfig.OrgName, miConfig.Code, role.UserName, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs)
		saveLog(result, requestLog, "2405", "出院登记撤销")

	}

	var dat map[string]interface{}
	if err := json.Unmarshal([]byte(result), &dat); err == nil {
		fmt.Println(dat)
	} else {
		fmt.Println(err)
	}
	userJSONBytes, _ := json.Marshal(dat)
	var res ResultEmpty
	var resEmpty10265 ResultEmpty10265
	if miConfig.Code == "H15049901371" {
		if err := json.Unmarshal(userJSONBytes, &resEmpty10265); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Infcode, _ := strconv.ParseInt(resEmpty10265.Infcode, 10, 64)
		res.Infcode = Infcode
		res.RespondTime = resEmpty10265.RespondTime
		res.ErrMsg = resEmpty10265.ErrMsg
		res.Output = resEmpty10265.Output
		res.WarnMsg = resEmpty10265.WarnMsg
	} else {
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	}

	if res.Infcode == 0 {
		record.OutHospitalStatus = 0
		service.CreateHospitalRecord(&record)
		service.UpdataOrderStatusByNumber(record.Number)
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "撤销出院成功",
		})

	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         res.ErrMsg,
		})
	}

}
func (this *ZHHisApiController) GetZHInHospitalUnCheck() {
	id, _ := this.GetInt64("id")
	admin_user_id, _ := this.GetInt64("admin_user_id")
	adminInfo := this.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)
	role, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, admin_user_id)
	record, _ := service.GetInHospitalRecord(id)

	if record.ID == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeInHospitalNoExistDataException)
		return
	}

	var result string
	var requestLog string

	if miConfig.MdtrtareaAdmvs == "150499" {
		//请求内网数据
		api := "http://172.16.13.254:9532/" + "nmyb/2302?psn_no=" + record.PsnNo + "&mdtrtId=" + record.Number + "&number=" + "0000" +
			"&org_name=" + miConfig.OrgName + "&doctor=" + role.UserName + "&fixmedins_code=" + miConfig.Code +
			"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&refund_type=0"
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		body, ioErr := ioutil.ReadAll(resp.Body)

		if ioErr != nil {
			utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		var respJSON map[string]interface{}

		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		result_byte, _ := json.Marshal(respJSON)
		result = string(result_byte)
		saveLog(result, requestLog, "2302", "月结退明细")

	} else {
		result, requestLog = service.Gdyb2302(record.PsnNo, record.Number, miConfig.OrgName, role.UserName, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, miConfig.Code, "0000", 0)
		saveLog(result, requestLog, "2302", "月结退明细")

	}

	var dat map[string]interface{}
	if err := json.Unmarshal([]byte(result), &dat); err == nil {
		fmt.Println(dat)
	} else {
		fmt.Println(err)
	}

	userJSONBytes, _ := json.Marshal(dat)

	var res2 ResultEmpty
	var resEmpty10265 ResultEmpty10265
	if miConfig.Code == "H15049901371" {
		if err := json.Unmarshal(userJSONBytes, &resEmpty10265); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Infcode, _ := strconv.ParseInt(resEmpty10265.Infcode, 10, 64)
		res2.Infcode = Infcode
		res2.RespondTime = resEmpty10265.RespondTime
		res2.ErrMsg = resEmpty10265.ErrMsg
		res2.Output = resEmpty10265.Output
		res2.WarnMsg = resEmpty10265.WarnMsg
	} else {
		if err := json.Unmarshal(userJSONBytes, &res2); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	}

	if res2.Infcode == 0 {

		service.UpdataHospitalOrderStatus(record.Number, adminInfo.CurrentOrgId)

		var result string
		var requestLog string
		if miConfig.MdtrtareaAdmvs == "150499" {
			//请求内网数据
			api := "http://172.16.13.254:9532/" + "nmyb/2404?mdtrt_id=" + record.Number + "&psn_no=" + record.PsnNo +
				"&org_name=" + miConfig.OrgName + "&doctor=" + role.UserName + "&fixmedins_code=" + miConfig.Code +
				"&insuplc_admdvs=" + record.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
			resp, requestErr := http.Get(api)
			if requestErr != nil {
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			body, ioErr := ioutil.ReadAll(resp.Body)

			if ioErr != nil {
				utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			var respJSON map[string]interface{}

			if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
				utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
			result_byte, _ := json.Marshal(respJSON)
			result = string(result_byte)

		} else {
			result, requestLog = service.ZHGdyb2404(record.Number, record.PsnNo, miConfig.SecretKey, miConfig.OrgName, miConfig.Code, role.UserName, record.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs)
			saveLog(result, requestLog, "2404", "入院登记撤销")

		}

		var dat map[string]interface{}
		if err := json.Unmarshal([]byte(result), &dat); err == nil {
			fmt.Println(dat)
		} else {
			fmt.Println(err)
		}
		userJSONBytes, _ := json.Marshal(dat)
		var res ResultEmpty
		var resEmpty10265 ResultEmpty10265
		if miConfig.Code == "H15049901371" {
			if err := json.Unmarshal(userJSONBytes, &resEmpty10265); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			Infcode, _ := strconv.ParseInt(resEmpty10265.Infcode, 10, 64)
			res.Infcode = Infcode
			res.RespondTime = resEmpty10265.RespondTime
			res.ErrMsg = resEmpty10265.ErrMsg
			res.Output = resEmpty10265.Output
			res.WarnMsg = resEmpty10265.WarnMsg
		} else {
			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
		}

		if res.Infcode == 0 {
			record.Status = 0
			service.CreateHospitalRecord(&record)

			this.ServeSuccessJSON(map[string]interface{}{
				"msg": "撤销入院成功",
			})

		} else {
			this.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res.ErrMsg,
			})
		}

	} else {
		this.ServeSuccessJSON(map[string]interface{}{
			"code": -10,
			"msg":  res2.ErrMsg,
		})
	}

}

func saveLog(result string, request string, infno string, desc string) {

	org_id, _ := beego.AppConfig.Int64("org_id")
	miConfig, _ := service.FindMedicalInsuranceInfo(org_id)
	dir := miConfig.OrgName + "日志"
	utils.Mkdir(dir)
	month := time.Unix(1557042972, 0).Format("1")
	year := time.Now().Format("2006")
	month = time.Now().Format("01")
	day := time.Now().Format("02")
	hour := time.Now().Format("15")
	min := time.Now().Format("04")
	sec := time.Now().Format("05")

	result_time := year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec

	file := strconv.FormatInt(org_id, 10) + "_" + year + month + day + "_log"
	file_name := file + ".txt"
	file_path := miConfig.OrgName + "日志" + "/" + file_name
	exist, _ := utils.PathExists(file_path)
	if exist { //存在
		fmt.Println("存在")
		f, err := os.OpenFile(file_path, os.O_WRONLY, 0644)
		if err != nil {
			fmt.Println("read fail")
		}
		content := "\r\n" + "\r\n" + "\r\n" + result_time + " " + "【 " + desc + infno + "入参" + " 】:" + "\r\n" + request + "\r\n" + result_time + " " + "【 " + desc + infno + "出参" + " 】:" + "\r\n" + result
		n, _ := f.Seek(0, 2)
		_, err = f.WriteAt([]byte(content), n)

	} else { //不存在
		fmt.Println("文件不存在,创建文件")
		f, err := os.Create(miConfig.OrgName + "日志" + "/" + file_name)
		defer f.Close()
		if err != nil {
		} else {
			_, err = f.Write([]byte("记录日志"))
		}
	}

}

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func ConvertToString(src string, srcCode string, tagCode string) string {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	result := string(cdata)
	return result
}

type ELeData struct {
	Data struct {
		IdNo        string `json:"idNo"`
		IdType      string `json:"idType"`
		UserName    string `json:"userName"`
		EcToken     string `json:"ecToken"`
		InsuOrg     string `json:"insuOrg"`
		Gender      string `json:"gender"`
		Birthday    string `json:"birthday"`
		Nationality string `json:"nationality"`
		Email       string `json:"email"`
		Extra       string `json:"extra"`
	} `json:"data"`
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (c *ZHHisApiController) ReadCard() {
	id_card_type, _ := c.GetInt64("id_card_type")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	roles, _ := service.GetAdminUserInfoByID(c.GetAdminUserInfo().CurrentOrgId, admin_user_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)

	var api string
	api = "http://172.16.13.254:9532/" + "nmyb/readcard?" + "fixmedins_code=" + miConfig.Code + "&secret_key=" + miConfig.SecretKey + "&org_name=" + miConfig.OrgName + "&doctor=" + roles.UserName +
		"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&url=" + miConfig.Url + "&cainfo=" + miConfig.Cainfo + "&id_card_type=" + strconv.FormatInt(id_card_type, 10) + "&operator_id=" + strconv.FormatInt(admin_user_id, 10) + "&operator=" + roles.UserName
	fmt.Println(api)

	resp, requestErr := http.Get(api)
	if requestErr != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	body, ioErr := ioutil.ReadAll(resp.Body)
	if ioErr != nil {
		utils.ErrorLog("接口返回数据读取失败: %v", ioErr)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	var respJSON map[string]interface{}
	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
		utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	var status string
	status = respJSON["data"].(map[string]interface{})["status"].(string)
	card_type := respJSON["data"].(map[string]interface{})["type"].(string)
	//console.log()
	fmt.Println("type===")

	fmt.Println(card_type)

	var token string
	var res ResultTwo           //1101结果
	var res10265 ResultTwo10265 //1101结果
	var card_info string        //卡信息
	var busi_card_info string

	card_info = respJSON["data"].(map[string]interface{})["card_info"].(string)
	busi_card_info = respJSON["data"].(map[string]interface{})["busi_card_info"].(string)

	if status == "0" { //读卡成功
		if card_type == "1" {

			respJSON = respJSON["data"].(map[string]interface{})["result"].(map[string]interface{})
			result, _ := json.Marshal(respJSON)

			if err := json.Unmarshal([]byte(result), &res10265); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			res.ErrMsg = res10265.ErrMsg
			infocode, _ := strconv.ParseInt(res10265.Infcode, 10, 64)
			res.Infcode = infocode
			res.Output = res10265.Output
			res.InfRefmsgid = res10265.InfRefmsgid

		} else {
			//var card_info string //卡信息
			//var busi_card_info string

			token = respJSON["data"].(map[string]interface{})["token"].(string)
			//busi_card_info = respJSON["data"].(map[string]interface{})["busi_card_info"].(string)

			//fmt.Println(card_info)
			//fmt.Println(busi_card_info)

			respJSON = respJSON["data"].(map[string]interface{})["result"].(map[string]interface{})
			result, _ := json.Marshal(respJSON)

			if err := json.Unmarshal([]byte(result), &res10265); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			res.ErrMsg = res10265.ErrMsg
			infocode, _ := strconv.ParseInt(res10265.Infcode, 10, 64)
			res.Infcode = infocode
			res.Output = res10265.Output
			res.InfRefmsgid = res10265.InfRefmsgid

		}

		if res.Infcode == 0 {
			var insutypes []string
			var insutype string
			var is390 int = 0
			var is310 int = 0
			for _, item := range res.Output.Iinfo {
				if (item.Insutype == "390" && item.PsnInsuStas == "1") || (item.Insutype == "310" && item.PsnInsuStas == "1") {
					insutypes = append(insutypes, item.Insutype)
				}
			}
			if len(insutypes) == 1 {
				insutype = insutypes[0]
			} else {
				for _, i := range insutypes {
					if i == "390" {
						is390 = 1
					}

					if i == "310" {
						is310 = 1
					}
				}
			}
			if is390 == 1 {
				insutype = "390"
			}
			if is310 == 1 {
				insutype = "310"
			}
			if len(insutypes) == 0 {
				insutype = "310"
			}

			patient, err := service.GetPatientByIDCard(res.Output.Baseinfo.Certno, c.GetAdminUserInfo().CurrentOrgId)
			if err == gorm.ErrRecordNotFound {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNoPateintException)
				return
			} else if err != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
				return

			} else {

				if card_type == "1" {
					bas := strings.Split(card_info, "|")
					basNumber := bas[2]
					Iinfos, _ := json.Marshal(res.Output.Iinfo)
					Idetinfos, _ := json.Marshal(res.Output.Idetinfo)
					infoStr := string(Iinfos)
					idetinfoStr := string(Idetinfos)
					psn := &models.HisPsn{
						PsnNo:        res.Output.Baseinfo.PsnNo,
						Age:          res.Output.Baseinfo.Age,
						PatientId:    patient.ID,
						Certno:       res.Output.Baseinfo.Certno,
						Brdy:         res.Output.Baseinfo.Brdy,
						Gend:         res.Output.Baseinfo.Gend,
						Naty:         res.Output.Baseinfo.Naty,
						PsnCertType:  res.Output.Baseinfo.PsnCertType,
						PsnName:      res.Output.Baseinfo.PsnName,
						Idetinfo:     idetinfoStr,
						Insuinfo:     infoStr,
						UserOrgId:    c.GetAdminUserInfo().CurrentOrgId,
						CardInfo:     card_info,
						VerifyNumber: busi_card_info,
					}
					service.CreateHisPsn(psn)
					c.ServeSuccessJSON(map[string]interface{}{
						"patient":  patient,
						"number":   basNumber,
						"info":     res,
						"insutype": insutype,
					})
				} else {
					Iinfos, _ := json.Marshal(res.Output.Iinfo)
					Idetinfos, _ := json.Marshal(res.Output.Idetinfo)
					infoStr := string(Iinfos)
					idetinfoStr := string(Idetinfos)
					psn := &models.HisPsn{
						PsnNo:        res.Output.Baseinfo.PsnNo,
						Age:          res.Output.Baseinfo.Age,
						PatientId:    patient.ID,
						Certno:       res.Output.Baseinfo.Certno,
						Brdy:         res.Output.Baseinfo.Brdy,
						Gend:         res.Output.Baseinfo.Gend,
						Naty:         res.Output.Baseinfo.Naty,
						PsnCertType:  res.Output.Baseinfo.PsnCertType,
						PsnName:      res.Output.Baseinfo.PsnName,
						Idetinfo:     idetinfoStr,
						Insuinfo:     infoStr,
						UserOrgId:    c.GetAdminUserInfo().CurrentOrgId,
						CardInfo:     card_info,
						VerifyNumber: token,
					}
					service.CreateHisPsn(psn)
					c.ServeSuccessJSON(map[string]interface{}{
						"patient":  patient,
						"number":   token,
						"info":     res,
						"insutype": insutype,
					})
				}
			}
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisFailedException)
			return
		}
	} else { //读卡失败
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisFailedException)
		return

	}
}

var initFlag int64 = 0

func (c *ZHHisApiController) TestGetBasBaseInit() {
	DllDef := syscall.MustLoadDLL("HeaSecReadInfo.dll")
	Iinit := DllDef.MustFindProc("Init")
	//miConfig, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)
	str := make([]byte, 2048)
	inputData := make(map[string]interface{})
	inputData["IP"] = "10.144.211.75"
	inputData["PORT"] = 7021
	inputData["TIMEOUT"] = 180
	inputData["LOG_PATH"] = "C:\\log\\"
	//inputData["SFZ_DRIVER_TYPE"] = 0
	inputData["URL"] = "/call1"

	bytesData, _ := json.Marshal(inputData)
	fmt.Println(inputData)
	fmt.Println(bytesData)

	ret, _, err := Iinit.Call((uintptr)(unsafe.Pointer(&bytesData[0])), (uintptr)(unsafe.Pointer(&str[0])))
	if ret != 0 {
		fmt.Println("SSCard的报错原因:", err)
		fmt.Println("SSCard的运算结果为:", ret)
		fmt.Println("SSCard的返回结果为:", string(str))
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
		return
	}
	fmt.Println("SSCard的返回结果为:", string(str))

	result := int(ret)
	fmt.Println("SSCard的运算结果为1:", result)
	//initFlag = 1
	return
}

func (c *ZHHisApiController) GetSFZBaseInfo() string {
	DllDef := syscall.MustLoadDLL("SSCard.dll")
	readCard := DllDef.MustFindProc("ReadSFZ")
	if readCard == nil {
		fmt.Println("readcard is nil")
		readCard = DllDef.MustFindProc("ReadSFZ")
	}

	str := make([]byte, 256)
	str1 := make([]byte, 256)
	r, _, _ := readCard.Call((uintptr)(unsafe.Pointer(&str[0])), IntPtr(1024), (uintptr)(unsafe.Pointer(&str1[0])), IntPtr(1024))

	fmt.Println(r)
	return string(str)
}

func (c *ZHHisApiController) GetBasBaseInfo(fixmedins_code string, mdtrtarea_admvs string, opter_name string, opter_id string, fixmedins_name string) string {
	DllDef := syscall.MustLoadDLL("HeaSecReadInfo.dll")
	readCard := DllDef.MustFindProc("ReadCardBas")
	fmt.Println(readCard)
	fmt.Println("!!!!!")

	month := time.Unix(1557042972, 0).Format("1")
	year := time.Now().Format("2006")
	month = time.Now().Format("01")
	day := time.Now().Format("02")

	hour := time.Now().Format("15")
	min := time.Now().Format("04")
	sec := time.Now().Format("05")

	msec := time.Now().Format("000")
	timestamp := time.Now().Unix()

	tempTime := time.Unix(timestamp, 0)
	//timeFormat := tempTime.Format("20060102150405")
	timeFormatOne := tempTime.Format("2006-01-02 15:04:05")
	//randNum := rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000)

	inputData := make(map[string]interface{})
	inputData["infno"] = "1199"
	//inputData["msgid"] = "7021"
	inputData["msgid"] = fixmedins_code + year + month + day + hour + min + sec + msec + "0" // 发送方报文 ID
	inputData["mdtrtarea_admvs"] = mdtrtarea_admvs                                           // 发送方报文 ID
	inputData["recer_sys_code"] = "01"
	inputData["infver"] = "V1.0"
	inputData["opter_type"] = "1"
	inputData["opter"] = opter_id
	inputData["opter_name"] = opter_name
	inputData["inf_time"] = timeFormatOne
	inputData["fixmedins_code"] = fixmedins_code
	inputData["fixmedins_name"] = fixmedins_name

	inputData["dev_no"] = ""
	inputData["dev_safe_info"] = ""
	inputData["cainfo"] = ""
	inputData["signtype"] = ""
	inputData["sign_no"] = ""

	bytesData, _ := json.Marshal(inputData)
	fmt.Println(string(bytesData))
	pBusiCardInfo := make([]byte, 8192)
	ret2, _, _ := readCard.Call((uintptr)(unsafe.Pointer(&bytesData[0])), (uintptr)(unsafe.Pointer(&pBusiCardInfo[0])))
	fmt.Println(ret2)
	fmt.Println(DeleteExtraSpace(string(pBusiCardInfo)))
	fmt.Println(":", ConvertToString(DeleteExtraSpace(string(pBusiCardInfo)), "gbk", "utf-8"))
	if ret2 != 0 {
		return ""
	}
	return DeleteExtraSpace(string(pBusiCardInfo))
}

func DeleteExtraSpace(s string) string {
	//删除字符串中的多余空格,有多个空格时,仅保留一个空格
	s1 := strings.Replace(s, "  ", " ", -1)      //替换tab为空格
	regstr := "\\s{2,}"                          //两个及两个以上空格的正则表达式
	reg, _ := regexp.Compile(regstr)             //编译正则表达式
	s2 := make([]byte, len(s1))                  //定义字符数组切片
	copy(s2, s1)                                 //将字符串复制到切片
	spc_index := reg.FindStringIndex(string(s2)) //在字符串中搜索
	for len(spc_index) > 0 {                     //找到适配项
		s2 = append(s2[:spc_index[0]+1], s2[spc_index[1]:]...) //删除多余空格
		spc_index = reg.FindStringIndex(string(s2))            //继续在字符串中搜索
	}
	return string(s2)
}

func (c *ZHHisApiController) GetELeInfo(code string, operator_id string, operator_name string) (string, string) {
	DllDef := syscall.MustLoadDLL("NationECCode.dll")
	readCard := DllDef.MustFindProc("NationEcTrans")
	fmt.Println(readCard)
	fmt.Println("!!!!!")
	pBusiCardInfo := make([]byte, 8192)
	input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputData["orgId"] = code
	inputData["businessType"] = "01101"
	inputData["operatorId"] = operator_id
	inputData["operatorName"] = operator_name
	inputData["officeId"] = "001"
	inputData["officeName"] = "血透室"
	inputData["deviceType"] = ""
	input["data"] = inputData
	input["orgId"] = code
	input["transType"] = "ec.query"

	bytesData, _ := json.Marshal(input)
	gdyb_url := beego.AppConfig.String("gdyb_url")

	url := gdyb_url + "/localcfc/api/hsecfc/localQrCodeQuery"
	ret2, _, _ := readCard.Call(StrPtr(url), StrPtr(string(bytesData)), (uintptr)(unsafe.Pointer(&pBusiCardInfo[0])))
	fmt.Println(ret2)
	fmt.Println(DeleteExtraSpace(string(pBusiCardInfo)))
	fmt.Println(":", ConvertToString(DeleteExtraSpace(string(pBusiCardInfo)), "gbk", "utf-8"))
	if ret2 != 0 {
		return "", ""
	}
	return DeleteExtraSpace(""), DeleteExtraSpace(string(pBusiCardInfo))
}

func StrPtr(s string) uintptr {
	return uintptr(unsafe.Pointer(syscall.StringBytePtr(s)))
}

func Remove0000(s string) string {
	str := make([]rune, 0, len(s))
	for _, v := range []rune(s) {
		if v == 0 {
			continue
		}
		str = append(str, v)
	}
	return string(str)
}

func IntPtr(n int) uintptr {
	return uintptr(n)
}