package sg

import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"gdyb/controllers"
	"gdyb/enums"
	"gdyb/models"
	"gdyb/service"
	"gdyb/utils"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"github.com/shopspring/decimal"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"
	"unsafe"
)

type HisApiController struct {
	controllers.BaseAuthAPIController
}

func HisManagerApiRegistRouters() {
	beego.Router("/api/register/get", &HisApiController{}, "get:GetRegisterInfo")
	beego.Router("/api/diag/upload", &HisApiController{}, "get:GetUploadDiag")
	beego.Router("/api/upload/get", &HisApiController{}, "get:GetUploadInfo")
	beego.Router("/api/settle/query", &HisApiController{}, "get:GetSettleAccounts")
	beego.Router("/api/checkaccount/get", &HisApiController{}, "get:GetCheckAccount")
	beego.Router("/api/checkdetailaccount/get", &HisApiController{}, "get:GetCheckDetailAccount")
	beego.Router("/api/refund/post", &HisApiController{}, "get:Refund")
	beego.Router("/api/sscard", &HisApiController{}, "get:Sscard")
	beego.Router("/api/refundnumber/post", &HisApiController{}, "get:RefundNumber")
	beego.Router("/api/refunddetail/post", &HisApiController{}, "get:RefundDetail")
	beego.Router("/api/treatment/check", &HisApiController{}, "get:CheckTreatment")
	beego.Router("/api/record/put", &HisApiController{}, "get:PutRecord")
	//beego.Router("/api/patient/info", &HisApiController{}, "get:GetHisPatientInfo")
	beego.Router("/api/org/info", &HisApiController{}, "get:GetOrgInfo")
	//beego.Router("/api/testcard", &HisApiController{}, "get:TestGetBasBaseInfo")

	//beego.Router("/api/testpay", &HisApiController{}, "get:TestPay")

	beego.Router("/api/pre_upload/get", &HisApiController{}, "get:GetPreUploadInfo")

	//beego.Router("/api/settle/get", &HisApiController{}, "get:GetSettleInfo")

	beego.Router("/api/310", &HisApiController{}, "get:Check310")
	beego.Router("/api/390", &HisApiController{}, "get:Check390")

	beego.Router("/api/patient/info", &HisApiController{}, "get:GetPatientInfo")

	//备案撤销相关接口
	beego.Router("/api/checkcode/get", &HisApiController{}, "get:GetCheckCode")
	beego.Router("/api/uncheckcode/get", &HisApiController{}, "get:UnCheckCode")
	beego.Router("/api/psn/putonrecord", &HisApiController{}, "get:PsnPutOnRecord")
	beego.Router("/api/psn/unputonrecord", &HisApiController{}, "get:PsnUnPutOnRecord")
	beego.Router("/api/psn/ncds/putonrecord", &HisApiController{}, "get:PsnPutNCDSOnRecord")
	beego.Router("/api/psn/ncds/unputonrecord", &HisApiController{}, "get:PsnPutUnNCDSOnRecord")
	beego.Router("/api/test", &HisApiController{}, "get:TestGetBasBaseInfo")
	beego.Router("/api/reversal", &HisApiController{}, "get:ReversalData")
	beego.Router("/api/reversal/other", &HisApiController{}, "get:ReversalOtherData")

	//beego.Router("/api/reversal/one", &HisApiController{}, "get:ReversalOtherOneData")

	beego.Router("/api/settlelist/get", &HisApiController{}, "get:GetSettleList")

	//beego.Router("/api/settlelist/get", &HisApiController{}, "get:GetSettleList")

}

type CustomFundPay struct {
	FundPayType string  `json:"fund_pay_type"`
	FundPayamt  float64 `json:"fund_payamt"`
}

func (c *HisApiController) GetSettleList() {

	order_id, _ := c.GetInt64("order_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	order, _ := service.GetHisOrderByIDTwo(order_id)
	roles, _ := service.GetDoctorListTwo(c.GetAdminUserInfo().CurrentOrgId)
	his, _ := service.GetHisPatientByNumber(order.MdtrtId)
	admin, _ := service.GetAdminUserByUserID(roles[0].AdminUserId)
	curRoles, _ := service.GetAdminUserInfoByID(c.GetAdminUserInfo().CurrentOrgId, admin_user_id)
	depart, _ := service.GetDepartMentDetail(curRoles.DepartmentId)
	miConfig, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)

	if order.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisOrderNoExistParamWrong)
		return
	}
	struct4101 := service.Struct4101{
		PsnNo:          order.PsnNo,
		MdtrtId:        order.MdtrtId,
		SetlId:         order.SetlId,
		PsnName:        order.PsnName,
		Gend:           order.Gend,
		Brdy:           his.Brdy,
		Age:            his.Age,
		Naty:           order.Naty,
		PatnCertType:   "01",
		Certno:         order.Certno,
		Prfs:           "90",
		ConerName:      roles[0].UserName,
		PatnRlts:       "99",
		ConerAddr:      miConfig.OrgName,
		ConerTel:       admin.Mobile,
		HiType:         order.Insutype,
		Insuplc:        miConfig.InsuplcAdmdvs,
		MaindiagFlag:   "1",
		BillCode:       order.FaPiaoCode,
		BillNo:         order.FaPiaoNumber,
		BizSn:          order.Number,
		PsnSelfPay:     order.PsnPartAmt,
		PsnOwnPay:      order.PsnPartAmt,
		AcctPay:        order.AcctPay,
		PsnCashpay:     order.PsnCashPay,
		HiPaymtd:       "1",
		Hsorg:          miConfig.InsuplcAdmdvs,
		HsorgOpter:     miConfig.InsuplcAdmdvs,
		MedinsFillPsn:  curRoles.UserName,
		MedinsFillDept: depart.Name,
		IptMedType:     "2",
	}
	if order.SettleType == 1 {
		t := time.Unix(int64(order.SettleAccountsDate), 0)
		dateStr := t.Format("2006-01-02")
		struct4101.SetlBegnDate = dateStr
		struct4101.SetlEndDate = dateStr
	} else {
		t := time.Unix(int64(order.SettleStartTime), 0)
		t2 := time.Unix(int64(order.SettleEndTime), 0)
		dateStartStr := t.Format("2006-01-02")
		dateEndStr := t2.Format("2006-01-02")
		struct4101.SetlBegnDate = dateStartStr
		struct4101.SetlEndDate = dateEndStr
	}

	var rf []CustomFundPay
	json.Unmarshal([]byte(order.SetlDetail), &rf)

	var tempFunPays []service.CustomStruct
	for _, item := range rf {
		var tempFunPay service.CustomStruct
		tempFunPay.FundPayamt = item.FundPayamt
		tempFunPay.FundPayType = item.FundPayType
		tempFunPays = append(tempFunPays, tempFunPay)
	}
	struct4101.CustomStruct = tempFunPays

	var tempOpspdiseinfos []service.OpspdiseinfoStruct
	var tempOpspdiseinfo service.OpspdiseinfoStruct
	var tempOpspdiseinfo2 service.OpspdiseinfoStruct
	sickConfig, _ := service.FindDiagnoseById(his.Diagnosis)
	sickConfigTwo, _ := service.FindSickById(his.SickType)
	tempOpspdiseinfo.DiagCode = sickConfig.CountryCode
	tempOpspdiseinfo.DiagName = sickConfig.CountryContentName
	tempOpspdiseinfo.MaindiagFlag = "1"
	tempOpspdiseinfo.OprnOprtCode = ""
	tempOpspdiseinfo.OprnOprtName = ""

	tempOpspdiseinfos = append(tempOpspdiseinfos, tempOpspdiseinfo)
	tempOpspdiseinfo2.DiagCode = sickConfigTwo.CountryCode
	tempOpspdiseinfo2.DiagName = sickConfigTwo.CountryContentName
	tempOpspdiseinfo2.MaindiagFlag = "2"
	tempOpspdiseinfo2.OprnOprtCode = ""
	tempOpspdiseinfo2.OprnOprtName = ""
	tempOpspdiseinfos = append(tempOpspdiseinfos, tempOpspdiseinfo2)
	struct4101.OpspdiseinfoStruct = tempOpspdiseinfos

	var iteminfo service.IteminfoStruct

	var bedCostTotal float64 = 0         //床位总费
	var bedCostSelfTotal float64 = 0     //床位自费
	var bedCostPartSelfTotal float64 = 0 //床位部分项目自费

	var operationCostTotal float64 = 0         //手术费
	var operationCostSelfTotal float64 = 0     //手术费
	var operationCostPartSelfTotal float64 = 0 //手术费

	var otherCostTotal float64 = 0         //其他费用
	var otherCostSelfTotal float64 = 0     //其他费用
	var otherCostPartSelfTotal float64 = 0 //其他费用

	var materialCostTotal float64 = 0         //材料费
	var materialCostSelfTotal float64 = 0     //材料费
	var materialCostPartSelfTotal float64 = 0 //材料费

	var westernMedicineCostTotal float64 = 0         //西药费
	var westernMedicineCostSelfTotal float64 = 0     //西药费
	var westernMedicineCostPartSelfTotal float64 = 0 //西药费

	var chineseTraditionalMedicineCostTotal float64 = 0         //中成药
	var chineseTraditionalMedicineCostSelfTotal float64 = 0     //中成药
	var chineseTraditionalMedicineCostPartSelfTotal float64 = 0 //中成药

	var checkCostTotal float64 = 0         //检查费
	var checkCostSelfTotal float64 = 0     //检查费
	var checkCostPartSelfTotal float64 = 0 //检查费

	var laboratoryCostTotal float64 = 0         //化验费
	var laboratoryCostSelfTotal float64 = 0     //化验费
	var laboratoryCostPartSelfTotal float64 = 0 //化验费

	var treatCostTotal float64 = 0         //治疗费用
	var treatCostSelfTotal float64 = 0     //治疗费用
	var treatCostPartSelfTotal float64 = 0 //治疗费用

	decimal.DivisionPrecision = 2

	var bed_fulamt_ownpay_amt float64 = 0
	var operation_fulamt_ownpay_amt float64 = 0
	var other_fulamt_ownpay_amt float64 = 0
	var westernMedicine_fulamt_ownpay_amt float64 = 0
	var chineseTraditional_fulamt_ownpay_amt float64 = 0
	var check_fulamt_ownpay_amt float64 = 0
	var material_fulamt_ownpay_amt float64 = 0
	var laboratory_fulamt_ownpay_amt float64 = 0
	var treat_fulamt_ownpay_amt float64 = 0

	var bed_claa_sunmfee float64 = 0
	var bed_clab_amt float64 = 0
	var bed_other_amt float64 = 0

	var operation_claa_sunmfee float64 = 0
	var operation_clab_amt float64 = 0
	var operation_other_amt float64 = 0

	var other_claa_sunmfee float64 = 0
	var other_clab_amt float64 = 0
	var other_other_amt float64 = 0

	var westernMedicine_claa_sunmfee float64 = 0
	var westernMedicine_clab_amt float64 = 0
	var westernMedicine_other_amt float64 = 0

	var chineseTraditional_claa_sunmfee float64 = 0
	var chineseTraditional_clab_amt float64 = 0
	var chineseTraditional_other_amt float64 = 0

	var check_claa_sunmfee float64 = 0
	var check_clab_amt float64 = 0
	var check_other_amt float64 = 0

	var material_claa_sunmfee float64 = 0
	var material_clab_amt float64 = 0
	var material_other_amt float64 = 0

	var laboratory_claa_sunmfee float64 = 0
	var laboratory_clab_amt float64 = 0
	var laboratory_other_amt float64 = 0

	var treat_claa_sunmfee float64 = 0
	var treat_clab_amt float64 = 0
	var treat_other_amt float64 = 0

	for _, item := range order.HisOrderInfo {
		if item.MedChrgitmType == "01" { //床位费
			bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			bedCostSelfTotal, _ = decimal.NewFromFloat(bedCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			bedCostPartSelfTotal, _ = decimal.NewFromFloat(bedCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			bed_fulamt_ownpay_amt, _ = decimal.NewFromFloat(bed_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {
				bed_claa_sunmfee, _ = decimal.NewFromFloat(bed_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			}
			if item.ChrgitmLv == "2" {
				bed_clab_amt, _ = decimal.NewFromFloat(bed_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				bed_other_amt, _ = decimal.NewFromFloat(bed_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}

		}

		if item.MedChrgitmType == "03" { //检查费
			checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			checkCostSelfTotal, _ = decimal.NewFromFloat(checkCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			checkCostPartSelfTotal, _ = decimal.NewFromFloat(checkCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			check_fulamt_ownpay_amt, _ = decimal.NewFromFloat(check_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {

				check_claa_sunmfee, _ = decimal.NewFromFloat(check_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				check_clab_amt, _ = decimal.NewFromFloat(check_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				check_other_amt, _ = decimal.NewFromFloat(check_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

		if item.MedChrgitmType == "04" { //化验费
			laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			laboratoryCostSelfTotal, _ = decimal.NewFromFloat(laboratoryCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			laboratoryCostPartSelfTotal, _ = decimal.NewFromFloat(laboratoryCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			laboratory_fulamt_ownpay_amt, _ = decimal.NewFromFloat(laboratory_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {

				laboratory_claa_sunmfee, _ = decimal.NewFromFloat(laboratory_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				laboratory_clab_amt, _ = decimal.NewFromFloat(laboratory_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				laboratory_other_amt, _ = decimal.NewFromFloat(laboratory_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

		if item.MedChrgitmType == "05" { //治疗费
			treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			treatCostSelfTotal, _ = decimal.NewFromFloat(treatCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			treatCostPartSelfTotal, _ = decimal.NewFromFloat(treatCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			treat_fulamt_ownpay_amt, _ = decimal.NewFromFloat(treat_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {

				treat_claa_sunmfee, _ = decimal.NewFromFloat(treat_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				treat_clab_amt, _ = decimal.NewFromFloat(treat_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				treat_other_amt, _ = decimal.NewFromFloat(treat_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

		if item.MedChrgitmType == "06" { //手术费
			operationCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			operationCostSelfTotal, _ = decimal.NewFromFloat(operationCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			operationCostPartSelfTotal, _ = decimal.NewFromFloat(operationCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			operation_fulamt_ownpay_amt, _ = decimal.NewFromFloat(operation_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()

			if item.ChrgitmLv == "1" {

				operation_claa_sunmfee, _ = decimal.NewFromFloat(operation_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				operation_clab_amt, _ = decimal.NewFromFloat(operation_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				operation_other_amt, _ = decimal.NewFromFloat(operation_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

		if item.MedChrgitmType == "08" { //材料费
			materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			materialCostSelfTotal, _ = decimal.NewFromFloat(materialCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			materialCostPartSelfTotal, _ = decimal.NewFromFloat(materialCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			material_fulamt_ownpay_amt, _ = decimal.NewFromFloat(material_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {

				material_claa_sunmfee, _ = decimal.NewFromFloat(material_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				material_clab_amt, _ = decimal.NewFromFloat(material_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				material_other_amt, _ = decimal.NewFromFloat(material_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

		if item.MedChrgitmType == "09" { //西药费
			westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			westernMedicineCostSelfTotal, _ = decimal.NewFromFloat(westernMedicineCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			westernMedicineCostPartSelfTotal, _ = decimal.NewFromFloat(westernMedicineCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			westernMedicine_fulamt_ownpay_amt, _ = decimal.NewFromFloat(westernMedicine_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {

				westernMedicine_claa_sunmfee, _ = decimal.NewFromFloat(westernMedicine_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				westernMedicine_clab_amt, _ = decimal.NewFromFloat(westernMedicine_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				westernMedicine_other_amt, _ = decimal.NewFromFloat(westernMedicine_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

		if item.MedChrgitmType == "11" { //中成费
			chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			chineseTraditionalMedicineCostSelfTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			chineseTraditionalMedicineCostPartSelfTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			chineseTraditional_fulamt_ownpay_amt, _ = decimal.NewFromFloat(chineseTraditional_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {

				chineseTraditional_claa_sunmfee, _ = decimal.NewFromFloat(chineseTraditional_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				chineseTraditional_clab_amt, _ = decimal.NewFromFloat(chineseTraditional_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				chineseTraditional_other_amt, _ = decimal.NewFromFloat(chineseTraditional_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

		if item.MedChrgitmType == "14" { //其他费
			otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			otherCostSelfTotal, _ = decimal.NewFromFloat(otherCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			otherCostPartSelfTotal, _ = decimal.NewFromFloat(otherCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
			other_fulamt_ownpay_amt, _ = decimal.NewFromFloat(other_fulamt_ownpay_amt).Add(decimal.NewFromFloat(item.FulamtOwnpayAmt)).Float64()
			if item.ChrgitmLv == "1" {
				other_claa_sunmfee, _ = decimal.NewFromFloat(other_claa_sunmfee).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()

			}
			if item.ChrgitmLv == "2" {
				other_clab_amt, _ = decimal.NewFromFloat(other_clab_amt).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()

			}
			if item.ChrgitmLv == "3" {
				other_other_amt, _ = decimal.NewFromFloat(other_other_amt).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			}
		}

	}

	var iteminfoStructs []service.IteminfoStruct

	if bedCostTotal != 0 {
		iteminfo.MedChrgitm = "01"
		iteminfo.FulamtOwnpayAmt = bed_fulamt_ownpay_amt
		iteminfo.Amt = bedCostTotal
		iteminfo.ClaaSumfee = bed_claa_sunmfee
		iteminfo.ClabAmt = bed_clab_amt
		iteminfo.OthAmt = bed_other_amt
		iteminfoStructs = append(iteminfoStructs, iteminfo)
	}

	if checkCostTotal != 0 {
		iteminfo.MedChrgitm = "03"
		iteminfo.FulamtOwnpayAmt = check_fulamt_ownpay_amt
		iteminfo.Amt = checkCostTotal
		iteminfo.ClaaSumfee = check_claa_sunmfee
		iteminfo.ClabAmt = check_clab_amt
		iteminfo.OthAmt = check_other_amt
		iteminfoStructs = append(iteminfoStructs, iteminfo)

	}

	if laboratoryCostTotal != 0 {
		iteminfo.MedChrgitm = "04"
		iteminfo.FulamtOwnpayAmt = laboratory_fulamt_ownpay_amt
		iteminfo.Amt = laboratoryCostTotal
		iteminfo.ClaaSumfee = laboratory_claa_sunmfee
		iteminfo.ClabAmt = laboratory_clab_amt
		iteminfo.OthAmt = laboratory_other_amt
		iteminfoStructs = append(iteminfoStructs, iteminfo)

		//struct4101.IteminfoStruct = append(struct4101.IteminfoStruct, iteminfo)

	}

	if treatCostTotal != 0 {
		iteminfo.MedChrgitm = "05"
		iteminfo.FulamtOwnpayAmt = treat_fulamt_ownpay_amt
		iteminfo.Amt = treatCostTotal
		iteminfo.ClaaSumfee = treat_claa_sunmfee
		iteminfo.ClabAmt = treat_clab_amt
		iteminfo.OthAmt = treat_other_amt
		iteminfoStructs = append(iteminfoStructs, iteminfo)

		// (struct4101.IteminfoStruct, iteminfo)

		//struct4101.IteminfoStruct = append(struct4101.IteminfoStruct, iteminfo)

	}

	if operationCostTotal != 0 {
		iteminfo.MedChrgitm = "06"
		iteminfo.FulamtOwnpayAmt = bed_fulamt_ownpay_amt
		iteminfo.Amt = operationCostTotal
		iteminfo.ClaaSumfee = operation_claa_sunmfee
		iteminfo.ClabAmt = operation_clab_amt
		iteminfo.OthAmt = operation_other_amt
		//struct4101.IteminfoStruct = append(struct4101.IteminfoStruct, iteminfo)
		iteminfoStructs = append(iteminfoStructs, iteminfo)

	}

	if materialCostTotal != 0 {
		iteminfo.MedChrgitm = "08"
		iteminfo.FulamtOwnpayAmt = material_fulamt_ownpay_amt
		iteminfo.Amt = materialCostTotal
		iteminfo.ClaaSumfee = material_claa_sunmfee
		iteminfo.ClabAmt = material_clab_amt
		iteminfo.OthAmt = material_other_amt
		//struct4101.IteminfoStruct = append(struct4101.IteminfoStruct, iteminfo)
		iteminfoStructs = append(iteminfoStructs, iteminfo)

	}
	if westernMedicineCostTotal != 0 {
		iteminfo.MedChrgitm = "09"
		iteminfo.FulamtOwnpayAmt = westernMedicine_fulamt_ownpay_amt
		iteminfo.Amt = westernMedicineCostTotal
		iteminfo.ClaaSumfee = westernMedicine_claa_sunmfee
		iteminfo.ClabAmt = westernMedicine_clab_amt
		iteminfo.OthAmt = westernMedicine_other_amt
		//struct4101.IteminfoStruct = append(struct4101.IteminfoStruct, iteminfo)
		iteminfoStructs = append(iteminfoStructs, iteminfo)

	}
	if chineseTraditionalMedicineCostTotal != 0 {
		iteminfo.MedChrgitm = "11"
		iteminfo.FulamtOwnpayAmt = westernMedicine_fulamt_ownpay_amt
		iteminfo.Amt = westernMedicineCostTotal
		iteminfo.ClaaSumfee = westernMedicine_claa_sunmfee
		iteminfo.ClabAmt = westernMedicine_clab_amt
		iteminfo.OthAmt = westernMedicine_other_amt
		//struct4101.IteminfoStruct = append(struct4101.IteminfoStruct, iteminfo)
		iteminfoStructs = append(iteminfoStructs, iteminfo)

	}
	if otherCostTotal != 0 {
		iteminfo.MedChrgitm = "14"
		iteminfo.FulamtOwnpayAmt = other_fulamt_ownpay_amt
		iteminfo.Amt = otherCostTotal
		iteminfo.ClaaSumfee = other_claa_sunmfee
		iteminfo.ClabAmt = other_clab_amt
		iteminfo.OthAmt = other_other_amt
		//struct4101.IteminfoStruct = append(struct4101.IteminfoStruct, iteminfo)
		iteminfoStructs = append(iteminfoStructs, iteminfo)

	}
	struct4101.IteminfoStruct = iteminfoStructs
	struct4101.Ntly = "中国"
	struct4101.AdmCaty = "A03.06"
	result := service.Gdyb4101(struct4101, miConfig.SecretKey, miConfig.OrgName, curRoles.UserName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs)
	fmt.Println(result)

	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 ResultSeventeen
	if err := json.Unmarshal(userJSONBytes, &res); err != nil {
		utils.ErrorLog("解析失败:%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

	if res.Infcode != 0 {
		c.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         res.ErrMsg,
		})
		return
	} else {
		hisFundSettleListResult := &models.HisFundSettleListResult{
			Number:    res.Output.SetlListId,
			Status:    1,
			Ctime:     time.Now().Unix(),
			Mtime:     time.Now().Unix(),
			UserOrgId: c.GetAdminUserInfo().CurrentOrgId,
			IsUpload:  1,
			OrderId:   order_id,
		}
		service.CreateUploadRecord(hisFundSettleListResult)
		c.ServeSuccessJSON(map[string]interface{}{
			"msg":    "上传成功",
			"result": hisFundSettleListResult,
		})
		return
	}
}

func (c *HisApiController) TestGetBasBaseInfo() {
	DllDef := syscall.MustLoadDLL("SSCard.dll")
	Iinit := DllDef.MustFindProc("Init")
	readCard := DllDef.MustFindProc("ReadCardBas")
	ret, _, err := Iinit.Call(StrPtr("http://igb.hsa.gdgov.cn/gdyb_inf/poc/api/card/initDll"), StrPtr("440200"))
	if ret != 0 {
		fmt.Println("SSCard的报错原因:", err)
		fmt.Println("SSCard的运算结果为:", ret)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
		return
	}

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

	if readCard == nil {
		fmt.Println("readcard is nil")
		readCard = DllDef.MustFindProc("ReadCardBas")
	}
	if readCard == nil {
		fmt.Println("readcard reload  is nil")
		return
	}

	str := make([]byte, 1024)
	str1 := make([]byte, 1024)
	cdat := len(str)
	cdat1 := len(str1)
	p := *((*int32)(unsafe.Pointer(&str[0])))
	p1 := *((*int32)(unsafe.Pointer(&str1[0])))
	ret2, _, err2 := readCard.Call(uintptr(p), uintptr(cdat), uintptr(p1), uintptr(cdat1))
	fmt.Println(" Add(4,5)的结果为:", ret2)
	str11 := prttostr(uintptr(p))
	str22 := prttostr(uintptr(p1))

	fmt.Println(" str:", str11)
	fmt.Println(" str1:", str22)
	// runtime.GC()
	if err2 != nil {
		fmt.Println("SSCard的运算结果为:", ret2)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
		return
	}

}

func prttostr(vcode uintptr) string {
	var vbyte []byte
	for i := 0; i < 10; i++ {
		sbyte := *((*byte)(unsafe.Pointer(vcode)))
		if sbyte == 0 {
			break
		}
		vbyte = append(vbyte, sbyte)
		vcode += 1
	}
	return string(vbyte)
}

//func (c *HisApiController) TestPay() {
//	DllDef2 := syscall.MustLoadDLL("SSSE32.dll")
//	readCards := DllDef2.MustFindProc("BankTrans")
//	inputData := make(map[string]interface{})
//	inputData["transId"] = "05"
//	inputData["amount"] = "0.01"
//	inputData["traceNo"] = "20210227093601325405377"
//	inputData["cardNo"] = "F36084348"
//	inputData["id"] = "44022919620927046X"
//	//jsonStr := `
//	//    {
//	//            "transId": "05",
//	//            "amount":"1.00",
//	//            "traceNo":"20210227093601325405377",
//	//            "cardNo":"F36084348",
//	//            "id":"44022919620927046X"
//	//
//	//    }
//	//`
//
//	bytes_arr, _ := json.Marshal(inputData)
//	str3 := make([]byte, 256)
//	ret4, _, err4 := readCards.Call(StrPtr(string(bytes_arr)), (uintptr)(unsafe.Pointer(&str3[0])))
//	fmt.Println(":", string(str3))
//
//	if err4 != nil {
//		fmt.Println("SSCard的运算结果为:", ret4)
//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
//		return
//	}
//
//}

//func (c *HisApiController) TestGetBasBaseInfo() {
//
//	//result := C.Init(StrPtr("http://igb.hsa.gdgov.cn/gdyb_inf/poc/api/card/initDll"), StrPtr("440200"))
//	//fmt.Println(result)
//	//cs1 := C.CString("")
//	//cs2 := C.CString("")
//	//C.ReadCardBas(cs1, IntPtr(1024), cs2, IntPtr(1024))
//	//fmt.Println(cs1)
//	//fmt.Println(cs2)
//	//C.free(unsafe.Pointer(cs1))
//	//C.free(unsafe.Pointer(cs2))
//
//	//
//
//	DllDef := syscall.MustLoadDLL("SSCard.dll")
//	Iinit := DllDef.MustFindProc("Init")
//	readCard := DllDef.MustFindProc("ReadCardBas")
//	ret, _, err := Iinit.Call(StrPtr("http://igb.hsa.gdgov.cn/gdyb_inf/poc/api/card/initDll"), StrPtr("440200"))
//	if ret != 0 {
//		fmt.Println("SSCard的报错原因:", err)
//		fmt.Println("SSCard的运算结果为:", ret)
//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
//		return
//	}
//
//	result := int(ret)
//	fmt.Println("SSCard的运算结果为1:", result)
//
//	//path := ""
//	//bytePath := []byte(  "\x00")
//	//bytePath2 := []byte(  "\x00")
//	//ssss
//
//	str := make([]byte, 256)
//	str1 := make([]byte, 256)
//	s2 := []byte(string(str))
//	s3 := []byte(string(str1))
//	ret2, _, err2 := readCard.Call((uintptr)(unsafe.Pointer(&s2[0])), IntPtr(256), (uintptr)(unsafe.Pointer(&s3[0])), IntPtr(256))
//	fmt.Println(" Add(4,5)的结果为:", ret2)
//	fmt.Println(" str:", s2)
//	fmt.Println(" str1:", s3)
//	if err2 != nil {
//		fmt.Println("SSCard的运算结果为:", ret2)
//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
//		return
//	}
//
//	//DllDef := syscall.MustLoadDLL("SSCard.dll")
//
//}

func (c *HisApiController) GetOrgInfo() {
	miConfig, _ := service.FindMedicalInsuranceInfo(9919)
	service.Gdyb1201("", miConfig.OrgName, "1122", miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, 1, "")

}

func (c *HisApiController) GetHisPatientInfo() {

	medical_insurance_card := c.GetString("medical_insurance_card")
	id_card_type, _ := c.GetInt64("id_card_type")
	id_card := c.GetString("id_card")

	adminInfo := c.GetAdminUserInfo()
	config, _ := service.GetMedicalInsuranceConfig(adminInfo.CurrentOrgId)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)

	appRole, _ := service.GetAppRole(adminInfo.CurrentOrgId)

	IdCardNo := ""

	if id_card_type == 1 {
		IdCardNo = medical_insurance_card
	} else if id_card_type == 2 {
		IdCardNo = id_card
	}

	if config.IsOpen == 1 {
		api := "http://127.0.0.1:9532/" + "gdyb/one?cert_no=" + IdCardNo + "&org_name=" + miConfig.OrgName + "&doctor=" + appRole.UserName + "&fixmedins_code=" + miConfig.Code + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		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(string(body)), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		userJSON := respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		userJSONBytes, _ := json.Marshal(userJSON)
		var res ResultTwo
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Iinfos, _ := json.Marshal(res.Output.Iinfo)
		Idetinfos, _ := json.Marshal(res.Output.Idetinfo)
		infoStr := string(Iinfos)
		idetinfoStr := string(Idetinfos)
		if res.Infcode == 0 {
			his := models.VMHisPatient{
				Status:      1,
				Ctime:       time.Now().Unix(),
				Mtime:       time.Now().Unix(),
				PsnNo:       res.Output.Baseinfo.PsnNo,
				PsnCertType: res.Output.Baseinfo.PsnCertType,
				Certno:      res.Output.Baseinfo.Certno,
				PsnName:     res.Output.Baseinfo.PsnName,
				Gend:        res.Output.Baseinfo.Gend,
				Naty:        res.Output.Baseinfo.Naty,
				Brdy:        res.Output.Baseinfo.Brdy,
				Age:         res.Output.Baseinfo.Age,
				Iinfo:       infoStr,
				Idetinfo:    idetinfoStr,
				UserOrgId:   adminInfo.CurrentOrgId,
				IsReturn:    1,
				IdCardType:  id_card_type,
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"info": his,
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisFailedException)
			return
		}
	}
}

func (c *HisApiController) Sscard() {
	//id_card_type, _ := c.GetInt64("id_card_type")
	//adminUser := c.GetAdminUserInfo()
	//miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	id_card_type := 1
	r := CardInit()
	fmt.Println(r)
	//if r == 0 {
	switch id_card_type {
	case 1:
		//defer GetBasBaseInfo()

		//if err != nil {
		//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
		//	return
		//
		//} else {
		//	fmt.Println(basStr)
		//
		//	bas := strings.Split(basStr, "|")
		//
		//	basNumber := bas[1]
		//
		//	//basNumber := bas[2]
		//	card_sn := bas[3]
		//
		//	appRole, _ := service.GetAppRole(adminUser.CurrentOrgId)
		//
		//	api := "http://127.0.0.1:9532/" + "gdyb/one?cert_no=" + basNumber + "&org_name=" + miConfig.OrgName + "&doctor=" + appRole.UserName + "&fixmedins_code=" + miConfig.Code + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&id_card_type=" + strconv.FormatInt(int64(id_card_type), 10) + "&card_sn=" + card_sn
		//	resp, requestErr := http.Get(api)
		//	if requestErr != nil {
		//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		//		return
		//	}
		//	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(string(body)), &respJSON); err != nil {
		//		utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
		//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		//		return
		//	}
		//
		//	userJSON := respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		//	userJSONBytes, _ := json.Marshal(userJSON)
		//	var res ResultTwo
		//	if err := json.Unmarshal(userJSONBytes, &res); err != nil {
		//		utils.ErrorLog("解析失败:%v", err)
		//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		//		return
		//	}
		//	Iinfos, _ := json.Marshal(res.Output.Iinfo)
		//	Idetinfos, _ := json.Marshal(res.Output.Idetinfo)
		//	infoStr := string(Iinfos)
		//	idetinfoStr := string(Idetinfos)
		//
		//	if res.Infcode == 0 {
		//		his := models.VMHisPatient{
		//			Status:      1,
		//			Ctime:       time.Now().Unix(),
		//			Mtime:       time.Now().Unix(),
		//			PsnNo:       res.Output.Baseinfo.PsnNo,
		//			PsnCertType: res.Output.Baseinfo.PsnCertType,
		//			Certno:      res.Output.Baseinfo.Certno,
		//			PsnName:     res.Output.Baseinfo.PsnName,
		//			Gend:        res.Output.Baseinfo.Gend,
		//			Naty:        res.Output.Baseinfo.Naty,
		//			Brdy:        res.Output.Baseinfo.Brdy,
		//			Age:         res.Output.Baseinfo.Age,
		//			Iinfo:       infoStr,
		//			Idetinfo:    idetinfoStr,
		//			UserOrgId:   adminUser.CurrentOrgId,
		//			IsReturn:    1,
		//			IdCardType:  id_card_type,
		//		}
		//
		//		patient, err := service.GetPatientByNumber(basNumber, adminUser.CurrentOrgId)
		//		if err == gorm.ErrRecordNotFound {
		//			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNoPateintException)
		//			return
		//
		//		} else if err != nil {
		//			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		//			return
		//
		//		} else {
		//			c.ServeSuccessJSON(map[string]interface{}{
		//				"patient": patient,
		//				"his":     his,
		//				"number":  basNumber,
		//			})
		//		}
		//	} else {
		//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisFailedException)
		//		return
		//	}
		//
		//}

		break
	case 2:
		////SFZStr, err := GetSFZBaseInfo()
		//if err != nil {
		//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
		//	return
		//
		//} else {
		//
		//	id_card_str := strings.Split(SFZStr, "^")
		//	id_card_number := id_card_str[0]
		//appRole, _ := service.GetAppRole(adminUser.CurrentOrgId)
		//
		//api := "http://127.0.0.1:9532/" + "gdyb/one?cert_no=" + id_card_number + "&org_name=" + miConfig.OrgName + "&doctor=" + appRole.UserName + "&fixmedins_code=" + miConfig.Code + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&id_card_type=" + strconv.FormatInt(int64(id_card_type), 10)
		//resp, requestErr := http.Get(api)
		//if requestErr != nil {
		//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		//	return
		//}
		//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(string(body)), &respJSON); err != nil {
		//	utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
		//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		//	return
		//}
		//
		//userJSON := respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		//userJSONBytes, _ := json.Marshal(userJSON)
		//var res ResultTwo
		//if err := json.Unmarshal(userJSONBytes, &res); err != nil {
		//	utils.ErrorLog("解析失败:%v", err)
		//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		//	return
		//}
		//Iinfos, _ := json.Marshal(res.Output.Iinfo)
		//Idetinfos, _ := json.Marshal(res.Output.Idetinfo)
		//infoStr := string(Iinfos)
		//idetinfoStr := string(Idetinfos)
		//
		//if res.Infcode == 0 {
		//	his := models.VMHisPatient{
		//		Status:      1,
		//		Ctime:       time.Now().Unix(),
		//		Mtime:       time.Now().Unix(),
		//		PsnNo:       res.Output.Baseinfo.PsnNo,
		//		PsnCertType: res.Output.Baseinfo.PsnCertType,
		//		Certno:      res.Output.Baseinfo.Certno,
		//		PsnName:     res.Output.Baseinfo.PsnName,
		//		Gend:        res.Output.Baseinfo.Gend,
		//		Naty:        res.Output.Baseinfo.Naty,
		//		Brdy:        res.Output.Baseinfo.Brdy,
		//		Age:         res.Output.Baseinfo.Age,
		//		Iinfo:       infoStr,
		//		Idetinfo:    idetinfoStr,
		//		UserOrgId:   adminUser.CurrentOrgId,
		//		IsReturn:    1,
		//		IdCardType:  id_card_type,
		//	}

		//	patient, err := service.GetPatientByNumber(id_card_number, adminUser.CurrentOrgId)
		//	if err == gorm.ErrRecordNotFound {
		//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNoPateintException)
		//		return
		//
		//	} else if err != nil {
		//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		//		return
		//
		//	} else {
		//		c.ServeSuccessJSON(map[string]interface{}{
		//			"patient": patient,
		//			"number":  id_card_number,
		//		})
		//	}
		//}
		break
	case 3:

		break

	}
}

//func GetBasBaseInfo() (jsonStr string, err error) {
//
//	handle := syscall.NewLazyDLL("SSCard.dll")
//	add := handle.NewProc("ReadCardBas")
//	str := make([]byte, 1024)
//	str1 := make([]byte, 1024)
//	ret, _, _ := add.Call((uintptr)(unsafe.Pointer(&str[0])), IntPtr(1024), (uintptr)(unsafe.Pointer(&str1[0])), IntPtr(1024))
//	fmt.Println(ConvertToString(string(str), "gbk", "utf-8"))
//
//	fmt.Println(ConvertToString(string(str1), "gbk", "utf-8"))
//
//	fmt.Println("> Add(4,5)的结果为:", ret)
//	handle.Release()
//
//	return "", nil
//
//}

//func GetSFZBaseInfo() (jsonStr string, err error) {
//	//handle := syscall.MustLoadDLL("SSCard.dll")
//
//	str := make([]byte, 256)
//	str1 := make([]byte, 256)
//	r, _, _ := ReadIDCardBas.Call((uintptr)(unsafe.Pointer(&str[0])), IntPtr(1024), (uintptr)(unsafe.Pointer(&str1[0])), IntPtr(1024))
//
//	fmt.Println(r)
//	return string(str), nil
//}

//func GetQRBaseInfo() (jsonStr string, err error) {
//	handle := syscall.LoadDLL("SSCard.dll")
//	ReadCardBas := handle.FindProc("GetQRBase")
//
//	str := make([]byte, 256)
//	str1 := make([]byte, 256)
//	r, _, _ := ReadCardBas.Call((uintptr)(unsafe.Pointer(&str[0])), IntPtr(1024), (uintptr)(unsafe.Pointer(&str1[0])), IntPtr(1024))
//
//	fmt.Println(string(str))
//	fmt.Println(r)
//	return string(str), nil
//}

func CardInit() int {
	DllTestDef := syscall.MustLoadDLL("SSCard.dll")
	add := DllTestDef.MustFindProc("Init")
	ret, _, err := add.Call(StrPtr("http://igb.hsa.gdgov.cn/gdyb_inf/poc/api/card/initDll"), StrPtr("440200"))
	if err != nil {
		fmt.Println("SSCard的运算结果为:", ret)
	}
	result := int(ret)
	return result
}

//func CardInit() int {
//	ret, _, err := add.Call(StrPtr("http://igb.hsa.gdgov.cn/gdyb_inf/poc/api/card/initDll"), StrPtr("440200"))
//	if err != nil {
//		fmt.Println("SSCard的运算结果为:", ret)
//	}
//	fmt.Println(err)
//	result := int(ret)
//	return result
//}

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

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

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 ResultThree struct {
	Cainfo      interface{} `json:"cainfo"`
	ErrMsg      string      `json:"err_msg"`
	InfRefmsgid string      `json:"inf_refmsgid"`
	Infcode     int64       `json:"infcode"`
	Output      struct {
		Data struct {
			IptOtpNo string `json:"ipt_otp_no"`
			MdtrtID  string `json:"mdtrt_id"`
			PsnNo    string `json:"psn_no"`
		} `json:"data"`
	} `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 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 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 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 ResultEight struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Stmtinfo struct {
			SetlOptins   string `json:"setl_optins"`
			StmtRslt     string `json:"stmt_rslt"`
			StmtRsltDscr string `json:"stmt_rslt_dscr"`
		} `json:"stmtinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

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

type ResultTen struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		DldEndtime string `json:"dld_endtime"`
		FileQuryNo string `json:"file_qury_no"`
		Filename   string `json:"filename"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

//type Autogenerated struct {
//	Output struct {
//		Setlinfo struct {
//			SetlTime          string      `json:"setl_time"`
//			CvlservPay        float64     `json:"cvlserv_pay"`
//			Year              string      `json:"year"`
//			MedType           string      `json:"med_type"`
//			PsnPay            float64     `json:"psn_pay"`
//			OpterID           string      `json:"opter_id"`
//			Begndate          string      `json:"begndate"`
//			FlxempeFlag       string      `json:"flxempe_flag"`
//			HifmiPay          float64     `json:"hifmi_pay"`
//			PsnNo             string      `json:"psn_no"`
//			ActPayDedc        float64     `json:"act_pay_dedc"`
//			MedinsSetlID      interface{} `json:"medins_setl_id"`
//			AcctMulaidPay     interface{} `json:"acct_mulaid_pay"`
//			ClrWay            string      `json:"clr_way"`
//			OthPay            float64     `json:"oth_pay"`
//			Gend              string      `json:"gend"`
//			MdtrtID           string      `json:"mdtrt_id"`
//			AcctPay           float64     `json:"acct_pay"`
//			InscpScpAmt       float64     `json:"inscp_scp_amt"`
//			Insutype          string      `json:"insutype"`
//			Invono            interface{} `json:"invono"`
//			Enddate           string      `json:"enddate"`
//			CashPayamt        float64     `json:"cash_payamt"`
//			PsnType           string      `json:"psn_type"`
//			FixmedinsName     string      `json:"fixmedins_name"`
//			HifpPay           float64     `json:"hifp_pay"`
//			NewFlag           interface{} `json:"new_flag"`
//			OverlmtSelfpay    float64     `json:"overlmt_selfpay"`
//			PreselfpayAmt     float64     `json:"preselfpay_amt"`
//			PayLoc            string      `json:"pay_loc"`
//			ClrType           string      `json:"clr_type"`
//			RefdSetlFlag      string      `json:"refd_setl_flag"`
//			CvlservFlag       string      `json:"cvlserv_flag"`
//			EmpName           string      `json:"emp_name"`
//			Brdy              string      `json:"brdy"`
//			Naty              string      `json:"naty"`
//			Certno            string      `json:"certno"`
//			DiseCode          string      `json:"dise_code"`
//			FixmedinsCode     string      `json:"fixmedins_code"`
//			DedcHospLv        string      `json:"dedc_hosp_lv"`
//			OpterName         string      `json:"opter_name"`
//			Balc              float64     `json:"balc"`
//			FixmedinsPoolarea string      `json:"fixmedins_poolarea"`
//			PsnCertType       string      `json:"psn_cert_type"`
//			HifobPay          float64     `json:"hifob_pay"`
//			MedfeeSumamt      float64     `json:"medfee_sumamt"`
//			HifesPay          float64     `json:"hifes_pay"`
//			FundPaySumamt     float64     `json:"fund_pay_sumamt"`
//			OptTime           string      `json:"opt_time"`
//			FulamtOwnpayAmt   float64     `json:"fulamt_ownpay_amt"`
//			SetlID            string      `json:"setl_id"`
//			MafPay            float64     `json:"maf_pay"`
//			PsnName           string      `json:"psn_name"`
//			InsuOptins        interface{} `json:"insu_optins"`
//			PrefFundPay       interface{} `json:"pref_fund_pay"`
//			ClrOptins         string      `json:"clr_optins"`
//			PoolPropSelfpay   float64     `json:"pool_prop_selfpay"`
//			DiseName          string      `json:"dise_name"`
//			LmtpricHospLv     string      `json:"lmtpric_hosp_lv"`
//			Age               float64     `json:"age"`
//			DtrtCertType      string      `json:"dtrt_cert_type"`
//			HospLv            string      `json:"hosp_lv"`
//		} `json:"setlinfo"`
//		Setldetail []struct {
//			FundPayType     string      `json:"fund_pay_type"`
//			FundPayamt      float64     `json:"fund_payamt"`
//			SetlProcInfo    interface{} `json:"setl_proc_info"`
//			CrtPaybLmtAmt   interface{} `json:"crt_payb_lmt_amt"`
//			InscpScpAmt     interface{} `json:"inscp_scp_amt"`
//			FundPayTypeName interface{} `json:"fund_pay_type_name"`
//			PrefFundPay     interface{} `json:"pref_fund_pay"`
//		} `json:"setldetail"`
//	} `json:"output"`
//	Infcode     int         `json:"infcode"`
//	WarnMsg     interface{} `json:"warn_msg"`
//	Cainfo      interface{} `json:"cainfo"`
//	ErrMsg      interface{} `json:"err_msg"`
//	RefmsgTime  string      `json:"refmsg_time"`
//	Signtype    interface{} `json:"signtype"`
//	RespondTime string      `json:"respond_time"`
//	InfRefmsgid string      `json:"inf_refmsgid"`
//}

type ResultEleven struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Setlinfo struct {
			SetlTime          string      `json:"setl_time"`
			CvlservPay        float64     `json:"cvlserv_pay"`
			Year              string      `json:"year"`
			MedType           string      `json:"med_type"`
			PsnPay            float64     `json:"psn_pay"`
			OpterID           string      `json:"opter_id"`
			Begndate          string      `json:"begndate"`
			FlxempeFlag       string      `json:"flxempe_flag"`
			HifmiPay          float64     `json:"hifmi_pay"`
			PsnNo             string      `json:"psn_no"`
			ActPayDedc        float64     `json:"act_pay_dedc"`
			MedinsSetlID      interface{} `json:"medins_setl_id"`
			AcctMulaidPay     interface{} `json:"acct_mulaid_pay"`
			ClrWay            string      `json:"clr_way"`
			OthPay            float64     `json:"oth_pay"`
			Gend              string      `json:"gend"`
			MdtrtID           string      `json:"mdtrt_id"`
			AcctPay           float64     `json:"acct_pay"`
			InscpScpAmt       float64     `json:"inscp_scp_amt"`
			Insutype          string      `json:"insutype"`
			Invono            interface{} `json:"invono"`
			Enddate           string      `json:"enddate"`
			CashPayamt        float64     `json:"cash_payamt"`
			PsnType           string      `json:"psn_type"`
			FixmedinsName     string      `json:"fixmedins_name"`
			HifpPay           float64     `json:"hifp_pay"`
			NewFlag           interface{} `json:"new_flag"`
			OverlmtSelfpay    float64     `json:"overlmt_selfpay"`
			PreselfpayAmt     float64     `json:"preselfpay_amt"`
			PayLoc            string      `json:"pay_loc"`
			ClrType           string      `json:"clr_type"`
			RefdSetlFlag      string      `json:"refd_setl_flag"`
			CvlservFlag       string      `json:"cvlserv_flag"`
			EmpName           string      `json:"emp_name"`
			Brdy              string      `json:"brdy"`
			Naty              string      `json:"naty"`
			Certno            string      `json:"certno"`
			DiseCode          string      `json:"dise_code"`
			FixmedinsCode     string      `json:"fixmedins_code"`
			DedcHospLv        string      `json:"dedc_hosp_lv"`
			OpterName         string      `json:"opter_name"`
			Balc              float64     `json:"balc"`
			FixmedinsPoolarea string      `json:"fixmedins_poolarea"`
			PsnCertType       string      `json:"psn_cert_type"`
			HifobPay          float64     `json:"hifob_pay"`
			MedfeeSumamt      float64     `json:"medfee_sumamt"`
			HifesPay          float64     `json:"hifes_pay"`
			FundPaySumamt     float64     `json:"fund_pay_sumamt"`
			OptTime           string      `json:"opt_time"`
			FulamtOwnpayAmt   float64     `json:"fulamt_ownpay_amt"`
			SetlID            string      `json:"setl_id"`
			MafPay            float64     `json:"maf_pay"`
			PsnName           string      `json:"psn_name"`
			InsuOptins        interface{} `json:"insu_optins"`
			PrefFundPay       interface{} `json:"pref_fund_pay"`
			ClrOptins         string      `json:"clr_optins"`
			PoolPropSelfpay   float64     `json:"pool_prop_selfpay"`
			DiseName          string      `json:"dise_name"`
			LmtpricHospLv     string      `json:"lmtpric_hosp_lv"`
			Age               float64     `json:"age"`
			DtrtCertType      string      `json:"dtrt_cert_type"`
			HospLv            string      `json:"hosp_lv"`
		} `json:"setlinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

type ResultTwelve struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		MdtrtId   string `json:"mdtrt_id"`
		ChrgBchno string `json:"chrg_bchno"`
		PsnNo     string `json:"psn_no"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

type ResultThirteen struct {
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Result struct {
			TrtDclaDetlSn string `json:"trt_dcla_detl_sn"`
		} `json:"result"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnInfo    interface{} `json:"warn_info"`
}

type ResultFourteen struct {
	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"`
	WarnInfo    interface{} `json:"warn_info"`
}

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 ResultSeventeen struct {
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		SetlListId string `json:"setl_list_id"`
	} `json:"output"`
	RefmsgTime  string `json:"refmsg_time"`
	RespondTime string `json:"respond_time"`
	Signtype    string `json:"signtype"`
	WarnInfo    string `json:"warn_info"`
}

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

//获取个人信息----挂号-----上传就诊信息
func (c *HisApiController) GetRegisterInfo() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	settlementValue, _ := c.GetInt64("settlement_value")
	medical_insurance_card := c.GetString("medical_insurance_card")
	name := c.GetString("name")
	id_card_type, _ := c.GetInt64("id_card_type")
	certificates, _ := c.GetInt64("certificates")
	medical_care, _ := c.GetInt64("medical_care")
	birthday := c.GetString("birthday")
	age, _ := c.GetInt64("age")
	id_card := c.GetString("id_card")
	register_type, _ := c.GetInt64("register")
	doctor, _ := c.GetInt64("doctor")
	department, _ := c.GetInt64("department")
	gender, _ := c.GetInt64("sex")
	phone := c.GetString("phone")
	registration_fee, _ := c.GetFloat("registration_fee")
	medical_expenses, _ := c.GetFloat("medical_expenses")
	social_type, _ := c.GetInt64("social_type")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	diagnosis_id, _ := c.GetInt64("diagnosis")
	sick_type, _ := c.GetInt64("sick_type")
	reg_type, _ := c.GetInt64("p_type")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	birthdays, _ := time.ParseInLocation(timeLayout+" 15:04:05", birthday+" 00:00:00", loc)
	birthUnix := birthdays.Unix()

	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()
	var patient service.Patients
	if id == 0 {
		patient, _ = service.GetPatientByIDCard(id_card, adminInfo.CurrentOrgId)
	} else {
		patient, _ = service.GetPatientByIDTwo(adminInfo.CurrentOrgId, id)
	}

	patientPrescription, _ := service.FindPatientPrescriptionInfo(adminInfo.CurrentOrgId, id, recordDateTime)
	if patientPrescription.ID == 0 {
		patientPrescription, _ = service.FindLastPatientPrescriptionInfo(adminInfo.CurrentOrgId, id, recordDateTime)
	}

	//adminRole, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, adminInfo.AdminUser.Id)
	diagnosisConfig, _ := service.FindDiagnoseById(diagnosis_id)
	sickConfig, _ := service.FindSickById(sick_type)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)
	if patient.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}
	if len(patient.IdCardNo) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeIDCartNo)
		return
	}
	config, _ := service.GetMedicalInsuranceConfig(adminInfo.CurrentOrgId)
	roles, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, admin_user_id)

	his, _ := service.GetHisPatientInfoTwo(adminInfo.CurrentOrgId, patient.ID, recordDateTime)
	if len(his) >= 1 {
		order, _ := service.GetNewHisOrderTwo(adminInfo.CurrentOrgId, his[len(his)-1].Number, his[len(his)-1].PatientId, recordDateTime)
		if len(his) >= 1 && order.ID == 0 {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisPatientParamWrong)
			return
		}
	}

	if config.IsOpen == 1 {
		api := "http://127.0.0.1:9532/" + "gdyb/one?cert_no=" + patient.IdCardNo + "&org_name=" + miConfig.OrgName + "&doctor=" + patientPrescription.Doctor + "&fixmedins_code=" + miConfig.Code + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&certificates=" + strconv.FormatInt(certificates, 10)
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		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(string(body)), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		userJSON := respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		userJSONBytes, _ := json.Marshal(userJSON)
		var res ResultTwo
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Iinfos, _ := json.Marshal(res.Output.Iinfo)
		Idetinfos, _ := json.Marshal(res.Output.Idetinfo)
		infoStr := string(Iinfos)
		idetinfoStr := string(Idetinfos)

		if res.Infcode == 0 {
			his := models.VMHisPatient{
				Name:                   name,
				Gender:                 gender,
				Birthday:               birthUnix,
				MedicalTreatmentType:   medical_care,
				IdType:                 certificates,
				IdCardNo:               id_card,
				BalanceAccountsType:    settlementValue,
				SocialType:             social_type,
				MedicalInsuranceNumber: medical_insurance_card,
				RegisterType:           register_type,
				RegisterCost:           registration_fee,
				TreatmentCost:          medical_expenses,
				Status:                 1,
				Ctime:                  time.Now().Unix(),
				Mtime:                  time.Now().Unix(),
				PsnNo:                  res.Output.Baseinfo.PsnNo,
				PsnCertType:            res.Output.Baseinfo.PsnCertType,
				Certno:                 res.Output.Baseinfo.Certno,
				PsnName:                res.Output.Baseinfo.PsnName,
				Gend:                   res.Output.Baseinfo.Gend,
				Naty:                   res.Output.Baseinfo.Naty,
				Brdy:                   res.Output.Baseinfo.Brdy,
				Age:                    res.Output.Baseinfo.Age,
				Iinfo:                  infoStr,
				Idetinfo:               idetinfoStr,
				PatientId:              patient.ID,
				RecordDate:             theTime.Unix(),
				UserOrgId:              adminInfo.CurrentOrgId,
				AdminUserId:            admin_user_id,
				IsReturn:               1,
				IdCardType:             id_card_type,
				Doctor:                 doctor,
				Departments:            department,
				SickType:               sick_type,
				Diagnosis:              diagnosis_id,
				PType:                  reg_type,
			}

			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(his.PatientId, 10)
			count, _ := service.FindHisRegisterRecord(theTime.Unix(), patient.ID, adminInfo.CurrentOrgId)
			department, _ := service.GetDepartMentDetail(patientPrescription.Departments)
			doctor_id := strconv.FormatInt(patientPrescription.DoctorId, 10)

			IdCardNo := ""
			if id_card_type == 1 {
				IdCardNo = medical_insurance_card
			} else {
				IdCardNo = patient.IdCardNo
			}

			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 count == 1 {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRegisterRepeatException)
				return
			}
			api := "http://127.0.0.1:9532/" + "gdyb/two?cert_no=" + IdCardNo + "&insutype=" +
				insutype + "&psn_no=" + res.Output.Baseinfo.PsnNo +
				"&org_name=" + miConfig.OrgName + "&doctor=" + patientPrescription.Doctor + "&ipt_otp_no=" + ipt_otp_no +
				"&dept=" + roles.UserName + "&fixmedins_code=" + miConfig.Code + "&dept_code=" + department.Number + "&doctor_id=" + doctor_id + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&id_card_type=" + strconv.FormatInt(int64(id_card_type), 10)
			resp, requestErr := http.Get(api)
			if requestErr != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			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(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{})
			userJSONBytes, _ := json.Marshal(respJSON)
			var res ResultThree
			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			if res.Infcode != 0 {
				adminUser := c.GetAdminUserInfo()
				errlog := &models.HisOrderError{
					UserOrgId:  adminUser.CurrentOrgId,
					Ctime:      time.Now().Unix(),
					Mtime:      time.Now().Unix(),
					ErrMsg:     res.ErrMsg,
					Status:     1,
					PatientId:  id,
					RecordTime: recordDateTime,
					Stage:      2,
				}
				service.CreateErrMsgLog(errlog)
				c.ServeSuccessJSON(map[string]interface{}{
					"failed_code": -10,
					"msg":         res.ErrMsg,
				})
				return
				//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRegisterTwoException)
				//return
			}

			his.Number = res.Output.Data.MdtrtID
			his.PsnNo = res.Output.Data.PsnNo
			his.IptOtpNo = res.Output.Data.IptOtpNo
			his.IdCardNo = patient.IdCardNo
			his.PhoneNumber = patient.Phone
			his.UserOrgId = adminInfo.CurrentOrgId
			his.Ctime = time.Now().Unix()
			his.Mtime = time.Now().Unix()
			his.Status = 0
			service.CreateHisPatientTwo(&his)

			lists, _ := service.GetHisPatientInfoList(adminInfo.CurrentOrgId, patient.ID, recordDateTime)
			if len(lists) == 1 {
				service.UpdateHisPrescriptionHisID(his.ID, patient.ID, recordDateTime, adminInfo.CurrentOrgId)
			}

			if err == nil {
				api2 := "http://127.0.0.1:9532/" + "gdyb/four?psn_no=" + his.PsnNo +
					"&mdtrt_id=" + his.Number + "&doctor=" + patientPrescription.Doctor + "&department=" + department.Name +
					"&diag=" + diagnosisConfig.ClassName + "&org_name=" + miConfig.OrgName + "&med_type=" + strconv.FormatInt(reg_type, 10) + "&doctor_id=" + strconv.FormatInt(patientPrescription.DoctorId, 10) + "&fixmedins_code=" + miConfig.Code + "&diag_code=" + diagnosisConfig.CountryCode +
					"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&sick_code=" + sickConfig.CountryCode + "&sick_name=" + sickConfig.ClassName
				resp2, requestErr2 := http.Get(api2)
				if requestErr2 != nil {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				body2, ioErr2 := ioutil.ReadAll(resp2.Body)
				if ioErr2 != nil {
					utils.ErrorLog("接口返回数据读取失败: %v", ioErr2)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				var respJSON2 map[string]interface{}
				if err := json.Unmarshal([]byte(string(body2)), &respJSON2); err != nil {
					utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				respJSON2 = respJSON2["data"].(map[string]interface{})["pre"].(map[string]interface{})
				userJSONBytes2, _ := json.Marshal(respJSON2)

				var res2 ResultSix
				if err := json.Unmarshal(userJSONBytes2, &res2); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				if res2.Infcode != 0 {
					adminUser := c.GetAdminUserInfo()
					errlog := &models.HisOrderError{
						UserOrgId:  adminUser.CurrentOrgId,
						Ctime:      time.Now().Unix(),
						Mtime:      time.Now().Unix(),
						ErrMsg:     res2.ErrMsg,
						Status:     1,
						PatientId:  id,
						RecordTime: recordDateTime,
						Stage:      3,
					}
					service.CreateErrMsgLog(errlog)
					c.ServeSuccessJSON(map[string]interface{}{
						"failed_code": -10,
						"msg":         res2.ErrMsg,
					})
					return

				} else {
					his.Status = 1
					service.UpdateHisPatientStatus(&his)

					c.ServeSuccessJSON(map[string]interface{}{
						"his_info": his,
					})
				}

			} else {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
				return
			}

		} else {
			adminUser := c.GetAdminUserInfo()
			errlog := &models.HisOrderError{
				UserOrgId:  adminUser.CurrentOrgId,
				Ctime:      time.Now().Unix(),
				Mtime:      time.Now().Unix(),
				ErrMsg:     res.ErrMsg,
				Status:     1,
				PatientId:  id,
				RecordTime: recordDateTime,
				Stage:      1,
			}
			service.CreateErrMsgLog(errlog)

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

			//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeGdybOneException)
		}
	} else {
		timeStr := time.Now().Format("2006-01-02")
		timeArr := strings.Split(timeStr, "-")
		var str = timeArr[0] + timeArr[1] + timeArr[2] + strconv.FormatInt(patient.ID, 10)

		his, err := service.GetHisPatientInfo(adminInfo.CurrentOrgId, patient.ID, recordDateTime)
		var hisPatient models.XtHisPatient
		if err == gorm.ErrRecordNotFound || his.ID == 0 {
			hisPatient = models.XtHisPatient{
				Name:                   name,
				Age:                    age,
				Gender:                 gender,
				Birthday:               birthUnix,
				Phone:                  phone,
				MedicalTreatmentType:   medical_care,
				IdType:                 certificates,
				IdCardNo:               id_card,
				BalanceAccountsType:    settlementValue,
				SocialType:             social_type,
				MedicalInsuranceNumber: medical_insurance_card,
				RegisterType:           register_type,
				RegisterCost:           registration_fee,
				TreatmentCost:          medical_expenses,
				AdminUserId:            admin_user_id,
				UserOrgId:              adminInfo.CurrentOrgId,
				Status:                 1,
				RecordDate:             recordDateTime,
				IsReturn:               1,
				PatientId:              patient.ID,
				Ctime:                  time.Now().Unix(),
				Mtime:                  time.Now().Unix(),
				Number:                 str,
			}
			service.CreateHisPatient(&hisPatient)

		}
		c.ServeSuccessJSON(map[string]interface{}{
			"his_info": hisPatient,
		})
	}
}

//上传明细----预结算----确认订单
func (c *HisApiController) GetUploadInfo() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	his_patient_id, _ := c.GetInt64("his_patient_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")
	settle_accounts_type, _ := c.GetInt64("settle_accounts_type")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	fapiao_code := c.GetString("fapiao_code")
	fapiao_number := c.GetString("fapiao_number")

	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

	var start_time int64
	var end_time int64

	//if adminUser.CurrentOrgId == 10106{
	//	if len(fapiao_code) == 0{
	//		fapiao_code = "144072080589"
	//	}
	//	if len(fapiao_number) == 0{
	//		order, _ := service.GetLastHisOrder(adminUser.CurrentOrgId)
	//		if order.ID == 0{
	//			fapiao_number = "00001520"
	//		}else{
	//			//fapiao_code = "00001520"
	//			fpNumber, _ := strconv.Atoi(order.FaPiaoNumber)
	//			var zero string
	//			if fpNumber >= 1000{
	//				zero = "0000" + strconv.Itoa(fpNumber)
	//			}else if fpNumber >= 10000{
	//				zero = "000" + strconv.Itoa(fpNumber)
	//			} else if fpNumber >= 100000{
	//				zero = "00" + strconv.Itoa(fpNumber)
	//			} else if fpNumber >= 1000000{
	//				zero = "0" + strconv.Itoa(fpNumber)
	//			}else {
	//				zero =  strconv.Itoa(fpNumber)
	//			}
	//			fapiao_number = zero
	//		}
	//	}
	//}

	data := make(map[string]interface{})
	if settle_accounts_type == 1 { //日结
		prescriptions, _ = service.GetHisPrescription(adminUser.CurrentOrgId, id, recordDateTime)
		data["pre"] = prescriptions

	} 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()
		start_time = recordStartTime
		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()
		end_time = recordEndTime
		prescriptions, _ = service.GetMonthHisPrescription(adminUser.CurrentOrgId, id, recordStartTime, recordEndTime)
		data["pre"] = prescriptions

	}

	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	fmt.Println(his_patient_id)
	his, _ := service.GetVMHisPatientInfo(adminUser.CurrentOrgId, id, recordDateTime)
	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(his.PatientId, 10)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	patientPrescription, _ := service.FindPatientPrescriptionInfo(adminUser.CurrentOrgId, id, recordDateTime)
	department, _ := service.GetDepartMentDetail(patientPrescription.Departments)
	strconv.FormatInt(his.PatientId, 10)

	client := &http.Client{}
	data["psn_no"] = his.PsnNo
	data["mdtrt_id"] = his.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(patientPrescription.Departments, 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
	}

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

	for _, item := range prescriptions {
		ids = append(ids, item.ID)
	}
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	if config.IsOpen == 1 { //对接了医保,走医保流程
		bytesData, _ := json.Marshal(data)
		req, _ := http.NewRequest("POST", "http://127.0.0.1:9532/"+"gdyb/five", bytes.NewReader(bytesData))
		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{})
		userJSONBytes, _ := json.Marshal(respJSON)
		var res ResultFour
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		if res.Infcode == 0 {
			order := &models.HisOrder{
				UserOrgId:             adminUser.CurrentOrgId,
				HisPatientId:          his.ID,
				PatientId:             his.PatientId,
				SettleAccountsDate:    recordDateTime,
				Ctime:                 time.Now().Unix(),
				Mtime:                 time.Now().Unix(),
				Status:                1,
				Number:                chrg_bchno,
				Infcode:               res.Infcode,
				WarnMsg:               res.WarnMsg,
				Cainfo:                res.Cainfo,
				ErrMsg:                res.ErrMsg,
				RespondTime:           res.RefmsgTime,
				InfRefmsgid:           res.InfRefmsgid,
				OrderStatus:           1,
				PayWay:                pay_way,
				PayPrice:              pay_price,
				PayCardNo:             pay_card_no,
				DiscountPrice:         discount_price,
				PreferentialPrice:     preferential_price,
				RealityPrice:          reality_price,
				FoundPrice:            found_price,
				MedicalInsurancePrice: medical_insurance_price,
				PrivatePrice:          private_price,
				IsMedicineInsurance:   1,
				SettleType:            settle_accounts_type,
				SettleStartTime:       start_time,
				SettleEndTime:         end_time,
				Creator:               roles.AdminUserId,
				Modify:                roles.AdminUserId,
				FaPiaoNumber:          fapiao_number,
				FaPiaoCode:            fapiao_code,
				PType:                 2,
			}
			err = service.CreateOrder(order)
			if err != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreatePreOrderException)
				return
			}

			for _, item := range res.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:      order.Number,
					FeedetlSn:        item.FeedetlSn,
					UploadDate:       time.Now().Unix(),
					AdviceId:         advice_id,
					DetItemFeeSumamt: item.DetItemFeeSumamt,
					Cnt:              item.Cnt,
					Pric:             float64(item.Pric),
					PatientId:        his.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:     his.ID,
					OrderId:          order.ID,
					ProjectId:        project_id,
					Type:             types,
				}
				service.CreateOrderInfo(info)

			}
			service.UpDatePrescriptionNumber(adminUser.CurrentOrgId, ids, chrg_bchno)
			service.UpDatePrescriptionInfoNumber(adminUser.CurrentOrgId, patientPrescription.PatientId, chrg_bchno, recordDateTime)

			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 {
						total = total + (subItem.Price * float64(subItem.Count))
					}
				}
			}

			for _, item := range prescriptions {
				for _, subItem := range item.HisAdditionalCharge {
					total = total + (subItem.Price * float64(subItem.Count))
				}
			}

			allTotal := fmt.Sprintf("%.2f", total)
			if res.Infcode == 0 {
				var rf []*ResultFive
				json.Unmarshal([]byte(his.Iinfo), &rf)
				chrg_bchno := chrg_bchno
				cert_no := his.Certno

				var insutypes []string

				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.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 his.IdCardType == 1 {
					cert_no = his.MedicalInsuranceNumber

				} else {

					cert_no = his.Certno

				}

				result, src_resquest := service.Gdyb2207(his.PsnNo, his.Number, chrg_bchno, cert_no, insutype, allTotal, miConfig.OrgName, roles.UserName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, strconv.FormatInt(patientPrescription.RegisterType, 10), his.IdCardType, 0, 0, 0, 0, his.IdType)
				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
				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:  adminUser.CurrentOrgId,
						Ctime:      time.Now().Unix(),
						Mtime:      time.Now().Unix(),
						Number:     chrg_bchno,
						ErrMsg:     res.ErrMsg,
						Status:     1,
						PatientId:  id,
						RecordTime: recordDateTime,
						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.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
					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.HifmiPay = res.Output.Setlinfo.HifmiPay
					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, adminUser.CurrentOrgId)
					err = service.UpDateOrder(order)
					if err == nil {
						c.ServeSuccessJSON(map[string]interface{}{
							"msg": "结算成功",
						})
					} else {
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAmountAccountException)
						return
					}
				}
			} else {
				adminUser := c.GetAdminUserInfo()
				errlog := &models.HisOrderError{
					UserOrgId:  adminUser.CurrentOrgId,
					Ctime:      time.Now().Unix(),
					Mtime:      time.Now().Unix(),
					ErrMsg:     res.ErrMsg,
					Status:     1,
					PatientId:  id,
					RecordTime: recordDateTime,
					Stage:      4,
				}
				service.CreateErrMsgLog(errlog)

				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRegisterRepeatException)
				return
			}
		} else {
			adminUser := c.GetAdminUserInfo()
			errlog := &models.HisOrderError{
				UserOrgId:  adminUser.CurrentOrgId,
				Ctime:      time.Now().Unix(),
				Mtime:      time.Now().Unix(),
				ErrMsg:     res.ErrMsg,
				Status:     1,
				PatientId:  id,
				RecordTime: recordDateTime,
				Stage:      4,
			}
			service.CreateErrMsgLog(errlog)
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res.ErrMsg,
			})
			return
			//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCalOrderException)
			//return
		}

	} else {
		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 {
					total = total + (subItem.Price * float64(subItem.Count))
				}
			}

			for _, subItem := range item.HisAdditionalCharge {
				total = total + (subItem.Price * float64(subItem.Count))
			}
		}

		allTotal := fmt.Sprintf("%.2f", total)
		totals, _ := strconv.ParseFloat(allTotal, 64)
		order := &models.HisOrder{
			UserOrgId:             adminUser.CurrentOrgId,
			HisPatientId:          his.ID,
			PatientId:             id,
			SettleAccountsDate:    recordDateTime,
			Ctime:                 time.Now().Unix(),
			Mtime:                 time.Now().Unix(),
			Status:                1,
			OrderStatus:           2,
			Number:                chrg_bchno,
			MedfeeSumamt:          totals,
			PayWay:                pay_way,
			PayPrice:              pay_price,
			PayCardNo:             pay_card_no,
			DiscountPrice:         discount_price,
			PreferentialPrice:     preferential_price,
			RealityPrice:          reality_price,
			FoundPrice:            found_price,
			MedicalInsurancePrice: medical_insurance_price,
			PrivatePrice:          private_price,
		}
		err = service.CreateOrder(order)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreatePreOrderException)
			return
		}

		var customs []*Custom
		for _, item := range prescriptions {

			if item.Type == 1 { //药品
				for _, subItem := range item.HisDoctorAdviceInfo {
					cus := &Custom{
						AdviceId:         subItem.ID,
						ProjectId:        0,
						DetItemFeeSumamt: fmt.Sprintf("%.2f", subItem.Price*subItem.PrescribingNumber),
						Cut:              fmt.Sprintf("%.2f", subItem.PrescribingNumber),
						FeedetlSn:        subItem.FeedetlSn,
						Price:            fmt.Sprintf("%.2f", subItem.Price),
						MedListCodg:      subItem.MedListCodg,
						Type:             1,
					}
					customs = append(customs, cus)
				}
			}

			if item.Type == 2 { //项目
				for _, subItem := range item.HisPrescriptionProject {

					cus := &Custom{
						AdviceId:         0,
						ProjectId:        subItem.ID,
						DetItemFeeSumamt: fmt.Sprintf("%.2f", subItem.Price*float64(subItem.Count)),
						Cut:              fmt.Sprintf("%.2f", float64(subItem.Count)),
						FeedetlSn:        subItem.FeedetlSn,
						Price:            fmt.Sprintf("%.2f", float64(subItem.Price)),
						MedListCodg:      subItem.MedListCodg,
						Type:             2,
					}

					customs = append(customs, cus)
				}
			}

			for _, item := range item.HisAdditionalCharge {
				cus := &Custom{
					ItemId:           item.ID,
					AdviceId:         0,
					ProjectId:        0,
					DetItemFeeSumamt: fmt.Sprintf("%.2f", item.Price),
					Cut:              fmt.Sprintf("%.2f", float64(item.Count)),
					FeedetlSn:        item.FeedetlSn,
					Price:            fmt.Sprintf("%.2f", float64(item.Price)),
					MedListCodg:      item.XtHisAddtionConfig.Code,
					Type:             3,
				}

				customs = append(customs, cus)
			}

		}

		for _, item := range customs {
			var advice_id int64 = 0
			var project_id int64 = 0
			var item_id int64 = 0

			var types int64 = 0

			if item.Type == 1 {
				advice_id = item.AdviceId
				project_id = 0
				item_id = 0
			} else if item.Type == 2 {
				advice_id = 0
				item_id = 0

				project_id = item.ProjectId
			} else if item.Type == 3 {
				advice_id = 0
				item_id = item.ItemId
				project_id = 0
			}

			detItemFeeSumamt, _ := strconv.ParseFloat(item.DetItemFeeSumamt, 32)
			cut, _ := strconv.ParseFloat(item.Cut, 32)
			pric, _ := strconv.ParseFloat(item.Price, 32)

			info := &models.HisOrderInfo{
				OrderNumber:      order.Number,
				UploadDate:       time.Now().Unix(),
				AdviceId:         advice_id,
				DetItemFeeSumamt: detItemFeeSumamt,
				Cnt:              cut,
				Pric:             pric,
				PatientId:        id,
				Status:           1,
				Mtime:            time.Now().Unix(),
				Ctime:            time.Now().Unix(),
				UserOrgId:        adminUser.CurrentOrgId,
				HisPatientId:     his.ID,
				OrderId:          order.ID,
				ProjectId:        project_id,
				Type:             types,
				ItemId:           item_id,
			}
			service.CreateOrderInfo(info)
		}
		//err := service.UpDateAddtionNumber(adminUser.CurrentOrgId, ids, chrg_bchno)
		err = service.UpDatePrescriptionNumber(adminUser.CurrentOrgId, ids, chrg_bchno)
		err = service.UpDatePrescriptionInfoNumber(adminUser.CurrentOrgId, id, chrg_bchno, recordDateTime)
		err = service.UpdataOrderStatusTwo(chrg_bchno, adminUser.CurrentOrgId)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "结算成功",
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAmountAccountException)
			return
		}
	}
}

func (c *HisApiController) GetPreUploadInfo() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	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

	var start_time int64
	var end_time int64

	data := make(map[string]interface{})
	if settle_accounts_type == 1 { //日结
		prescriptions, _ = service.GetHisPrescription(adminUser.CurrentOrgId, id, recordDateTime)
		data["pre"] = prescriptions

	} 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()
		start_time = recordStartTime
		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()
		end_time = recordEndTime
		prescriptions, _ = service.GetMonthHisPrescription(adminUser.CurrentOrgId, id, recordStartTime, recordEndTime)
		data["pre"] = prescriptions

	}

	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)

	his, _ := service.GetVMHisPatientInfo(adminUser.CurrentOrgId, id, recordDateTime)
	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(his.PatientId, 10)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	patientPrescription, _ := service.FindPatientPrescriptionInfo(adminUser.CurrentOrgId, id, recordDateTime)
	department, _ := service.GetDepartMentDetail(patientPrescription.Departments)
	strconv.FormatInt(his.PatientId, 10)
	client := &http.Client{}
	data["psn_no"] = his.PsnNo
	data["mdtrt_id"] = his.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(patientPrescription.Departments, 10)
	data["fixmedins_code"] = miConfig.Code
	data["dept_code"] = department.Number
	data["insuplc_admdvs"] = miConfig.InsuplcAdmdvs
	data["mdtrtarea_admvs"] = miConfig.MdtrtareaAdmvs
	data["secret_key"] = miConfig.SecretKey
	var ids []int64

	for _, item := range prescriptions {
		ids = append(ids, item.ID)
	}
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	if config.IsOpen == 1 { //对接了医保,走医保流程
		bytesData, _ := json.Marshal(data)
		req, _ := http.NewRequest("POST", "http://127.0.0.1:9532/"+"gdyb/five", bytes.NewReader(bytesData))
		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{})
		userJSONBytes, _ := json.Marshal(respJSON)
		var res ResultFour
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		if res.Infcode == 0 {
			order := &models.HisOrder{
				UserOrgId:           adminUser.CurrentOrgId,
				HisPatientId:        his.ID,
				PatientId:           his.PatientId,
				SettleAccountsDate:  recordDateTime,
				Ctime:               time.Now().Unix(),
				Mtime:               time.Now().Unix(),
				Status:              1,
				Number:              chrg_bchno,
				Infcode:             res.Infcode,
				WarnMsg:             res.WarnMsg,
				Cainfo:              res.Cainfo,
				ErrMsg:              res.ErrMsg,
				RespondTime:         res.RefmsgTime,
				InfRefmsgid:         res.InfRefmsgid,
				OrderStatus:         1,
				IsMedicineInsurance: 1,
				SettleType:          settle_accounts_type,
				SettleStartTime:     start_time,
				SettleEndTime:       end_time,
				Creator:             roles.ID,
				Modify:              roles.ID,
			}
			err = service.CreateOrder(order)
			if err != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreatePreOrderException)
				return
			}

			for _, item := range res.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:      order.Number,
					FeedetlSn:        item.FeedetlSn,
					UploadDate:       time.Now().Unix(),
					AdviceId:         advice_id,
					DetItemFeeSumamt: item.DetItemFeeSumamt,
					Cnt:              item.Cnt,
					Pric:             float64(item.Pric),
					PatientId:        his.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:     his.ID,
					OrderId:          order.ID,
					ProjectId:        project_id,
					Type:             types,
				}
				service.CreateOrderInfo(info)

			}
			service.UpDatePrescriptionNumber(adminUser.CurrentOrgId, ids, chrg_bchno)
			service.UpDatePrescriptionInfoNumber(adminUser.CurrentOrgId, patientPrescription.PatientId, chrg_bchno, recordDateTime)

			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 {
						total = total + (subItem.Price * float64(subItem.Count))
					}
				}
			}

			for _, item := range prescriptions {
				for _, subItem := range item.HisAdditionalCharge {
					total = total + (subItem.Price * float64(subItem.Count))
				}
			}

			allTotal := fmt.Sprintf("%.2f", total)
			if res.Infcode == 0 {
				var rf []*ResultFive
				json.Unmarshal([]byte(his.Iinfo), &rf)
				psn_no := his.PsnNo
				mdtrt_id := his.Number
				chrg_bchno := chrg_bchno
				cert_no := his.Certno
				insutype := rf[0].Insutype

				if his.IdCardType == 1 {
					cert_no = his.MedicalInsuranceNumber

				} else {

					cert_no = his.Certno

				}

				api := "http://127.0.0.1:9532/" + "gdyb/seven?cert_no=" + cert_no + "&insutype=" +
					insutype + "&psn_no=" + psn_no + "&chrg_bchno=" + chrg_bchno + "&mdtrt_id=" + mdtrt_id +
					"&total=" + allTotal + "&org_name=" + miConfig.OrgName + "&doctor=" + roles.UserName + "&fixmedins_code=" + miConfig.Code + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" +
					miConfig.SecretKey + "&med_type=" + strconv.FormatInt(patientPrescription.RegisterType, 10) + "&id_card_type=" + strconv.FormatInt(int64(his.IdCardType), 10)
				resp, requestErr := http.Get(api)
				if requestErr != nil {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				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(string(body)), &respJSON); err != nil {
					utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				fmt.Println(respJSON)
				respJSON = respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
				userJSONBytes, _ := json.Marshal(respJSON)
				var res ResultSeven
				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:  adminUser.CurrentOrgId,
						Ctime:      time.Now().Unix(),
						Mtime:      time.Now().Unix(),
						Number:     chrg_bchno,
						ErrMsg:     res.ErrMsg,
						Status:     1,
						PatientId:  id,
						RecordTime: recordDateTime,
						Stage:      7,
					}
					service.CreateErrMsgLog(errlog)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRegisterRepeatException)
					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
					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.ID
					setlDetail, _ := json.Marshal(res.Output.Setldetail)
					detailStr := string(setlDetail)
					order.SetlDetail = detailStr
					//err := service.UpdataOrderStatusTwo(chrg_bchno, adminUser.CurrentOrgId)
					err = service.UpDateOrder(order)
					if err == nil {
						c.ServeSuccessJSON(map[string]interface{}{
							"msg": "预结算成功",
						})
					} else {
						c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAmountAccountException)
						return
					}
				}
			} else {
				adminUser := c.GetAdminUserInfo()
				errlog := &models.HisOrderError{
					UserOrgId:  adminUser.CurrentOrgId,
					Ctime:      time.Now().Unix(),
					Mtime:      time.Now().Unix(),
					ErrMsg:     res.ErrMsg,
					Status:     1,
					PatientId:  id,
					RecordTime: recordDateTime,
					Stage:      4,
				}
				service.CreateErrMsgLog(errlog)

				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRegisterRepeatException)
				return
			}
		} else {
			adminUser := c.GetAdminUserInfo()
			errlog := &models.HisOrderError{
				UserOrgId:  adminUser.CurrentOrgId,
				Ctime:      time.Now().Unix(),
				Mtime:      time.Now().Unix(),
				ErrMsg:     res.ErrMsg,
				Status:     1,
				PatientId:  id,
				RecordTime: recordDateTime,
				Stage:      4,
			}
			service.CreateErrMsgLog(errlog)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCalOrderException)
			return
		}

	} else {
		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 {
					total = total + (subItem.Price * float64(subItem.Count))
				}
			}

			for _, subItem := range item.HisAdditionalCharge {
				total = total + (subItem.Price * float64(subItem.Count))
			}
		}

		allTotal := fmt.Sprintf("%.2f", total)
		totals, _ := strconv.ParseFloat(allTotal, 64)
		order := &models.HisOrder{
			UserOrgId:          adminUser.CurrentOrgId,
			HisPatientId:       his.ID,
			PatientId:          id,
			SettleAccountsDate: recordDateTime,
			Ctime:              time.Now().Unix(),
			Mtime:              time.Now().Unix(),
			Status:             1,
			OrderStatus:        2,
			Number:             chrg_bchno,
			MedfeeSumamt:       totals,
		}
		err = service.CreateOrder(order)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreatePreOrderException)
			return
		}

		var customs []*Custom
		for _, item := range prescriptions {

			if item.Type == 1 { //药品
				for _, subItem := range item.HisDoctorAdviceInfo {
					cus := &Custom{
						AdviceId:         subItem.ID,
						ProjectId:        0,
						DetItemFeeSumamt: fmt.Sprintf("%.2f", subItem.Price*subItem.PrescribingNumber),
						Cut:              fmt.Sprintf("%.2f", subItem.PrescribingNumber),
						FeedetlSn:        subItem.FeedetlSn,
						Price:            fmt.Sprintf("%.2f", subItem.Price),
						MedListCodg:      subItem.MedListCodg,
						Type:             1,
					}
					customs = append(customs, cus)
				}
			}

			if item.Type == 2 { //项目
				for _, subItem := range item.HisPrescriptionProject {

					cus := &Custom{
						AdviceId:         0,
						ProjectId:        subItem.ID,
						DetItemFeeSumamt: fmt.Sprintf("%.2f", subItem.Price*float64(subItem.Count)),
						Cut:              fmt.Sprintf("%.2f", float64(subItem.Count)),
						FeedetlSn:        subItem.FeedetlSn,
						Price:            fmt.Sprintf("%.2f", float64(subItem.Price)),
						MedListCodg:      subItem.MedListCodg,
						Type:             2,
					}

					customs = append(customs, cus)
				}
			}

			for _, item := range item.HisAdditionalCharge {
				cus := &Custom{
					ItemId:           item.ID,
					AdviceId:         0,
					ProjectId:        0,
					DetItemFeeSumamt: fmt.Sprintf("%.2f", item.Price),
					Cut:              fmt.Sprintf("%.2f", float64(item.Count)),
					FeedetlSn:        item.FeedetlSn,
					Price:            fmt.Sprintf("%.2f", float64(item.Price)),
					MedListCodg:      item.XtHisAddtionConfig.Code,
					Type:             3,
				}

				customs = append(customs, cus)
			}

		}

		for _, item := range customs {
			var advice_id int64 = 0
			var project_id int64 = 0
			var item_id int64 = 0

			var types int64 = 0

			if item.Type == 1 {
				advice_id = item.AdviceId
				project_id = 0
				item_id = 0
			} else if item.Type == 2 {
				advice_id = 0
				item_id = 0

				project_id = item.ProjectId
			} else if item.Type == 3 {
				advice_id = 0
				item_id = item.ItemId
				project_id = 0
			}

			detItemFeeSumamt, _ := strconv.ParseFloat(item.DetItemFeeSumamt, 32)
			cut, _ := strconv.ParseFloat(item.Cut, 32)
			pric, _ := strconv.ParseFloat(item.Price, 32)

			info := &models.HisOrderInfo{
				OrderNumber:      order.Number,
				UploadDate:       time.Now().Unix(),
				AdviceId:         advice_id,
				DetItemFeeSumamt: detItemFeeSumamt,
				Cnt:              cut,
				Pric:             pric,
				PatientId:        id,
				Status:           1,
				Mtime:            time.Now().Unix(),
				Ctime:            time.Now().Unix(),
				UserOrgId:        adminUser.CurrentOrgId,
				HisPatientId:     his.ID,
				OrderId:          order.ID,
				ProjectId:        project_id,
				Type:             types,
				ItemId:           item_id,
			}
			service.CreateOrderInfo(info)
		}
		//err := service.UpDateAddtionNumber(adminUser.CurrentOrgId, ids, chrg_bchno)
		err = service.UpDatePrescriptionNumber(adminUser.CurrentOrgId, ids, chrg_bchno)
		err = service.UpDatePrescriptionInfoNumber(adminUser.CurrentOrgId, id, chrg_bchno, recordDateTime)
		err = service.UpdataOrderStatusTwo(chrg_bchno, adminUser.CurrentOrgId)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "结算成功",
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAmountAccountException)
			return
		}
	}
}

//func (c *HisApiController) GetSettleInfo() {
//	id, _ := c.GetInt64("id")
//	order_id, _ := c.GetInt64("order_id")
//
//	record_time := c.GetString("record_time")
//	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")
//	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.GetHisPrescription(adminUser.CurrentOrgId, id, recordDateTime)
//		data["pre"] = prescriptions
//
//	} 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.GetMonthHisPrescription(adminUser.CurrentOrgId, id, recordStartTime, recordEndTime)
//		data["pre"] = prescriptions
//
//	}
//
//	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
//
//	his, _ := service.GetVMHisPatientInfo(adminUser.CurrentOrgId, id, recordDateTime)
//	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
//	patientPrescription, _ := service.FindPatientPrescriptionInfo(adminUser.CurrentOrgId, id, recordDateTime)
//	strconv.FormatInt(his.PatientId, 10)
//
//	order_src, _ := service.GetHisOrderByID(order_id)
//
//	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
//	if config.IsOpen == 1 { //对接了医保,走医保流程
//
//		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 {
//					total = total + (subItem.Price * float64(subItem.Count))
//				}
//			}
//		}
//
//		for _, item := range prescriptions {
//			for _, subItem := range item.HisAdditionalCharge {
//				total = total + (subItem.Price * float64(subItem.Count))
//			}
//		}
//
//		allTotal := fmt.Sprintf("%.2f", total)
//		var rf []*ResultFive
//		json.Unmarshal([]byte(his.Iinfo), &rf)
//		psn_no := order_src.PsnNo
//		mdtrt_id := order_src.MdtrtId
//		chrg_bchno := order_src.Number
//		cert_no := order_src.Certno
//		insutype := rf[0].Insutype
//
//		if his.IdCardType == 1 {
//			cert_no = his.MedicalInsuranceNumber
//		} else {
//			cert_no = his.Certno
//		}
//
//		result, src_resquest := service.Gdyb2207(his.PsnNo, his.Number, chrg_bchno, cert_no, insutype, strconv.FormatFloat(total, 'E', -1, 64) ,miConfig.OrgName,roles.UserName,miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, strconv.FormatInt(patientPrescription.RegisterType, 10),his.IdCardType, order_src.FulamtOwnpayAmt,order_src.OverlmtSelfPay,order_src.PreselfpayAmt,order_src.InscpScpAmt)
//		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
//		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
//			utils.ErrorLog("解析失败:%v", err)
//			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
//			return
//		}
//		if res.Infcode == -1 {
//			errlog := &models.HisOrderError{
//				UserOrgId:  adminUser.CurrentOrgId,
//				Ctime:      time.Now().Unix(),
//				Mtime:      time.Now().Unix(),
//				Number:     chrg_bchno,
//				ErrMsg:     res.ErrMsg,
//				Status:     1,
//				PatientId:  id,
//				RecordTime: recordDateTime,
//				Stage:      6,
//			}
//			service.CreateErrMsgLog(errlog)
//			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRegisterRepeatException)
//			return
//		} else {
//			order_src.OrderStatus = 2
//			order_src.PayWay = pay_way
//			order_src.PayPrice = pay_price
//			order_src.PayCardNo = pay_card_no
//			order_src.DiscountPrice = discount_price
//			order_src.PreferentialPrice = preferential_price
//			order_src.RealityPrice = reality_price
//			order_src.FoundPrice = found_price
//			order_src.MedicalInsurancePrice = medical_insurance_price
//			order_src.PrivatePrice = private_price
//			order_src.MdtrtId = res.Output.Setlinfo.MdtrtID
//			order_src.SetlId = res.Output.Setlinfo.SetlID
//			order_src.PsnNo = res.Output.Setlinfo.PsnNo
//			order_src.PsnName = res.Output.Setlinfo.PsnName
//			order_src.PsnCertType = res.Output.Setlinfo.PsnCertType
//			order_src.Certno = res.Output.Setlinfo.Certno
//			order_src.Gend = res.Output.Setlinfo.Gend
//			order_src.Naty = res.Output.Setlinfo.Naty
//			order_src.Age = res.Output.Setlinfo.Age
//			order_src.Insutype = res.Output.Setlinfo.Insutype
//			order_src.PsnType = res.Output.Setlinfo.PsnType
//			order_src.CvlservFlag = res.Output.Setlinfo.CvlservFlag
//			order_src.SetlTime = res.Output.Setlinfo.SetlTime
//			order_src.MdtrtCertType = res.Output.Setlinfo.MdtrtCertType
//			order_src.MedType = res.Output.Setlinfo.MedType
//			order_src.MedfeeSumamt = res.Output.Setlinfo.MedfeeSumamt
//			order_src.FulamtOwnpayAmt = res.Output.Setlinfo.FulamtOwnpayAmt
//			order_src.OverlmtSelfPay = res.Output.Setlinfo.OverlmtSelfpay
//			order_src.PreselfpayAmt = res.Output.Setlinfo.PreselfpayAmt
//			order_src.InscpScpAmt = res.Output.Setlinfo.InscpScpAmt
//			order_src.ActPayDedc = res.Output.Setlinfo.ActPayDedc
//			order_src.HifpPay = res.Output.Setlinfo.HifpPay
//			order_src.CvlservPay = res.Output.Setlinfo.CvlservPay
//			order_src.PoolPropSelfpay = res.Output.Setlinfo.PoolPropSelfpay
//			order_src.HifesPay = res.Output.Setlinfo.HifesPay
//			order_src.HifobPay = res.Output.Setlinfo.HifobPay
//			order_src.MafPay = res.Output.Setlinfo.MafPay
//			order_src.OthPay = res.Output.Setlinfo.OthPay
//			order_src.FundPaySumamt = res.Output.Setlinfo.FundPaySumamt
//			order_src.PsnPartAmt = res.Output.Setlinfo.PsnPartAmt
//			order_src.AcctPay = res.Output.Setlinfo.AcctPay
//			order_src.PsnCashPay = res.Output.Setlinfo.PsnCashPay
//			order_src.HospPartAmt = res.Output.Setlinfo.HospPartAmt
//			order_src.Balc = res.Output.Setlinfo.Balc
//			order_src.AcctMulaidPay = res.Output.Setlinfo.AcctMulaidPay
//			order_src.MedinsSetlId = res.Output.Setlinfo.MedinsSetlID
//			order_src.ClrOptins = res.Output.Setlinfo.ClrOptins
//			order_src.ClrWay = res.Output.Setlinfo.ClrWay
//			order_src.Creator = order_src.Creator
//			order_src.Modify = roles.ID
//			order_src.RequestLog = src_resquest
//			setlDetail, _ := json.Marshal(res.Output.Setldetail)
//			detailStr := string(setlDetail)
//			order_src.SetlDetail = detailStr
//			err = service.UpdataOrderStatusTwo(chrg_bchno, adminUser.CurrentOrgId)
//			err = service.UpDateOrder(order_src)
//
//			if err == nil {
//				c.ServeSuccessJSON(map[string]interface{}{
//					"msg": "结算成功",
//				})
//			} else {
//				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAmountAccountException)
//				return
//			}
//		}
//	}
//}

//退款
func (c *HisApiController) Refund() {
	order_id, _ := c.GetInt64("order_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	record_time := c.GetString("record_time")
	patient_id, _ := c.GetInt64("patient_id")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminUser := c.GetAdminUserInfo()
	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()
	//his, _ := service.GetVMHisPatientInfo(adminUser.CurrentOrgId, patient_id, recordDateTime)
	var order models.HisOrder
	order, _ = service.GetHisOrderByID(order_id)
	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if order.ID == 0 {
		order, _ = service.GetHisOrderThree(recordDateTime, patient_id, adminUser.CurrentOrgId)
	}
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	if config.IsOpen == 1 { //对接了医保,走医保流程

		result, src_resquest := service.Gdyb2208(order.PsnNo, order.MdtrtId, order.SetlId, miConfig.OrgName, roles.UserName, miConfig.SecretKey, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs)

		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
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		if res.Infcode == 0 {
			result := service.Gdyb2205(order.PsnNo, order.MdtrtId, order.Number, miConfig.OrgName, roles.UserName, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, miConfig.Code)
			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 ResultSix
			if err := json.Unmarshal(userJSONBytes, &res2); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			if res2.Infcode == 0 {
				err := service.UpdataOrderStatus(order_id, order.Number, adminUser.CurrentOrgId, src_resquest, result)
				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,
				})
			}
		} 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 *HisApiController) RefundNumber() {
	record_time := c.GetString("record_time")
	patient_id, _ := c.GetInt64("patient_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	//his_patient_id, _ := c.GetInt64("id")

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

	//his, _ := service.GetNewHisPatientRecord(adminUser.CurrentOrgId, patient_id)
	//patientPrescription, _ := service.FindPatientPrescriptionInfo(adminUser.CurrentOrgId, patient_id, recordDateTime)
	//order, _ := service.GetHisOrderByID(order_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	roles, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)

	if config.IsOpen == 1 { //对接了医保,走医保流程

		api3 := "http://127.0.0.1:9532/" + "gdyb/three?psn_no=" + his.PsnNo +
			"&mdtrt_id=" + his.Number + "&ipt_otp_no=" + his.IptOtpNo + "&doctor=" + roles.UserName + "&org_name=" + miConfig.OrgName + "&fixmedins_code=" + miConfig.Code +
			"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
		resp3, requestErr3 := http.Get(api3)
		if requestErr3 != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		body3, ioErr3 := ioutil.ReadAll(resp3.Body)
		if ioErr3 != nil {
			utils.ErrorLog("接口返回数据读取失败: %v", ioErr3)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		var respJSON3 map[string]interface{}
		if err := json.Unmarshal([]byte(string(body3)), &respJSON3); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		respJSON3 = respJSON3["data"].(map[string]interface{})["pre"].(map[string]interface{})
		userJSONBytes3, _ := json.Marshal(respJSON3)

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

		if res2.Infcode == 0 {
			//err := service.UpdataOrderStatus(order_id, number, adminUser.CurrentOrgId)
			service.UpdataRegStatus(patient_id, recordDateTime, adminUser.CurrentOrgId)

			//err := service.UpdataRegStatus2()

			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,
			})

		}

	} else {
		//err := service.UpdataOrderStatus(order_id, number, adminUser.CurrentOrgId)
		//if err == nil {
		//	c.ServeSuccessJSON(map[string]interface{}{
		//		"msg": "退费成功",
		//	})
		//} else {
		//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		//	return
		//}
	}
}
func (c *HisApiController) RefundDetail() {
	order_id, _ := c.GetInt64("order_id")
	his_patient_id, _ := c.GetInt64("his_patient_id")

	number := c.GetString("number")
	record_time := c.GetString("record_time")
	patient_id, _ := c.GetInt64("patient_id")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminUser := c.GetAdminUserInfo()
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)
	fmt.Println(err)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	his, _ := service.GetVMHisPatientInfo(adminUser.CurrentOrgId, his_patient_id, recordDateTime)
	patientPrescription, _ := service.FindPatientPrescriptionInfo(adminUser.CurrentOrgId, patient_id, recordDateTime)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var order models.HisOrder
	order, _ = service.GetHisOrderByID(order_id)

	if order.ID == 0 {
		order, _ = service.GetHisOrderThree(recordDateTime, patient_id, adminUser.CurrentOrgId)

	}

	if config.IsOpen == 1 { //对接了医保,走医保流程
		api2 := "http://127.0.0.1:9532/" + "gdyb/six?psn_no=" + his.PsnNo +
			"&mdtrt_id=" + his.Number + "&chrg_bchno=" + order.Number + "&doctor=" + patientPrescription.Doctor + "&org_name=" + miConfig.OrgName + "&fixmedins_code=" + miConfig.Code +
			"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
		resp2, requestErr2 := http.Get(api2)
		if requestErr2 != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		body2, ioErr2 := ioutil.ReadAll(resp2.Body)
		if ioErr2 != nil {
			utils.ErrorLog("接口返回数据读取失败: %v", ioErr2)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		var respJSON2 map[string]interface{}
		if err := json.Unmarshal([]byte(string(body2)), &respJSON2); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

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

//对账
func (c *HisApiController) GetCheckAccount() {
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	insutype := c.GetString("insutype")
	clr_type := c.GetString("clr_type")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	orders, _ := service.GetOrderByTime(startime.Unix(), endtime.Unix(), adminUser.CurrentOrgId, insutype, clr_type)
	//orders_two, _ := service.GetOrderByTimeThree(startime.Unix(), endtime.Unix(), adminUser.CurrentOrgId, insutype, clr_type)
	fixmedins_setl_cnt := int64(len(orders))
	//
	////撤销的算2条数据为一笔
	//for _, item := range orders_two {
	//	if item.OrderStatus == 3 {
	//		fixmedins_setl_cnt = fixmedins_setl_cnt + 1
	//	}
	//}
	var medfee_sumamt float64
	var acct_pay float64
	var fund_pay_sumamt float64
	for _, item := range orders {
		medfee_sumamt = medfee_sumamt + item.MedfeeSumamt
		acct_pay = acct_pay + item.AcctPay
		fund_pay_sumamt = fund_pay_sumamt + item.FundPaySumamt
	}
	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if role.ID == 0 {
		user_name = "xxx"
	} else {
		user_name = role.UserName
	}
	if config.IsOpen == 1 {
		api := "http://127.0.0.1:9532/" + "gdyb/ten?" +
			"insutype=" + insutype +
			"&clr_type=" + clr_type +
			"&setl_optins=" + "定点医保中心" +
			"&stmt_begndate=" + start_time +
			"&stm_enddate=" + end_time +
			"&medfee_sumamt=" + fmt.Sprintf("%.2f", medfee_sumamt) +
			"&fund_pay_sumamt=" + fmt.Sprintf("%.2f", fund_pay_sumamt) +
			"&acct_pay=" + fmt.Sprintf("%.2f", acct_pay) +
			"&fixmedins_setl_cnt=" + strconv.FormatInt(fixmedins_setl_cnt, 10) +
			"&fixmedins_code=" + miConfig.Code +
			"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs +
			"&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs +
			"&secret_key=" + miConfig.SecretKey +
			"&org_name=" + miConfig.OrgName +
			"&doctor=" + user_name

		fmt.Println(api)
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		body, ioErr := ioutil.ReadAll(resp.Body)
		fmt.Println(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{})
		userJSONBytes, _ := json.Marshal(respJSON)
		var res ResultEight
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		if res.Infcode == 0 {
			if res.Output.Stmtinfo.StmtRslt == "0" {
				micc := &models.MedicalInsuranceCostCompare{
					StartTime: startime.Unix(),
					EndTime:   endtime.Unix(),
					Insutype:  insutype,
					CheckType: 1,
					Num:       fixmedins_setl_cnt,
					Mtime:     time.Now().Unix(),
					Status:    1,
					UserOrgId: adminUser.CurrentOrgId,
					CostTotal: medfee_sumamt,
					FuncTotal: fund_pay_sumamt,
					PsnPay:    acct_pay,
					Creator:   admin_user_id,
					Ctime:     time.Now().Unix(),
				}
				err := service.CreateMedicalInsuranceCostCompareRecord(micc)
				if err == nil {
					c.ServeSuccessJSON(map[string]interface{}{
						"stmt_rslt":      res.Output.Stmtinfo.StmtRslt,
						"stmt_rslt_dscr": res.Output.Stmtinfo.StmtRsltDscr,
					})

				} else {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				}
			} else {
				c.ServeSuccessJSON(map[string]interface{}{
					"stmt_rslt":      res.Output.Stmtinfo.StmtRslt,
					"stmt_rslt_dscr": res.Output.Stmtinfo.StmtRsltDscr,
				})
			}
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"code": -10,
				"msg":  res.ErrMsg,
			})

		}
	}
}

func (c *HisApiController) Check310() {

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)

	var user_name string
	user_name = "xxx"
	api := "http://127.0.0.1:9532/" + "gdyb/ten?" +
		"insutype=" + "310" +
		"&clr_type=" + "11" +
		"&setl_optins=" + "定点医保中心" +
		"&stmt_begndate=" + "2021-03-01" +
		"&stm_enddate=" + "2021-03-31" +
		"&medfee_sumamt=" + "11521" +
		"&fund_pay_sumamt=" + "10166.66" +
		"&acct_pay=" + "0" +
		"&fixmedins_setl_cnt=" + "7" +
		"&fixmedins_code=" + miConfig.Code +
		"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs +
		"&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs +
		"&secret_key=" + miConfig.SecretKey +
		"&org_name=" + miConfig.OrgName +
		"&doctor=" + user_name

	fmt.Println(api)
	resp, requestErr := http.Get(api)
	if requestErr != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	body, ioErr := ioutil.ReadAll(resp.Body)
	fmt.Println(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{})
	userJSONBytes, _ := json.Marshal(respJSON)

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

}
func (c *HisApiController) Check390() {

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)

	var user_name string
	user_name = "张俊杰"
	api := "http://127.0.0.1:9532/" + "gdyb/ten?" +
		"insutype=" + "390" +
		"&clr_type=" + "11" +
		"&setl_optins=" + "定点医保中心" +
		"&stmt_begndate=" + "2021-03-01" +
		"&stm_enddate=" + "2021-03-31" +
		"&medfee_sumamt=" + "209318.43" +
		"&fund_pay_sumamt=" + "188029.12" +
		"&acct_pay=" + "0" +
		"&fixmedins_setl_cnt=" + "48" +
		"&fixmedins_code=" + miConfig.Code +
		"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs +
		"&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs +
		"&secret_key=" + miConfig.SecretKey +
		"&org_name=" + miConfig.OrgName +
		"&doctor=" + user_name

	fmt.Println(api)
	resp, requestErr := http.Get(api)
	if requestErr != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	body, ioErr := ioutil.ReadAll(resp.Body)
	fmt.Println(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{})
	userJSONBytes, _ := json.Marshal(respJSON)

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

}

//对账明细
func (c *HisApiController) GetCheckDetailAccount() {
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	orders, _ := service.GetOrderByTimeTwo(startime.Unix(), endtime.Unix(), adminUser.CurrentOrgId)

	Mkdir(miConfig.OrgName)
	file := strconv.FormatInt(adminUser.CurrentOrgId, 10) + strconv.FormatInt(time.Now().Unix(), 10)
	file_name := file + ".txt"
	zip_name := file + ".zip"
	zip_path := miConfig.OrgName + "/" + zip_name
	file_path := miConfig.OrgName + "/" + file_name

	decimal.DivisionPrecision = 2
	var medfee_sumamt float64
	var psn_cash_pay float64
	var fund_pay_sumamt float64
	fixmedins_setl_cnt := int64(len(orders))

	for _, item := range orders {
		medfee_sumamt = medfee_sumamt + item.MedfeeSumamt
		psn_cash_pay = psn_cash_pay + item.PsnCashPay
		fund_pay_sumamt = fund_pay_sumamt + item.FundPaySumamt
	}

	f, err := os.Create(miConfig.OrgName + "/" + file_name)
	defer f.Close()
	if err != nil {
		fmt.Println(err.Error())
	} else {
		for _, item := range orders {
			var refd_setl_flag string
			if item.OrderStatus == 2 {
				refd_setl_flag = "0"
				var str string
				str = item.SetlId + "	" +
					item.MdtrtId + "	" +
					item.PsnNo + "	" +
					fmt.Sprintf("%.2f", item.MedfeeSumamt) + "	" +
					fmt.Sprintf("%.2f", item.FundPaySumamt) + "	" +
					fmt.Sprintf("%.2f", item.AcctPay) + "	" + refd_setl_flag + "\r\n"
				_, err = f.Write([]byte(str))
			}
			if item.OrderStatus == 3 {

				var str string
				str = item.SetlId + "	" +
					item.MdtrtId + "	" +
					item.PsnNo + "	" +
					fmt.Sprintf("%.2f", item.MedfeeSumamt) + "	" +
					fmt.Sprintf("%.2f", item.FundPaySumamt) + "	" +
					fmt.Sprintf("%.2f", item.AcctPay) + "	" + "1" + "\r\n"
				_, err = f.Write([]byte(str))

				var str2 string
				str2 = item.SetlId + "	" +
					item.MdtrtId + "	" +
					item.PsnNo + "	" +
					fmt.Sprintf("%.2f", 0-item.MedfeeSumamt) + "	" +
					fmt.Sprintf("%.2f", 0-item.FundPaySumamt) + "	" +
					fmt.Sprintf("%.2f", 0-item.AcctPay) + "	" + "1" + "\r\n"
				_, err = f.Write([]byte(str2))
			}

		}

	}
	Zip(file_path, zip_path)
	fmt.Println(ReadFile(zip_path))
	fmt.Println(string(ReadFile(zip_path)))

	if config.IsOpen == 1 {

		var user_name string
		role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
		if role.ID == 0 {
			user_name = "管理员"
		} else {
			user_name = role.UserName
		}

		baseParams := models.BaseParams{
			SecretKey:      miConfig.SecretKey,
			FixmedinsCode:  miConfig.Code,
			InsuplcAdmdvs:  miConfig.InsuplcAdmdvs,
			MdtrtareaAdmvs: miConfig.MdtrtareaAdmvs,
			OrgName:        miConfig.OrgName,
			Doctor:         user_name,
		}

		result := service.Gdyb9101(baseParams, zip_name, ReadFile(zip_path))

		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 ResultNine
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		if res.Infcode == 0 {
			fileNo := res.Output.FileQuryNo
			api := "http://127.0.0.1:9532/" + "gdyb/twelve?" +
				"file_qury_no=" + fileNo +
				"&setl_optins=" + "定点医保中心" +
				"&stmt_begndate=" + start_time +
				"&stm_enddate=" + end_time +
				"&medfee_sumamt=" + fmt.Sprintf("%.2f", medfee_sumamt) +
				"&fund_pay_sumamt=" + fmt.Sprintf("%.2f", fund_pay_sumamt) +
				"&cash_payamt=" + fmt.Sprintf("%.2f", psn_cash_pay) +
				"&fixmedins_setl_cnt=" + strconv.FormatInt(fixmedins_setl_cnt, 10) +
				"&fixmedins_code=" + miConfig.Code +
				"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs +
				"&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs +
				"&secret_key=" + miConfig.SecretKey +
				"&org_name=" + miConfig.OrgName +
				"&doctor=" + user_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{})

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

			if res.Infcode == 0 {
				service.Gdyb9102(baseParams, zip_name, fileNo)

				micc := &models.MedicalInsuranceCostCompare{
					StartTime: startime.Unix(),
					EndTime:   endtime.Unix(),
					Insutype:  "0",
					CheckType: 2,
					Num:       fixmedins_setl_cnt,
					Mtime:     time.Now().Unix(),
					Status:    1,
					UserOrgId: adminUser.CurrentOrgId,
					CostTotal: medfee_sumamt,
					FuncTotal: fund_pay_sumamt,
					PsnPay:    psn_cash_pay,
					Creator:   admin_user_id,
					Ctime:     time.Now().Unix(),
				}

				service.CreateMedicalInsuranceCostCompareRecord(micc)

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

		} else {

		}
	}
}

func (c *HisApiController) GetSettleAccounts() {
	//id, _ := c.GetInt64("id")
	//record_time := c.GetString("record_time")
	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()
	order, _ := service.GetHisOrderByID(order_id)
	his, _ := service.GetHisPatientByNumber(order.MdtrtId)
	orderInfos, _ := service.GetHisOrderInfoByNumber(order.Number)
	orderInfos_two, _ := service.GetHisOrderInfoByNumberTwo(order.Number)
	orderInfos = append(orderInfos, orderInfos_two...)
	diagnosisConfig, _ := service.FindDiagnoseById(his.Diagnosis)

	var bedCostTotal float64 = 0         //床位总费
	var bedCostSelfTotal float64 = 0     //床位自费
	var bedCostPartSelfTotal float64 = 0 //床位部分项目自费

	var operationCostTotal float64 = 0         //手术费
	var operationCostSelfTotal float64 = 0     //手术费
	var operationCostPartSelfTotal float64 = 0 //手术费

	var otherCostTotal float64 = 0         //其他费用
	var otherCostSelfTotal float64 = 0     //其他费用
	var otherCostPartSelfTotal float64 = 0 //其他费用

	var materialCostTotal float64 = 0         //材料费
	var materialCostSelfTotal float64 = 0     //材料费
	var materialCostPartSelfTotal float64 = 0 //材料费

	var westernMedicineCostTotal float64 = 0         //西药费
	var westernMedicineCostSelfTotal float64 = 0     //西药费
	var westernMedicineCostPartSelfTotal float64 = 0 //西药费

	var chineseTraditionalMedicineCostTotal float64 = 0         //中成药
	var chineseTraditionalMedicineCostSelfTotal float64 = 0     //中成药
	var chineseTraditionalMedicineCostPartSelfTotal float64 = 0 //中成药

	var checkCostTotal float64 = 0         //检查费
	var checkCostSelfTotal float64 = 0     //检查费
	var checkCostPartSelfTotal float64 = 0 //检查费

	var laboratoryCostTotal float64 = 0         //化验费
	var laboratoryCostSelfTotal float64 = 0     //化验费
	var laboratoryCostPartSelfTotal float64 = 0 //化验费

	var treatCostTotal float64 = 0         //治疗费用
	var treatCostSelfTotal float64 = 0     //治疗费用
	var treatCostPartSelfTotal float64 = 0 //治疗费用

	decimal.DivisionPrecision = 2

	for _, item := range orderInfos {
		if item.MedChrgitmType == "01" { //床位费
			bedCostTotal, _ = decimal.NewFromFloat(bedCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			bedCostSelfTotal, _ = decimal.NewFromFloat(bedCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			bedCostPartSelfTotal, _ = decimal.NewFromFloat(bedCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "03" { //检查费
			checkCostTotal, _ = decimal.NewFromFloat(checkCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			checkCostSelfTotal, _ = decimal.NewFromFloat(checkCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			checkCostPartSelfTotal, _ = decimal.NewFromFloat(checkCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "04" { //化验费
			laboratoryCostTotal, _ = decimal.NewFromFloat(laboratoryCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			laboratoryCostSelfTotal, _ = decimal.NewFromFloat(laboratoryCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			laboratoryCostPartSelfTotal, _ = decimal.NewFromFloat(laboratoryCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "05" { //治疗费
			treatCostTotal, _ = decimal.NewFromFloat(treatCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			treatCostSelfTotal, _ = decimal.NewFromFloat(treatCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			treatCostPartSelfTotal, _ = decimal.NewFromFloat(treatCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "06" { //手术费
			operationCostTotal, _ = decimal.NewFromFloat(operationCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			operationCostSelfTotal, _ = decimal.NewFromFloat(operationCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			operationCostPartSelfTotal, _ = decimal.NewFromFloat(operationCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "08" { //材料费
			materialCostTotal, _ = decimal.NewFromFloat(materialCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			materialCostSelfTotal, _ = decimal.NewFromFloat(materialCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			materialCostPartSelfTotal, _ = decimal.NewFromFloat(materialCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "09" { //西药费
			westernMedicineCostTotal, _ = decimal.NewFromFloat(westernMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			westernMedicineCostSelfTotal, _ = decimal.NewFromFloat(westernMedicineCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			westernMedicineCostPartSelfTotal, _ = decimal.NewFromFloat(westernMedicineCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "11" { //中成费
			chineseTraditionalMedicineCostTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			chineseTraditionalMedicineCostSelfTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			chineseTraditionalMedicineCostPartSelfTotal, _ = decimal.NewFromFloat(chineseTraditionalMedicineCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

		if item.MedChrgitmType == "14" { //其他费
			otherCostTotal, _ = decimal.NewFromFloat(otherCostTotal).Add(decimal.NewFromFloat(item.DetItemFeeSumamt)).Float64()
			otherCostSelfTotal, _ = decimal.NewFromFloat(otherCostSelfTotal).Add(decimal.NewFromFloat(item.OverlmtAmt)).Float64()
			otherCostPartSelfTotal, _ = decimal.NewFromFloat(otherCostPartSelfTotal).Add(decimal.NewFromFloat(item.PreselfpayAmt)).Float64()
		}

	}

	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if role.ID == 0 {
		user_name = "管理员"
	} else {
		user_name = role.UserName
	}

	baseParams := models.BaseParams{
		SecretKey:      miConfig.SecretKey,
		FixmedinsCode:  miConfig.Code,
		InsuplcAdmdvs:  miConfig.InsuplcAdmdvs,
		MdtrtareaAdmvs: miConfig.MdtrtareaAdmvs,
		OrgName:        miConfig.OrgName,
		Doctor:         user_name,
	}

	businessParams := models.BusinessParams{
		PsnNo:   order.PsnNo,
		MdtrtId: order.MdtrtId,
		SetlId:  order.SetlId,
	}

	if config.IsOpen == 1 {
		result := service.Gdyb5203(baseParams, businessParams)
		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 ResultEleven
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		printor_admin, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
		charge_admin, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, order.Creator)

		if res.Infcode == 0 {
			c.ServeSuccessJSON(map[string]interface{}{
				"diagnosis":                                   diagnosisConfig.CountryContentName,
				"order_infos":                                 orderInfos,
				"number":                                      order.MdtrtId,
				"date":                                        order.SettleAccountsDate,
				"charge_admin":                                charge_admin,
				"printor_admin":                               printor_admin,
				"info":                                        res.Output.Setlinfo,
				"bedCostTotal":                                bedCostTotal,
				"bedCostSelfTotal":                            bedCostSelfTotal,
				"bedCostPartSelfTotal":                        bedCostPartSelfTotal,
				"operationCostTotal":                          operationCostTotal,
				"operationCostSelfTotal":                      operationCostSelfTotal,
				"operationCostPartSelfTotal":                  operationCostPartSelfTotal,
				"otherCostTotal":                              otherCostTotal,
				"otherCostSelfTotal":                          otherCostSelfTotal,
				"otherCostPartSelfTotal":                      otherCostPartSelfTotal,
				"materialCostTotal":                           materialCostTotal,
				"materialCostSelfTotal":                       materialCostSelfTotal,
				"materialCostPartSelfTotal":                   materialCostPartSelfTotal,
				"westernMedicineCostTotal":                    westernMedicineCostTotal,
				"westernMedicineCostSelfTotal":                westernMedicineCostSelfTotal,
				"westernMedicineCostPartSelfTotal":            westernMedicineCostPartSelfTotal,
				"chineseTraditionalMedicineCostTotal":         chineseTraditionalMedicineCostTotal,
				"chineseTraditionalMedicineCostSelfTotal":     chineseTraditionalMedicineCostSelfTotal,
				"chineseTraditionalMedicineCostPartSelfTotal": chineseTraditionalMedicineCostPartSelfTotal,
				"checkCostTotal":                              checkCostTotal,
				"checkCostSelfTotal":                          checkCostSelfTotal,
				"checkCostPartSelfTotal":                      checkCostPartSelfTotal,
				"laboratoryCostTotal":                         laboratoryCostTotal,
				"laboratoryCostSelfTotal":                     laboratoryCostSelfTotal,
				"laboratoryCostPartSelfTotal":                 laboratoryCostPartSelfTotal,
				"treatCostTotal":                              treatCostTotal,
				"treatCostSelfTotal":                          treatCostSelfTotal,
				"treatCostPartSelfTotal":                      treatCostPartSelfTotal,
			})
		}
	}

}

func (c *HisApiController) CheckTreatment() {
	patient_id, _ := c.GetInt64("patient_id", 0)
	record_time := c.GetString("record_time")
	insutype := c.GetString("insutype")

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

	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, adminUser.AdminUser.Id)
	if role.ID == 0 {
		user_name = "xxx"
	} else {
		user_name = role.UserName
	}

	baseParams := models.BaseParams{
		SecretKey:      miConfig.SecretKey,
		FixmedinsCode:  miConfig.Code,
		InsuplcAdmdvs:  miConfig.InsuplcAdmdvs,
		MdtrtareaAdmvs: miConfig.MdtrtareaAdmvs,
		OrgName:        miConfig.OrgName,
		Doctor:         user_name,
	}

	if config.IsOpen == 1 {
		result := service.Gdyb2001(baseParams, his.PsnNo, insutype, strconv.FormatInt(patientPrescription.RegisterType, 10))
		var dat map[string]interface{}
		if err := json.Unmarshal([]byte(result), &dat); err == nil {
			fmt.Println(dat)
		} else {
			fmt.Println(err)
		}

	}

}

func (c *HisApiController) PutRecord() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	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()
	patient, _ := service.GetPatientByID(adminInfo.CurrentOrgId, id)
	patientPrescription, _ := service.FindPatientPrescriptionInfo(adminInfo.CurrentOrgId, id, recordDateTime)

	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)

	fmt.Println(miConfig.SecretKey)

	if patient == nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
		return
	}
	if len(patient.IdCardNo) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeIDCartNo)
		return
	}
	config, _ := service.GetMedicalInsuranceConfig(adminInfo.CurrentOrgId)
	if config.IsOpen == 1 {
		api := "http://127.0.0.1:9532/" + "gdyb/one?cert_no=" + patient.IdCardNo + "&org_name=" + miConfig.OrgName + "&doctor=" + patientPrescription.Doctor + "&fixmedins_code=" + miConfig.Code + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
		resp, requestErr := http.Get(api)
		if requestErr != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		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(string(body)), &respJSON); err != nil {
			utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		userJSON := respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
		userJSONBytes, _ := json.Marshal(userJSON)
		var res ResultTwo
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		Iinfos, _ := json.Marshal(res.Output.Iinfo)
		Idetinfos, _ := json.Marshal(res.Output.Idetinfo)
		infoStr := string(Iinfos)
		idetinfoStr := string(Idetinfos)

		if res.Infcode == 0 {
			his := models.VMHisPatient{
				Status:      1,
				Ctime:       time.Now().Unix(),
				Mtime:       time.Now().Unix(),
				PsnNo:       res.Output.Baseinfo.PsnNo,
				PsnCertType: res.Output.Baseinfo.PsnCertType,
				Certno:      res.Output.Baseinfo.Certno,
				PsnName:     res.Output.Baseinfo.PsnName,
				Gend:        res.Output.Baseinfo.Gend,
				Naty:        res.Output.Baseinfo.Naty,
				Brdy:        res.Output.Baseinfo.Brdy,
				Age:         res.Output.Baseinfo.Age,
				Iinfo:       infoStr,
				Idetinfo:    idetinfoStr,
				PatientId:   patient.ID,
				RecordDate:  theTime.Unix(),
				UserOrgId:   adminInfo.CurrentOrgId,
				AdminUserId: adminInfo.AdminUser.Id,
				IsReturn:    1,
			}

			doctor_id := strconv.FormatInt(patientPrescription.DoctorId, 10)
			result := service.Gdyb2503(his.PsnNo, res.Output.Iinfo[0].Insutype, miConfig.OrgName, patientPrescription.Doctor, miConfig.Code, doctor_id, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, "重症尿毒症透析(血透)", "M07801")
			result2 := service.Gdyb5301(his.PsnNo, res.Output.Iinfo[0].Insutype, miConfig.OrgName, patientPrescription.Doctor, miConfig.Code, doctor_id, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, "重症尿毒症透析(血透)", "M07801")

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

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

		} else {
			adminUser := c.GetAdminUserInfo()
			errlog := &models.HisOrderError{
				UserOrgId:  adminUser.CurrentOrgId,
				Ctime:      time.Now().Unix(),
				Mtime:      time.Now().Unix(),
				ErrMsg:     res.ErrMsg,
				Status:     1,
				PatientId:  id,
				RecordTime: recordDateTime,
				Stage:      1,
			}
			service.CreateErrMsgLog(errlog)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeGdybOneException)
			return
		}
	}

}

func (c *HisApiController) GetUploadDiag() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")

	diagnosis_id, _ := c.GetInt64("diagnosis")
	sick_type, _ := c.GetInt64("sick_type")
	reg_type, _ := c.GetInt64("reg_type")

	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
	}

	var patientPrescription models.HisPrescriptionInfo
	recordDateTime := theTime.Unix()
	adminInfo := c.GetAdminUserInfo()
	patientPrescription, _ = service.FindPatientPrescriptionInfo(adminInfo.CurrentOrgId, id, recordDateTime)

	if patientPrescription.ID == 0 {
		patientPrescription, _ = service.FindLastPatientPrescriptionInfo(adminInfo.CurrentOrgId, id, recordDateTime)
	}

	miConfig, _ := service.FindMedicalInsuranceInfo(adminInfo.CurrentOrgId)
	diagnosisConfig, _ := service.FindDiagnoseById(diagnosis_id)
	his, _ := service.GetVMHisPatientInfo(adminInfo.CurrentOrgId, id, recordDateTime)
	sickConfig, _ := service.FindSickById(sick_type)
	department, _ := service.GetDepartMentDetail(patientPrescription.Departments)

	api2 := "http://127.0.0.1:9532/" + "gdyb/four?psn_no=" + his.PsnNo +
		"&mdtrt_id=" + his.Number + "&doctor=" + patientPrescription.Doctor + "&department=" + department.Name +
		"&diag=" + diagnosisConfig.ClassName + "&org_name=" + miConfig.OrgName + "&med_type=" + strconv.FormatInt(reg_type, 10) + "&doctor_id=" + strconv.FormatInt(patientPrescription.DoctorId, 10) + "&fixmedins_code=" + miConfig.Code + "&diag_code=" + diagnosisConfig.CountryCode +
		"&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey + "&sick_code=" + sickConfig.CountryCode + "&sick_name=" + sickConfig.ClassName
	resp2, requestErr2 := http.Get(api2)
	if requestErr2 != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	body2, ioErr2 := ioutil.ReadAll(resp2.Body)
	if ioErr2 != nil {
		utils.ErrorLog("接口返回数据读取失败: %v", ioErr2)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	var respJSON2 map[string]interface{}
	if err := json.Unmarshal([]byte(string(body2)), &respJSON2); err != nil {
		utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	respJSON2 = respJSON2["data"].(map[string]interface{})["pre"].(map[string]interface{})
	userJSONBytes2, _ := json.Marshal(respJSON2)

	var res2 ResultSix
	if err := json.Unmarshal(userJSONBytes2, &res2); err != nil {
		utils.ErrorLog("解析失败:%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	if res2.Infcode != 0 {
		adminUser := c.GetAdminUserInfo()
		errlog := &models.HisOrderError{
			UserOrgId:  adminUser.CurrentOrgId,
			Ctime:      time.Now().Unix(),
			Mtime:      time.Now().Unix(),
			ErrMsg:     res2.ErrMsg,
			Status:     1,
			PatientId:  id,
			RecordTime: recordDateTime,
			Stage:      3,
		}
		service.CreateErrMsgLog(errlog)

		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeRegisterThreeException)
		return
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "上传成功",
	})

}

type QueryResult struct {
	ID             int64
	Name           string
	Code           string
	List_type_code string
}

func (c *HisApiController) GetCheckCode() {
	ids_str := c.GetString("ids")
	record_type, _ := c.GetInt64("record_type") //1.药品 2.耗材  3.项目

	ids_arr := strings.Split(ids_str, ",")
	var queryResult []QueryResult
	ids := make([]int64, 0)
	for _, item := range ids_arr {
		id, _ := strconv.ParseInt(item, 10, 64)
		ids = append(ids, id)
	}
	if record_type == 1 {
		drugs, _ := service.GetBatchDrugList(ids)
		for _, item := range drugs {
			result := QueryResult{
				ID:             item.ID,
				Name:           item.DrugName,
				Code:           item.MedicalInsuranceNumber,
				List_type_code: "101",
			}
			queryResult = append(queryResult, result)
		}

	} else if record_type == 2 {
		goods, _ := service.GetBatchGoodInformationList(ids)

		for _, item := range goods {
			result := QueryResult{
				ID:             item.ID,
				Name:           item.GoodName,
				Code:           item.MedicalInsuranceNumber,
				List_type_code: "301",
			}
			queryResult = append(queryResult, result)
		}
	} else if record_type == 3 {
		projects, _ := service.GetBathchMyPorjecgList(ids)
		for _, item := range projects {
			result := QueryResult{
				ID:             item.ID,
				Name:           item.ProjectName,
				Code:           item.MedicalCode,
				List_type_code: "201",
			}
			queryResult = append(queryResult, result)
		}
	}

	admin_user_id, _ := c.GetInt64("admin_user_id")
	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if role.ID == 0 {
		user_name = "xxx"
	} else {
		user_name = role.UserName
	}

	baseParams := &models.BaseParams{
		SecretKey:      miConfig.SecretKey,
		FixmedinsCode:  miConfig.Code,
		InsuplcAdmdvs:  miConfig.InsuplcAdmdvs,
		MdtrtareaAdmvs: miConfig.MdtrtareaAdmvs,
		OrgName:        miConfig.OrgName,
		Doctor:         user_name,
	}

	if config.IsOpen == 1 {
		for _, item := range queryResult {
			var result string
			if record_type == 1 {
				result = service.Gdyb3301(baseParams, item.Name, item.Code, item.List_type_code, "2021-04-26", "", item.List_type_code)
			} else if record_type == 2 {
				result = service.Gdyb3301(baseParams, item.Name, item.Code, item.List_type_code, "2021-04-26", "", item.List_type_code)
			} else if record_type == 3 {
				result = service.Gdyb3301(baseParams, item.Name, item.Code, item.List_type_code, "2021-04-26", "", item.List_type_code)
			}
			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
			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			if res.Infcode == 0 {
				if record_type == 1 {
					service.UpdateBaseDrugById(item.ID)
				} else if record_type == 2 {
					service.UpdateGoodInformaitonByDetail(item.ID)
				} else if record_type == 3 {
					service.UpdateProjectById(item.ID)
				}
				c.ServeSuccessJSON(map[string]interface{}{
					"failed_code": 0,
					"msg":         "目录对照成功",
				})
			} else {
				c.ServeSuccessJSON(map[string]interface{}{
					"failed_code": -10,
					"msg":         res.ErrMsg,
				})

			}
		}
	}
}
func (c *HisApiController) UnCheckCode() {
	ids_str := c.GetString("ids")
	record_type, _ := c.GetInt64("record_type") //1.药品 2.耗材  3.项目
	admin_user_id, _ := c.GetInt64("admin_user_id")
	ids_arr := strings.Split(ids_str, ",")
	var queryResult []QueryResult
	ids := make([]int64, 0)
	for _, item := range ids_arr {
		id, _ := strconv.ParseInt(item, 10, 64)
		ids = append(ids, id)
	}
	if record_type == 1 {
		drugs, _ := service.GetBatchDrugList(ids)
		for _, item := range drugs {
			result := QueryResult{
				ID:             item.ID,
				Name:           item.DrugName,
				Code:           item.MedicalInsuranceNumber,
				List_type_code: "101",
			}
			queryResult = append(queryResult, result)
		}

	} else if record_type == 2 {
		goods, _ := service.GetBatchGoodInformationList(ids)

		for _, item := range goods {
			result := QueryResult{
				ID:             item.ID,
				Name:           item.GoodName,
				Code:           item.MedicalInsuranceNumber,
				List_type_code: "301",
			}
			queryResult = append(queryResult, result)
		}
	} else if record_type == 3 {
		projects, _ := service.GetBathchMyPorjecgList(ids)
		for _, item := range projects {
			result := QueryResult{
				ID:             item.ID,
				Name:           item.ProjectName,
				Code:           item.MedicalCode,
				List_type_code: "201",
			}
			queryResult = append(queryResult, result)
		}
	}

	adminUser := c.GetAdminUserInfo()

	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if role.ID == 0 {
		user_name = "xxx"
	} else {
		user_name = role.UserName
	}

	baseParams := &models.BaseParams{
		SecretKey:      miConfig.SecretKey,
		FixmedinsCode:  miConfig.Code,
		InsuplcAdmdvs:  miConfig.InsuplcAdmdvs,
		MdtrtareaAdmvs: miConfig.MdtrtareaAdmvs,
		OrgName:        miConfig.OrgName,
		Doctor:         user_name,
	}

	if config.IsOpen == 1 {
		for _, item := range queryResult {
			var result string
			if record_type == 1 {
				result = service.Gdyb3302(baseParams, item.Name, item.Code, item.List_type_code)
			} else if record_type == 2 {
				result = service.Gdyb3302(baseParams, item.Name, item.Code, item.List_type_code)
			} else if record_type == 3 {
				result = service.Gdyb3302(baseParams, item.Name, item.Code, item.List_type_code)
			}
			var dat2 map[string]interface{}
			if err := json.Unmarshal([]byte(result), &dat2); err == nil {
				fmt.Println(dat2)
			} else {
				fmt.Println(err)
			}
			userJSONBytes, _ := json.Marshal(dat2)
			var res ResultSix
			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			if res.Infcode == 0 {
				if record_type == 1 {
					service.UpdateDrugByIdDetail(item.ID)
				} else if record_type == 2 {
					service.UpdateGoodInfoById(item.ID)
				} else if record_type == 3 {
					service.UpdateMyProjectById(item.ID)
				}
				c.ServeSuccessJSON(map[string]interface{}{
					"failed_code": 0,
					"msg":         "撤销目录对照成功",
				})
			} else {
				c.ServeSuccessJSON(map[string]interface{}{
					"failed_code": -10,
					"msg":         res.ErrMsg,
				})
			}
		}
	}
}
func (c *HisApiController) GetPatientInfo() {
	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 {

		result := service.Gdyb1101A(id_card_no, miConfig.OrgName, role.UserName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey)
		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
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		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,
			})
		}

	}
}
func (c *HisApiController) PsnPutOnRecord() {
	record_type, _ := c.GetInt64("type")
	patient_id, _ := c.GetInt64("patient_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var patients []*models.Patients
	if record_type == 1 { //全部备案

		patient, _ := service.GetAllPatient(adminUser.CurrentOrgId)
		patients = append(patients, patient...)

	} else { //单个备案
		patient, _ := service.GetPatientByID(adminUser.CurrentOrgId, patient_id)
		patients = append(patients, patient)

	}

	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if role.ID == 0 {
		user_name = "xxx"
	} else {
		user_name = role.UserName
	}

	if config.IsOpen == 1 {
		for _, item := range patients {
			api := "http://127.0.0.1:9532/" + "gdyb/one?cert_no=" + item.IdCardNo + "&org_name=" + miConfig.OrgName + "&doctor=" + user_name + "&fixmedins_code=" + miConfig.Code + "&insuplc_admdvs=" + miConfig.InsuplcAdmdvs + "&mdtrtarea_admvs=" + miConfig.MdtrtareaAdmvs + "&secret_key=" + miConfig.SecretKey
			resp, requestErr := http.Get(api)
			if requestErr != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}
			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(string(body)), &respJSON); err != nil {
				utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			userJSON := respJSON["data"].(map[string]interface{})["pre"].(map[string]interface{})
			userJSONBytes, _ := json.Marshal(userJSON)
			var res ResultTwo
			if err := json.Unmarshal(userJSONBytes, &res); err != nil {
				utils.ErrorLog("解析失败:%v", err)
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			if res.Infcode == 0 {
				result := service.Gdyb2505(res.Output.Baseinfo.PsnNo, user_name, miConfig.OrgName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, start_time, end_time)
				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 ResultThirteen
				if err := json.Unmarshal(userJSONBytes, &res2); err != nil {
					utils.ErrorLog("解析失败:%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
				if res2.Infcode == 0 {
					psnResult := &models.GdybPsnRecord{
						UserOrgId:     adminUser.CurrentOrgId,
						PatientId:     item.ID,
						PsnNo:         res.Output.Baseinfo.PsnNo,
						Ctime:         time.Now().Unix(),
						Mtime:         time.Now().Unix(),
						Status:        1,
						IsCancel:      1,
						TrtDclaDetlSn: res2.Output.Result.TrtDclaDetlSn,
					}
					service.CreatePsnRecord(psnResult)

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

			}

		}
	}

}
func (c *HisApiController) PsnUnPutOnRecord() {
	id, _ := c.GetInt64("id")
	//record_type, _ := c.GetInt64("type")
	admin_user_id, _ := c.GetInt64("admin_user_id")

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if role.ID == 0 {
		user_name = "xxx"
	} else {
		user_name = role.UserName
	}

	psn_record, _ := service.GetPsnRecordById(id)
	if psn_record.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorPsnRecordNoExistWrong)
		return
	}
	if config.IsOpen == 1 {
		result := service.Gdyb2506(psn_record.PsnNo, user_name, miConfig.OrgName, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, psn_record.TrtDclaDetlSn)
		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 ResultFourteen
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		if res.Infcode == 0 {
			psn_record.IsCancel = 2
			service.CreatePsnRecord(&psn_record)
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res.ErrMsg,
			})
			return
		}
	}

}
func (c *HisApiController) PsnPutNCDSOnRecord() {
	patient_id, _ := c.GetInt64("patient_id")
	insutype := c.GetString("insutype")
	psn_no := c.GetString("psn_no")
	doctor_id, _ := c.GetInt64("doctor_id")
	sick_id, _ := c.GetInt64("sick_id")
	department_id, _ := c.GetInt64("department_id")
	adminUser := c.GetAdminUserInfo()
	patient, _ := service.GetPatientByID(adminUser.CurrentOrgId, patient_id)
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	sick, _ := service.FindSickById(sick_id)
	doctor, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, doctor_id)
	if config.IsOpen == 1 {
		result := service.Gdyb2503(psn_no, insutype, miConfig.OrgName, doctor.UserName, miConfig.Code, strconv.FormatInt(doctor.ID, 10), miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, sick.ClassName, sick.CountryCode)
		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 ResultThirteen
		if err := json.Unmarshal(userJSONBytes, &res2); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		if res2.Infcode == 0 {
			psnResult := &models.GdybPsnNcdsRecord{
				UserOrgId:     adminUser.CurrentOrgId,
				PatientId:     patient.ID,
				PsnNo:         psn_no,
				DoctorId:      doctor.AdminUserId,
				DepartmentId:  department_id,
				SickType:      sick_id,
				Insutype:      insutype,
				Ctime:         time.Now().Unix(),
				Mtime:         time.Now().Unix(),
				Status:        1,
				IsCancel:      1,
				TrtDclaDetlSn: res2.Output.Result.TrtDclaDetlSn,
			}
			service.CreatePsnNCDSRecord(psnResult)
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": 0,
				"msg":         "备案成功",
				"result":      psnResult,
			})

		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res2.ErrMsg,
			})
			return
		}
	}
}
func (c *HisApiController) PsnPutUnNCDSOnRecord() {
	id, _ := c.GetInt64("id")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var user_name string
	role, _ := service.GetAdminUserInfoByID(adminUser.CurrentOrgId, admin_user_id)
	if role.ID == 0 {
		user_name = "xxx"
	} else {
		user_name = role.UserName
	}

	psn_record, _ := service.GetPsnNCDSRecordById(id)
	if psn_record.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorPsnRecordNoExistWrong)
		return
	}
	if config.IsOpen == 1 {
		result := service.Gdyb2504(psn_record.PsnNo, miConfig.OrgName, user_name, miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey, psn_record.TrtDclaDetlSn)
		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 ResultFourteen
		if err := json.Unmarshal(userJSONBytes, &res); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		if res.Infcode == 0 {
			psn_record.IsCancel = 2
			service.CreatePsnNCDSRecord(&psn_record)
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": 0,
				"msg":         "撤销备案成功",
			})
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res.ErrMsg,
			})
			return
		}
	}

}

func (c *HisApiController) TestTest() {
	patient, _ := service.GetHisPatientInfo(4, 456, 1619712000)
	fmt.Println(patient.Iinfo)

}

type CustomData struct {
	MsgId string
	PsnNo string
	Info  string
}

func (c *HisApiController) ReversalData() {
	var customData []*CustomData

	custom := &CustomData{
		MsgId: "H44022900158202103301714472004",
		PsnNo: "44020000001101329945",
		Info:  "2207",
	}
	customData = append(customData, custom)

	custom1 := &CustomData{
		MsgId: "H4402290015820210330172057803",
		PsnNo: "44020000001101161813",
		Info:  "2207",
	}
	customData = append(customData, custom1)
	custom2 := &CustomData{
		MsgId: "H44022900158202103301705198813",
		PsnNo: "44190000133097375417",
		Info:  "2207",
	}
	customData = append(customData, custom2)
	custom3 := &CustomData{
		MsgId: "H44022900158202103301715524756",
		PsnNo: "44020000001100187221",
		Info:  "2207",
	}
	customData = append(customData, custom3)
	custom4 := &CustomData{
		MsgId: "H44022900158202103301730376224",
		PsnNo: "44020000001101959155",
		Info:  "2207",
	}
	customData = append(customData, custom4)
	custom5 := &CustomData{
		MsgId: "H44022900158202103301748008725",
		PsnNo: "44020000001104246641",
		Info:  "2207",
	}
	customData = append(customData, custom5)
	custom6 := &CustomData{
		MsgId: "H44022900158202103301718096755",
		PsnNo: "44020000001102211860",
		Info:  "2207",
	}
	customData = append(customData, custom6)
	custom7 := &CustomData{
		MsgId: "H44022900158202103301736551640",
		PsnNo: "44020000001102687718",
		Info:  "2207",
	}

	customData = append(customData, custom7)

	custom8 := &CustomData{
		MsgId: "H44022900158202103301743097676",
		PsnNo: "44020000001102127785",
		Info:  "2207",
	}
	customData = append(customData, custom8)
	custom9 := &CustomData{
		MsgId: "H44022900158202103301712304203",
		PsnNo: "44020000001101518097",
		Info:  "2207",
	}
	customData = append(customData, custom9)
	custom10 := &CustomData{
		MsgId: "H44022900158202103301738448785",
		PsnNo: "44020000001100500813",
		Info:  "2207",
	}
	customData = append(customData, custom10)

	custom11 := &CustomData{
		MsgId: "H44022900158202103301732455843",
		PsnNo: "44020000001102690557",
		Info:  "2207",
	}

	customData = append(customData, custom11)

	custom12 := &CustomData{
		MsgId: "H44022900158202103301745421708",
		PsnNo: "44020000001102211928",
		Info:  "2207",
	}
	customData = append(customData, custom12)

	custom1212 := &CustomData{
		MsgId: "H440229001582021033017351627",
		PsnNo: "44020000001102481733",
		Info:  "2207",
	}
	customData = append(customData, custom1212)

	custom13 := &CustomData{
		MsgId: "H44022900158202103301740327951",
		PsnNo: "44020000001103174866",
		Info:  "2207",
	}
	customData = append(customData, custom13)
	custom14 := &CustomData{
		MsgId: "H4402290015820210330174922668",
		PsnNo: "44020000001102927272",
		Info:  "2207",
	}
	customData = append(customData, custom14)
	custom15 := &CustomData{
		MsgId: "H44022900158202103301752362273",
		PsnNo: "44020000001102942890",
		Info:  "2207",
	}
	customData = append(customData, custom15)

	custom16 := &CustomData{
		MsgId: "H44022900158202103301751082917",
		PsnNo: "44020000001101662162",
		Info:  "2207",
	}
	customData = append(customData, custom16)

	custom17 := &CustomData{
		MsgId: "H44022900158202103301754147728",
		PsnNo: "44020000000229014511",
		Info:  "2207",
	}
	customData = append(customData, custom17)

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)

	for _, item := range customData {
		result := service.Gdyb2601(item.PsnNo, item.MsgId, item.Info, miConfig.OrgName, "张俊杰", miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey)
		fmt.Println(result)
	}
}
func (c *HisApiController) ReversalOtherData() {
	var customData []*CustomData

	custom := &CustomData{
		MsgId: "H44022900158202103301714472004",
		PsnNo: "44020000001101329945",
		Info:  "2208",
	}
	customData = append(customData, custom)

	custom1 := &CustomData{
		MsgId: "H4402290015820210330172057803",
		PsnNo: "44020000001101161813",
		Info:  "2208",
	}
	customData = append(customData, custom1)
	custom2 := &CustomData{
		MsgId: "H44022900158202103301705198813",
		PsnNo: "44190000133097375417",
		Info:  "2208",
	}
	customData = append(customData, custom2)
	custom3 := &CustomData{
		MsgId: "H44022900158202103301715524756",
		PsnNo: "44020000001100187221",
		Info:  "2208",
	}
	customData = append(customData, custom3)
	custom4 := &CustomData{
		MsgId: "H44022900158202103301730376224",
		PsnNo: "44020000001101959155",
		Info:  "2208",
	}
	customData = append(customData, custom4)
	custom5 := &CustomData{
		MsgId: "H44022900158202103301748008725",
		PsnNo: "44020000001104246641",
		Info:  "2208",
	}
	customData = append(customData, custom5)
	custom6 := &CustomData{
		MsgId: "H44022900158202103301718096755",
		PsnNo: "44020000001102211860",
		Info:  "2208",
	}
	customData = append(customData, custom6)
	custom7 := &CustomData{
		MsgId: "H44022900158202103301736551640",
		PsnNo: "44020000001102687718",
		Info:  "2208",
	}

	customData = append(customData, custom7)

	custom8 := &CustomData{
		MsgId: "H44022900158202103301743097676",
		PsnNo: "44020000001102127785",
		Info:  "2208",
	}
	customData = append(customData, custom8)
	custom9 := &CustomData{
		MsgId: "H44022900158202103301712304203",
		PsnNo: "44020000001101518097",
		Info:  "2208",
	}
	customData = append(customData, custom9)
	custom10 := &CustomData{
		MsgId: "H44022900158202103301738448785",
		PsnNo: "44020000001100500813",
		Info:  "2208",
	}
	customData = append(customData, custom10)

	custom11 := &CustomData{
		MsgId: "H44022900158202103301732455843",
		PsnNo: "44020000001102690557",
		Info:  "2208",
	}

	customData = append(customData, custom11)

	custom12 := &CustomData{
		MsgId: "H44022900158202103301745421708",
		PsnNo: "44020000001102211928",
		Info:  "2208",
	}
	customData = append(customData, custom12)

	custom1212 := &CustomData{
		MsgId: "H440229001582021033017351627",
		PsnNo: "44020000001102481733",
		Info:  "2208",
	}
	customData = append(customData, custom1212)

	custom13 := &CustomData{
		MsgId: "H44022900158202103301740327951",
		PsnNo: "44020000001103174866",
		Info:  "2208",
	}
	customData = append(customData, custom13)
	custom14 := &CustomData{
		MsgId: "H4402290015820210330174922668",
		PsnNo: "44020000001102927272",
		Info:  "2208",
	}
	customData = append(customData, custom14)
	custom15 := &CustomData{
		MsgId: "H44022900158202103301752362273",
		PsnNo: "44020000001102942890",
		Info:  "2208",
	}
	customData = append(customData, custom15)

	custom16 := &CustomData{
		MsgId: "H44022900158202103301751082917",
		PsnNo: "44020000001101662162",
		Info:  "2208",
	}
	customData = append(customData, custom16)

	custom17 := &CustomData{
		MsgId: "H44022900158202103301754147728",
		PsnNo: "44020000000229014511",
		Info:  "2208",
	}
	customData = append(customData, custom17)

	adminUser := c.GetAdminUserInfo()
	miConfig, _ := service.FindMedicalInsuranceInfo(adminUser.CurrentOrgId)

	for _, item := range customData {
		result := service.Gdyb2601(item.PsnNo, item.MsgId, item.Info, miConfig.OrgName, "张俊杰", miConfig.Code, miConfig.InsuplcAdmdvs, miConfig.MdtrtareaAdmvs, miConfig.SecretKey)
		fmt.Println(result)
	}
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

//创建文件夹
func Mkdir(dir string) {
	// 创建文件夹
	exist, err := PathExists(dir)
	if err != nil {
		fmt.Println(err.Error())
	} else {
		if exist {
			fmt.Println(dir + "文件夹已存在!")
		} else {
			// 文件夹名称,权限
			err := os.Mkdir(dir, os.ModePerm)
			if err != nil {
				fmt.Println(dir+"文件夹创建失败:", err.Error())
			} else {
				fmt.Println(dir + "文件夹创建成功!")
			}
		}
	}
}

//压缩文件
func Zip(srcFile string, destZip string) error {
	zipfile, err := os.Create(destZip)
	if err != nil {
		return err
	}
	defer zipfile.Close()

	archive := zip.NewWriter(zipfile)
	defer archive.Close()

	filepath.Walk(srcFile, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}

		header.Name = strings.TrimPrefix(path, filepath.Dir(srcFile)+"/")
		// header.Name = path
		if info.IsDir() {
			header.Name += "/"
		} else {
			header.Method = zip.Deflate
		}

		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}

		if !info.IsDir() {
			file, err := os.Open(path)
			if err != nil {
				return err
			}
			defer file.Close()
			_, err = io.Copy(writer, file)
		}
		return err
	})

	return err
}

func ReadFile(filePath string) []byte {
	f, err := os.Open(filePath)
	if err != nil {
		fmt.Println("read file fail", err)
		return nil
	}
	defer f.Close()

	fd, err := ioutil.ReadAll(f)
	if err != nil {
		fmt.Println("read to fd fail", err)
		return nil
	}

	return fd
}

func RemoveRepeatedCode(arr []string) (newArr []string) {
	newArr = make([]string, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i] == arr[j] {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}