package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/jinzhu/gorm"
	"math/rand"
	"reflect"
	"strconv"
	"strings"
	"syscall"
	"time"
	"unsafe"
)

type HisApiController struct {
	BaseAuthAPIController
}

func HisManagerApiRegistRouters() {

	beego.Router("/api/hispatient/list", &HisApiController{}, "get:GetHisPatientList")
	beego.Router("/api/hispatient/get", &HisApiController{}, "get:GetHisPatientInfo")
	beego.Router("/api/hisprescription/config", &HisApiController{}, "get:GetHisPrescriptionConfig")

	beego.Router("/api/hisprescription/delete", &HisApiController{}, "post:DeletePrescription")
	beego.Router("/api/advice/delete", &HisApiController{}, "post:DeleteDoctorAdvice")
	beego.Router("/api/project/delete", &HisApiController{}, "post:DeleteProject")
	beego.Router("/api/addition_charge/delete", &HisApiController{}, "post:DeleteAddition")

	beego.Router("/api/hisprescription/list", &HisApiController{}, "get:GetHisPrescriptionList")
	beego.Router("/api/hisprescription/info", &HisApiController{}, "get:GetHisPrescriptionInfo")

	beego.Router("/api/hisprescription/create", &HisApiController{}, "post:CreateHisPrescription")
	beego.Router("/api/hisprescription/edit", &HisApiController{}, "post:EditHisPrescription")

	beego.Router("/api/doctorworkstation/casehistory/list", &HisApiController{}, "get:GetHisPatientCaseHistoryList")
	beego.Router("/api/doctorworkstation/casehistory/get", &HisApiController{}, "get:GetHisPatientCaseHistory")
	beego.Router("/api/doctorworkstation/casehistory/create", &HisApiController{}, "get:CreateHisPatientCaseHistory")
	beego.Router("/api/doctorworkstation/casehistorytemplate/create", &HisApiController{}, "get:CreateCaseHistoryTemplate")
	beego.Router("/api/doctorworkstation/casehistorytemplate/get", &HisApiController{}, "get:GetCaseHistoryTemplate")

	beego.Router("/api/hisorder/list", &HisApiController{}, "get:GetHisOrderList")
	beego.Router("/api/hisorder/get", &HisApiController{}, "get:GetHisOrder")

	beego.Router("/api/register/get", &HisApiController{}, "get:GetRegisterInfo")
	beego.Router("/api/upload/get", &HisApiController{}, "get:GetUploadInfo")

	beego.Router("/api/refund/post", &HisApiController{}, "post:Refund")

	beego.Router("/api/medicalinsurance/config", &HisApiController{}, "get:GetMedicalInsuranceConfig")

	beego.Router("/api/doctor/list", &HisApiController{}, "get:GetAdminUsers")

	//beego.Router("/api/medicalinsurance/config", &HisApiController{}, "get:GetMedicalInsuranceConfig")

	//新增附加费用
	//beego.Router("/api/his/additionalcharge", &HisApiController{}, "Post:AdditionalCharge")

	//beego.Router("/api/additionalcharge/get", &HisApiController{}, "Get:GetAdditionalcharge")

	beego.Router("/api/hisprescription/get", &DialysisApiController{}, "Get:GetLastOrNextHisPrescription")

	beego.Router("/api/callhisprescription/get", &DialysisApiController{}, "Get:GetCallHisPrescription")

	beego.Router("/api/dayprescription/get", &HisApiController{}, "get:GetHisDayPrescription")

	beego.Router("/api/charge/list", &HisApiController{}, "get:GetHisChargePatientList")
	beego.Router("/api/charge/info", &HisApiController{}, "get:GetHisChargePatientInfo")

	beego.Router("/api/unregister/list", &HisApiController{}, "get:GetHisUnRegisterPatientList")

	beego.Router("/api/orderdetail/get", &HisApiController{}, "get:GetAllOrderDetail")
	beego.Router("/api/orderdetaicollect/get", &HisApiController{}, "get:GetAllOrderDetailCollect")

}

func (c *HisApiController) Sscard() {
	//r := CardInit()
	//if r == 0 {
	//	GetBaseInfo()
	//}
	//c.ServeSuccessJSON(map[string]interface{}{
	//	"list": "11",
	//})

}

func GetBaseInfo() error {
	//handle := syscall.MustLoadDLL("SSCard.dll")
	//ReadCardBas := handle.MustFindProc("ReadCardBas")
	//
	//str := make([]byte, 256)
	//str1 := make([]byte, 256)
	//r, _, ferr := ReadCardBas.Call((uintptr)(unsafe.Pointer(&str[0])), IntPtr(1024), (uintptr)(unsafe.Pointer(&str1[0])), IntPtr(1024))
	//if ferr != nil {
	//	fmt.Println("ReadCardBas 报错", ferr.Error())
	//	return ferr
	//}
	//
	//fmt.Println(string(str))
	//
	//fmt.Println(r)
	return 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 0
}

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

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

func (c *HisApiController) GetHisPatientList() {
	types, _ := c.GetInt64("type", 0)
	record_date := c.GetString("record_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")

	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminInfo := c.GetAdminUserInfo()
	patients, _ := service.GetScheduleHisPatientList(adminInfo.CurrentOrgId, "", recordDateTime)
	patients_two, _ := service.GetHisPatientList(adminInfo.CurrentOrgId, "", recordDateTime)
	patients = append(patients, patients_two...)
	patients = RemoveRepeatedPatient(patients)

	var total_one int64
	var total_two int64

	//获取当前用户的信息
	adminUserInfo, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, adminInfo.AdminUser.Id)
	doctors, _ := service.GetHisAdminUserDoctors(adminInfo.CurrentOrgId)
	//获取所有科室信息
	department, _ := service.GetAllDepartMent(adminInfo.CurrentOrgId)

	for _, item := range patients {

		if item.HisPrescription == nil || len(item.HisPrescription) <= 0 {
			total_one = total_one + 1
		}
		if item.HisPrescription != nil && len(item.HisPrescription) > 0 {
			total_two = total_two + 1
		}
	}

	if types == 0 {
		c.ServeSuccessJSON(map[string]interface{}{
			"list":       patients,
			"total_one":  total_one,
			"total_two":  total_two,
			"info":       adminUserInfo,
			"doctors":    doctors,
			"department": department,
		})

	} else if types == 1 { //未就诊
		var patientsOne []*service.Patients
		for _, item := range patients {
			if item.HisPrescription == nil || len(item.HisPrescription) <= 0 {
				patientsOne = append(patientsOne, item)
			}
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"list":       patientsOne,
			"total_one":  total_one,
			"total_two":  total_two,
			"info":       adminUserInfo,
			"doctors":    doctors,
			"department": department,
		})

	} else if types == 2 { //已就诊
		var patientsTwo []*service.Patients
		for _, item := range patients {

			if item.HisPrescription != nil && len(item.HisPrescription) > 0 {
				patientsTwo = append(patientsTwo, item)
			}
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"list":       patientsTwo,
			"total_one":  total_one,
			"total_two":  total_two,
			"info":       adminUserInfo,
			"doctors":    doctors,
			"department": department,
		})
	}

}
func (c *HisApiController) GetHisPatientInfo() {
	patient_id, _ := c.GetInt64("patient_id")
	record_date := c.GetString("record_date")
	number := c.GetString("number")

	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")

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

	startTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	if err != nil {

	}
	startRecordDateTime := startTime.Unix()

	endTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	if err != nil {

	}
	endRecordDateTime := endTime.Unix()

	admin := c.GetAdminUserInfo()
	his_patient_info, _ := service.GetHisPatientInfo(admin.CurrentOrgId, patient_id, recordDateTime)
	xt_patient_info, _ := service.GetXTPatientInfo(admin.CurrentOrgId, patient_id)
	prescriptions, _ := service.GetHisPrescription(admin.CurrentOrgId, patient_id, recordDateTime)
	monthPrescriptions, _ := service.GetMonthHisPrescriptionTwo(admin.CurrentOrgId, patient_id, startRecordDateTime, endRecordDateTime)
	case_history, _ := service.GetHisPatientCaseHistoryInfo(admin.CurrentOrgId, patient_id, recordDateTime)
	patientPrescriptionInfo, _ := service.FindPatientPrescriptionInfo(admin.CurrentOrgId, patient_id, recordDateTime)
	order, _ := service.GetHisOrder(admin.CurrentOrgId, number, patient_id)

	doctors, _ := service.GetHisAdminUserDoctors(admin.CurrentOrgId)
	//获取所有科室信息
	department, _ := service.GetAllDepartMent(admin.CurrentOrgId)

	c.ServeSuccessJSON(map[string]interface{}{
		"his_info":            his_patient_info,
		"xt_info":             xt_patient_info,
		"prescription":        prescriptions,
		"case_history":        case_history,
		"info":                patientPrescriptionInfo,
		"month_prescriptions": monthPrescriptions,
		"order":               order,
		"doctors":             doctors,
		"department":          department,
	})
	return

}
func (c *HisApiController) GetHisPrescriptionConfig() {
	adminInfo := c.GetAdminUserInfo()
	//获取医嘱模版
	advices, _ := service.FindAllHisAdviceTemplate(adminInfo.CurrentOrgId)
	//获取所有基础药
	drugs, _ := service.GetAllDrugLibList(adminInfo.CurrentOrgId)
	drugways, _, _ := service.GetDrugWayDics(adminInfo.CurrentOrgId)
	efs, _, _ := service.GetExecutionFrequencyDics(adminInfo.CurrentOrgId)
	doctors, _ := service.GetHisAdminUserDoctors(adminInfo.CurrentOrgId)
	//获取所有科室信息
	department, _ := service.GetAllDepartMent(adminInfo.CurrentOrgId)

	//获取诊断信息

	sick, _ := service.FindAllSick(adminInfo.CurrentOrgId)

	diagnose, _ := service.FindAllDiagnose(adminInfo.CurrentOrgId)

	additions, _ := service.FindAllAddition(adminInfo.CurrentOrgId)

	c.ServeSuccessJSON(map[string]interface{}{
		"drugs":            drugs,
		"advices_template": advices,
		"drugways":         drugways,
		"efs":              efs,
		"doctors":          doctors,
		"department":       department,
		"sick":             sick,
		"additions":        additions,
		"diagnose":         diagnose,
	})
}
func (c *HisApiController) CreateHisPrescription() {
	record_date := c.GetString("record_date")
	patient_id, _ := c.GetInt64("patient_id")
	reg_type, _ := c.GetInt64("reg_type")
	diagnose, _ := c.GetInt64("diagnose")
	sick_type, _ := c.GetInt64("sick_type")
	sick_history := c.GetString("sick_history")
	doctor_id, _ := c.GetInt64("doctor", 0)
	department, _ := c.GetInt64("department", 0)
	his_patient_id, _ := c.GetInt64("his_patient_id")
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

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

	role, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, doctor_id)

	info, _ := service.FindPatientPrescriptionInfo(adminInfo.CurrentOrgId, patient_id, recordDateTime)
	var hpInfo models.HisPrescriptionInfo
	if info.ID == 0 {
		var randNum int
		randNum = rand.Intn(10000) + 1000
		timestamp := time.Now().Unix()
		tempTime := time.Unix(timestamp, 0)
		timeFormat := tempTime.Format("20060102150405")
		p_number := timeFormat + strconv.FormatInt(int64(randNum), 10) + strconv.FormatInt(int64(adminInfo.CurrentOrgId), 10) + strconv.FormatInt(int64(patient_id), 10)

		hpInfo = models.HisPrescriptionInfo{
			UserOrgId:          adminInfo.CurrentOrgId,
			RecordDate:         theTime.Unix(),
			PatientId:          patient_id,
			Status:             1,
			Ctime:              time.Now().Unix(),
			Mtime:              time.Now().Unix(),
			Creator:            adminInfo.AdminUser.Id,
			Modifier:           adminInfo.AdminUser.Id,
			Diagnosis:          diagnose,
			SickHistory:        sick_history,
			Departments:        department,
			RegisterType:       reg_type,
			PrescriptionNumber: p_number,
			PrescriptionStatus: 1,
			Doctor:             role.UserName,
			DoctorId:           doctor_id,
			SickType:           sick_type,
		}
		service.SavePatientPrescriptionInfo(hpInfo)

	} else {
		hpInfo = models.HisPrescriptionInfo{
			ID:                 info.ID,
			UserOrgId:          adminInfo.CurrentOrgId,
			RecordDate:         info.RecordDate,
			PatientId:          info.PatientId,
			Status:             1,
			Ctime:              info.Ctime,
			Mtime:              time.Now().Unix(),
			Creator:            info.Creator,
			Modifier:           adminInfo.AdminUser.Id,
			Diagnosis:          diagnose,
			SickHistory:        sick_history,
			Departments:        department,
			RegisterType:       reg_type,
			PrescriptionNumber: info.PrescriptionNumber,
			Doctor:             role.UserName,
			PrescriptionStatus: info.PrescriptionStatus,
			DoctorId:           doctor_id,
			SickType:           sick_type,
		}
		service.SavePatientPrescriptionInfo(hpInfo)
	}

	if dataBody["prescriptions"] != nil && reflect.TypeOf(dataBody["prescriptions"]).String() == "[]interface {}" {
		prescriptions, _ := dataBody["prescriptions"].([]interface{})

		if len(prescriptions) > 0 {
			for _, item := range prescriptions {
				items := item.(map[string]interface{})
				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["id"].(float64))

				if items["type"] == nil || reflect.TypeOf(items["type"]).String() != "float64" {
					utils.ErrorLog("type")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				types := int64(items["type"].(float64))

				if items["pre_time"] == nil || reflect.TypeOf(items["pre_time"]).String() != "string" {
					utils.ErrorLog("pre_time")
				}
				preTime, _ := items["pre_time"].(string)
				timeLayout := "2006-01-02"
				loc, _ := time.LoadLocation("Local")
				theTime2, err := time.ParseInLocation(timeLayout+" 15:04", preTime, loc)
				if err != nil {
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				pTime := theTime2.Unix()

				ctime := time.Now().Unix()
				prescription := &models.HisPrescription{
					ID:                 id,
					PatientId:          patient_id,
					UserOrgId:          adminInfo.CurrentOrgId,
					RecordDate:         recordDateTime,
					Ctime:              ctime,
					Mtime:              ctime,
					Type:               types,
					Modifier:           adminInfo.AdminUser.Id,
					Creator:            adminInfo.AdminUser.Id,
					Status:             1,
					Doctor:             role.UserName,
					HisPatientId:       his_patient_id,
					OrderStatus:        1,
					BatchNumber:        "",
					PrescriptionNumber: hpInfo.PrescriptionNumber,
					PreTime:            pTime,
				}
				service.SaveHisPrescription(prescription)

				//更改患者挂号状态
				_, err2 := service.UpdateHisPatientIsReturn(patient_id, recordDateTime, adminInfo.CurrentOrgId)
				fmt.Println("更改失败", err2)
				if items["advices"] != nil && reflect.TypeOf(items["advices"]).String() == "[]interface {}" {
					advices := items["advices"].([]interface{})
					//group := service.GetMaxAdviceGroupID(adminInfo.CurrentOrgId)
					groupNo := int64(0)
					ctime := time.Now().Unix()
					mtime := ctime
					if len(advices) > 0 {
						for _, advice := range advices {
							var s models.HisDoctorAdviceInfo
							s.PrescriptionId = prescription.ID
							s.AdviceType = 2
							s.AdviceDoctor = adminInfo.AdminUser.Id
							s.StopState = 2
							s.ExecutionState = 2
							s.AdviceDate = recordDateTime
							s.Status = 1
							s.UserOrgId = adminInfo.CurrentOrgId
							s.RecordDate = recordDateTime
							s.StartTime = prescription.PreTime
							s.Groupno = groupNo
							s.CreatedTime = ctime
							s.UpdatedTime = mtime
							s.PatientId = patient_id
							s.HisPatientId = his_patient_id
							errcode := c.setAdviceWithJSON(&s, advice.(map[string]interface{}))
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateHisDoctorAdvice(&s)
							var randNum int
							randNum = rand.Intn(10000) + 1000
							timestamp := time.Now().Unix()
							tempTime := time.Unix(timestamp, 0)
							timeFormat := tempTime.Format("20060102150405")
							s.FeedetlSn = timeFormat + strconv.FormatInt(int64(randNum), 10) + "-" + "1" + "-" + strconv.FormatInt(s.ID, 10)
							service.CreateHisDoctorAdvice(&s)

						}
					}
				}
				if items["project"] != nil && reflect.TypeOf(items["project"]).String() == "[]interface {}" {
					projects := items["project"].([]interface{})
					if len(projects) > 0 {
						for _, project := range projects {
							var p models.HisPrescriptionProject
							p.PrescriptionId = prescription.ID
							p.Ctime = time.Now().Unix()
							p.Mtime = time.Now().Unix()
							p.PatientId = patient_id
							p.RecordDate = recordDateTime
							p.UserOrgId = adminInfo.CurrentOrgId
							p.HisPatientId = his_patient_id
							p.Status = 1
							errcode := c.setProjectWithJSON(&p, project.(map[string]interface{}))
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateHisProjectTwo(&p)
							var randNum int
							randNum = rand.Intn(10000) + 1000
							timestamp := time.Now().Unix()
							tempTime := time.Unix(timestamp, 0)
							timeFormat := tempTime.Format("20060102150405")
							p.FeedetlSn = timeFormat + strconv.FormatInt(int64(randNum), 10) + "-" + "2" + "-" + strconv.FormatInt(p.ID, 10)
							service.SaveHisProjectTwo(&p)

						}
					}
				}
				if items["addition"] != nil && reflect.TypeOf(items["addition"]).String() == "[]interface {}" {
					addition := items["addition"].([]interface{})
					//group := service.GetMaxAdviceGroupID(adminInfo.CurrentOrgId)
					ctime := time.Now().Unix()
					mtime := ctime
					if len(addition) > 0 {
						for _, item := range addition {
							var s models.HisAdditionalCharge
							s.PrescriptionId = prescription.ID
							s.Status = 1
							s.UserOrgId = adminInfo.CurrentOrgId
							s.RecordDate = recordDateTime
							s.CreatedTime = ctime
							s.UpdatedTime = mtime
							s.PatientId = patient_id
							s.HisPatientId = his_patient_id
							errcode := c.setAddtionWithJSON(&s, item.(map[string]interface{}), adminInfo.CurrentOrgId)
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateAdditionalCharge(&s)
							var randNum int
							randNum = rand.Intn(10000) + 1000
							timestamp := time.Now().Unix()
							tempTime := time.Unix(timestamp, 0)
							timeFormat := tempTime.Format("20060102150405")
							s.FeedetlSn = timeFormat + strconv.FormatInt(int64(randNum), 10) + "-" + "3" + "-" + strconv.FormatInt(s.ID, 10)
							service.CreateAdditionalCharge(&s)

						}
					}
				}

			}
		}
	}
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "保存成功",
		})
		return

	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (c *HisApiController) EditHisPrescription() {
	record_date := c.GetString("record_date")
	patient_id, _ := c.GetInt64("patient_id")
	reg_type, _ := c.GetInt64("reg_type")
	diagnose, _ := c.GetInt64("diagnose")
	sick_type, _ := c.GetInt64("sick_type")
	sick_history := c.GetString("sick_history")
	doctor_id, _ := c.GetInt64("doctor", 0)
	department, _ := c.GetInt64("department", 0)
	his_patient_id, _ := c.GetInt64("his_patient_id")
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

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

	role, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, doctor_id)

	info, _ := service.FindPatientPrescriptionInfo(adminInfo.CurrentOrgId, patient_id, recordDateTime)
	var hpInfo models.HisPrescriptionInfo
	if info.ID == 0 {
		var randNum int
		randNum = rand.Intn(10000) + 1000
		timestamp := time.Now().Unix()
		tempTime := time.Unix(timestamp, 0)
		timeFormat := tempTime.Format("20060102150405")
		p_number := timeFormat + strconv.FormatInt(int64(randNum), 10) + strconv.FormatInt(int64(adminInfo.CurrentOrgId), 10) + strconv.FormatInt(int64(patient_id), 10)

		hpInfo = models.HisPrescriptionInfo{
			UserOrgId:          adminInfo.CurrentOrgId,
			RecordDate:         theTime.Unix(),
			PatientId:          patient_id,
			Status:             1,
			Ctime:              time.Now().Unix(),
			Mtime:              time.Now().Unix(),
			Creator:            adminInfo.AdminUser.Id,
			Modifier:           adminInfo.AdminUser.Id,
			Diagnosis:          diagnose,
			SickHistory:        sick_history,
			Departments:        department,
			RegisterType:       reg_type,
			PrescriptionNumber: p_number,
			PrescriptionStatus: 1,
			Doctor:             role.UserName,
			DoctorId:           doctor_id,
			SickType:           sick_type,
		}
		service.SavePatientPrescriptionInfo(hpInfo)

	} else {
		hpInfo = models.HisPrescriptionInfo{
			ID:                 info.ID,
			UserOrgId:          adminInfo.CurrentOrgId,
			RecordDate:         info.RecordDate,
			PatientId:          info.PatientId,
			Status:             1,
			Ctime:              info.Ctime,
			Mtime:              time.Now().Unix(),
			Creator:            info.Creator,
			Modifier:           adminInfo.AdminUser.Id,
			Diagnosis:          diagnose,
			SickHistory:        sick_history,
			Departments:        department,
			RegisterType:       reg_type,
			PrescriptionNumber: info.PrescriptionNumber,
			Doctor:             role.UserName,
			PrescriptionStatus: info.PrescriptionStatus,
			DoctorId:           doctor_id,
			SickType:           sick_type,
		}
		service.SavePatientPrescriptionInfo(hpInfo)
	}

	if dataBody["prescriptions"] != nil && reflect.TypeOf(dataBody["prescriptions"]).String() == "[]interface {}" {
		prescriptions, _ := dataBody["prescriptions"].([]interface{})

		if len(prescriptions) > 0 {
			for _, item := range prescriptions {
				items := item.(map[string]interface{})
				if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
					utils.ErrorLog("id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				id := int64(items["id"].(float64))

				if items["type"] == nil || reflect.TypeOf(items["type"]).String() != "float64" {
					utils.ErrorLog("type")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				types := int64(items["type"].(float64))

				historyPrescription, _ := service.GetHisPrescriptionByID(adminInfo.CurrentOrgId, id)

				ctime := time.Now().Unix()

				prescription := &models.HisPrescription{
					ID:                 id,
					PatientId:          patient_id,
					UserOrgId:          adminInfo.CurrentOrgId,
					RecordDate:         recordDateTime,
					Ctime:              ctime,
					Mtime:              ctime,
					Type:               types,
					Modifier:           adminInfo.AdminUser.Id,
					Creator:            adminInfo.AdminUser.Id,
					Status:             1,
					Doctor:             role.UserName,
					HisPatientId:       his_patient_id,
					OrderStatus:        1,
					BatchNumber:        "",
					PrescriptionNumber: hpInfo.PrescriptionNumber,
				}

				if historyPrescription.ID > 0 {
					prescription.PreTime = historyPrescription.PreTime
				}

				service.SaveHisPrescription(prescription)

				if items["advices"] != nil && reflect.TypeOf(items["advices"]).String() == "[]interface {}" {
					advices := items["advices"].([]interface{})
					//group := service.GetMaxAdviceGroupID(adminInfo.CurrentOrgId)
					groupNo := int64(0)
					ctime := time.Now().Unix()
					mtime := ctime
					if len(advices) > 0 {
						for _, advice := range advices {
							var s models.HisDoctorAdviceInfo
							s.PrescriptionId = prescription.ID
							s.AdviceType = 2
							s.AdviceDoctor = adminInfo.AdminUser.Id
							s.StopState = 2
							s.ExecutionState = 2
							s.AdviceDate = recordDateTime
							s.Status = 1
							s.UserOrgId = adminInfo.CurrentOrgId
							s.RecordDate = recordDateTime
							s.StartTime = prescription.PreTime
							s.Groupno = groupNo
							s.CreatedTime = ctime
							s.UpdatedTime = mtime
							s.PatientId = patient_id
							s.HisPatientId = his_patient_id
							errcode := c.setAdviceWithJSONTwo(&s, advice.(map[string]interface{}))
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateHisDoctorAdvice(&s)

						}
					}
				}
				if items["project"] != nil && reflect.TypeOf(items["project"]).String() == "[]interface {}" {
					projects := items["project"].([]interface{})
					if len(projects) > 0 {
						for _, project := range projects {
							var p models.HisPrescriptionProject
							p.PrescriptionId = prescription.ID
							p.Ctime = time.Now().Unix()
							p.Mtime = time.Now().Unix()
							p.PatientId = patient_id
							p.RecordDate = recordDateTime
							p.UserOrgId = adminInfo.CurrentOrgId
							p.HisPatientId = his_patient_id
							p.Status = 1
							errcode := c.setProjectWithJSONTwo(&p, project.(map[string]interface{}))
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateHisProjectTwo(&p)

						}
					}
				}
				if items["addition"] != nil && reflect.TypeOf(items["addition"]).String() == "[]interface {}" {
					addition := items["addition"].([]interface{})
					//group := service.GetMaxAdviceGroupID(adminInfo.CurrentOrgId)
					ctime := time.Now().Unix()
					mtime := ctime
					if len(addition) > 0 {
						for _, item := range addition {
							var s models.HisAdditionalCharge
							s.PrescriptionId = prescription.ID
							s.Status = 1
							s.UserOrgId = adminInfo.CurrentOrgId
							s.RecordDate = recordDateTime
							s.CreatedTime = ctime
							s.UpdatedTime = mtime
							s.PatientId = patient_id
							s.HisPatientId = his_patient_id
							errcode := c.setAddtionWithJSONTwo(&s, item.(map[string]interface{}), adminInfo.CurrentOrgId)
							if errcode > 0 {
								c.ServeFailJSONWithSGJErrorCode(errcode)
								return
							}
							service.CreateAdditionalCharge(&s)
						}
					}
				}

			}
		}
	}
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "保存成功",
		})
		return

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

func (c *HisApiController) DeletePrescription() {
	prescription_id, _ := c.GetInt64("id")
	//TODO 需要判断是否已经结算
	err := service.DelelteHisPrescription(prescription_id, c.GetAdminUserInfo().CurrentOrgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}

func (c *HisApiController) DeleteDoctorAdvice() {
	id, _ := c.GetInt64("id")
	//TODO 需要判断是否已经结算
	err := service.DelelteDoctorAdvice(id, c.GetAdminUserInfo().CurrentOrgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}

func (c *HisApiController) DeleteProject() {
	id, _ := c.GetInt64("id")
	//TODO 需要判断是否已经结算
	err := service.DelelteProject(id, c.GetAdminUserInfo().CurrentOrgId)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
		return
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}

func (c *HisApiController) CreateHisAdditionalCharge() {
	his_patient_id, _ := c.GetInt64("his_patient_id")
	patient_id, _ := c.GetInt64("patient_id")
	record_date := c.GetString("record_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	adminInfo := c.GetAdminUserInfo()
	recordDateTime := theTime.Unix()
	dataBody := make(map[string]interface{}, 0)
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var additions []*models.HisAdditionalCharge
	if dataBody["addition"] != nil && reflect.TypeOf(dataBody["addition"]).String() == "[]interface {}" {
		additions, _ := dataBody["addition"].([]interface{})
		if len(additions) > 0 {
			for _, item := range additions {
				items := item.(map[string]interface{})

				if items["item_id"] == nil || reflect.TypeOf(items["item_id"]).String() != "float64" {
					utils.ErrorLog("item_id")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				item_id := int64(items["item_id"].(float64))

				if items["item_name"] == nil || reflect.TypeOf(items["item_name"]).String() != "string" {
					utils.ErrorLog("item_name")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				item_name := items["item_name"].(string)

				if items["price"] == nil || reflect.TypeOf(items["price"]).String() != "string" {
					utils.ErrorLog("price")
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
					return
				}
				price, _ := strconv.ParseFloat(items["price"].(string), 64)

				ctime := time.Now().Unix()
				additional := &models.HisAdditionalCharge{
					PatientId:    patient_id,
					HisPatientId: his_patient_id,
					UserOrgId:    adminInfo.CurrentOrgId,
					RecordDate:   recordDateTime,
					CreatedTime:  ctime,
					UpdatedTime:  ctime,
					Modifier:     adminInfo.AdminUser.Id,
					Creator:      adminInfo.AdminUser.Id,
					Price:        price,
					ItemName:     item_name,
					ItemId:       item_id,
					Status:       1,
				}
				additions = append(additions, additional)
			}
		}
	}
	for _, item := range additions {
		service.CreateAddtionalCharge(item)
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"msg": "创建成功",
	})
}

func (c *HisApiController) CreateHisPatientCaseHistory() {

	blood_fat := c.GetString("blood_fat")
	bloodfatfloat, _ := strconv.ParseFloat(blood_fat, 64)
	//fmt.Println("33333333", bloodfatfloat)
	blood_sugar := c.GetString("blood_sugar")
	bloodsugarfloat, _ := strconv.ParseFloat(blood_sugar, 64)
	fmt.Println(bloodsugarfloat)
	chief_conplaint := c.GetString("chief_conplaint")

	dbp := c.GetString("dbp")
	dbpfloat, _ := strconv.ParseFloat(dbp, 64)
	delivery_way, _ := c.GetInt64("delivery_way")
	diagnostic := c.GetString("diagnostic")
	fmt.Println("diagnostic", diagnostic)
	family_history := c.GetString("family_history")
	fmt.Println(family_history)
	height := c.GetString("height")
	history_of_present_illness := c.GetString("history_of_present_illness")
	is_infect, _ := c.GetInt64("is_infect")
	fmt.Println("is", is_infect)
	past_history := c.GetString("past_history")
	patient_id, _ := c.GetInt64("patient_id")
	his_patient_id, _ := c.GetInt64("his_patient_id")
	fmt.Println("patient_id", patient_id)
	personal_history := c.GetString("personal_history")
	pulse := c.GetString("pulse")
	pulsefloat, _ := strconv.ParseFloat(pulse, 64)
	sbp := c.GetString("sbp")
	sbpfloat, _ := strconv.ParseFloat(sbp, 64)
	heightfloat, _ := strconv.ParseFloat(height, 64)
	sicktype := c.GetString("sick_type")
	fmt.Println("sicketype", sicktype)
	sick_type, _ := strconv.ParseInt(sicktype, 10, 64)
	symptom := c.GetString("symptom")
	sick_date := c.GetString("sick_date")
	temperatures := c.GetString("temperature")
	fmt.Println("temperatures", temperatures)
	temperature, _ := strconv.ParseFloat(temperatures, 64)
	record_date := c.GetString("record_date")
	breathing := c.GetString("breathing")
	doctor_advice := c.GetString("doctor_advice")
	remark := c.GetString("remark")
	breathingfloat, _ := strconv.ParseFloat(breathing, 64)
	fmt.Println("breathingfloat", breathingfloat)
	sick, _ := c.GetInt64("sick")
	diagnose, _ := c.GetInt64("diagnose")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	fmt.Println("recordDataTime", recordDateTime)
	sickTime, err := time.ParseInLocation(timeLayout+" 15:04:05", sick_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	sickTimes := sickTime.Unix()
	ctime := time.Now().Unix()
	caseHistory := models.HisPatientCaseHistory{
		HisPatientId:            his_patient_id,
		PatientId:               patient_id,
		Temperature:             temperature,
		BloodSugar:              bloodsugarfloat,
		Pulse:                   pulsefloat,
		Sbp:                     sbpfloat,
		Dbp:                     dbpfloat,
		Height:                  heightfloat,
		BloodFat:                bloodfatfloat,
		SickType:                sick_type,
		Symptom:                 symptom,
		SickDate:                sickTimes,
		IsInfect:                is_infect,
		HistoryOfPresentIllness: history_of_present_illness,
		PastHistory:             past_history,
		Doctor:                  c.GetAdminUserInfo().AdminUser.Id,
		ChiefConplaint:          chief_conplaint,
		PersonalHistory:         personal_history,
		FamilyHistory:           family_history,
		Diagnostic:              diagnostic,
		UserOrgId:               c.GetAdminUserInfo().CurrentOrgId,
		Status:                  1,
		Ctime:                   ctime,
		Mtime:                   ctime,
		RecordDate:              recordDateTime,
		DeliveryWay:             delivery_way,
		Breathing:               breathingfloat,
		DoctorAdvice:            doctor_advice,
		Remark:                  remark,
		Sick:                    sick,
		Diagnose:                diagnose,
	}

	err = service.SaveHisPatientCaseHistory(&caseHistory)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"caseHistory": caseHistory,
	})
	return

	//查询该患者是否有病历
	//_, errcode := service.GetHisPatientCaseHistoryById(his_patient_id)
	//if errcode == gorm.ErrRecordNotFound {
	//	err = service.SaveHisPatientCaseHistory(caseHistory)
	//	if err != nil {
	//		c.ServeSuccessJSON(map[string]interface{}{
	//			"msg": "保存成功",
	//		})
	//	}
	//} else if errcode == nil {
	//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
	//	return
	//}

}
func (c *HisApiController) GetHisPatientCaseHistoryList() {
	patient_id, _ := c.GetInt64("patient_id", 0)
	adminUser := c.GetAdminUserInfo()
	caseHistorys, _ := service.GetHisPatientCaseHistoryList(adminUser.CurrentOrgId, patient_id)
	c.ServeSuccessJSON(map[string]interface{}{
		"list": caseHistorys,
	})

}
func (c *HisApiController) GetHisPatientCaseHistory() {
	record_date, _ := c.GetInt64("record_date", 0)
	patient_id, _ := c.GetInt64("patient_id", 0)
	admin := c.GetAdminUserInfo()
	info, _ := service.GetHisPatientInfo(admin.CurrentOrgId, patient_id, record_date)
	case_history, _ := service.GetHisPatientCaseHistoryInfo(admin.CurrentOrgId, patient_id, record_date)
	c.ServeSuccessJSON(map[string]interface{}{
		"info":         info,
		"case_history": case_history,
	})

}
func (c *HisApiController) CreateCaseHistoryTemplate() {
	template_name := c.GetString("template_name")
	fmt.Println("template_name22222222222222", template_name)
	template_remark := c.GetString("template_remark")
	doctor := c.GetAdminUserInfo().AdminUser.Id
	diagnostic := c.GetString("diagnostic")
	chief_conplaint := c.GetString("chief_conplain")
	history_of_present_illness := c.GetString("history_of_present_illness")
	past_history := c.GetString("past_history")
	personal_history := c.GetString("personal_history")
	family_history := c.GetString("family_history")
	user_name := c.GetString("user_name")
	doctor_advice := c.GetString("doctor_advice")
	remark := c.GetString("remark")
	//record_date := c.GetString("record_date")
	//fmt.Println("record_date--------",record_date)
	//timeLayout := "2006-01-02"
	//loc, _ := time.LoadLocation("Local")
	//
	//theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	//if err != nil {
	//	c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//	return
	//}
	//recordDateTime := theTime.Unix()

	ctime := time.Now().Unix()

	template := models.HisCaseHistoryTemplate{
		HistoryOfPresentIllness: history_of_present_illness,
		PastHistory:             past_history,
		ChiefConplaint:          chief_conplaint,
		PersonalHistory:         personal_history,
		FamilyHistory:           family_history,
		Diagnostic:              diagnostic,
		UserOrgId:               c.GetAdminUserInfo().CurrentOrgId,
		Status:                  1,
		Ctime:                   ctime,
		Mtime:                   ctime,
		RecordDate:              time.Now().Unix(),
		TemplateName:            template_name,
		TemplateRemark:          template_remark,
		Creator:                 doctor,
		Modifier:                doctor,
		UserName:                user_name,
		DoctorAdvice:            doctor_advice,
		Remark:                  remark,
	}

	err := service.SaveHisPatientCaseHistoryTemplate(template)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "保存成功",
		})

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

}
func (c *HisApiController) GetCaseHistoryTemplate() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := c.GetString("keyword")
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	startTime, _ := 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)
	admin := c.GetAdminUserInfo()
	template, _ := service.GetHisPatientCaseHistoryTemplate(admin.CurrentOrgId, startTime.Unix(), endTime.Unix(), keyword)
	//history, _ := service.GetHisPatientCaseHistory(admin.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"template": template,
		//"history":  history,
	})

}

func (c *HisApiController) setAdviceWithJSONTwo(advice *models.HisDoctorAdviceInfo, json map[string]interface{}) int {

	if json["drug_name"] == nil || reflect.TypeOf(json["drug_name"]).String() != "string" {
		utils.ErrorLog("drug_name")
		return enums.ErrorCodeParamWrong
	}
	adviceName, _ := json["drug_name"].(string)
	if len(adviceName) == 0 {
		utils.ErrorLog("len(advice_name) == 0")
		return enums.ErrorCodeParamWrong
	}
	advice.AdviceName = adviceName
	adviceDesc, _ := json["advice_desc"].(string)
	advice.AdviceDesc = adviceDesc
	if json["drug_spec"] != nil && reflect.TypeOf(json["drug_spec"]).String() == "string" {
		drugSpec, _ := strconv.ParseFloat(json["drug_spec"].(string), 64)
		advice.DrugSpec = drugSpec
	}
	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		advice.Remark = remark
	}
	if json["id"] == nil {
		advice.DrugId = 0
	} else {
		if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
			drug_id := int64(json["id"].(float64))
			advice.DrugId = drug_id
		}
	}
	if json["advice_id"] != nil && reflect.TypeOf(json["advice_id"]).String() == "float64" {
		advice_id := int64(json["advice_id"].(float64))
		advice.ID = advice_id
		if advice.ID > 0 {
			hisAdvice, err := service.GetHisDoctorAdvicesById(advice.ID)
			if err == nil {
				if hisAdvice.ID > 0 {
					advice.ExecutionTime = hisAdvice.ExecutionTime
					advice.ExecutionStaff = hisAdvice.ExecutionStaff
					advice.ExecutionState = hisAdvice.ExecutionState
					advice.CheckTime = hisAdvice.CheckTime
					advice.Checker = hisAdvice.Checker
					advice.CheckState = hisAdvice.CheckState
					advice.StartTime = hisAdvice.StartTime
					advice.FeedetlSn = hisAdvice.FeedetlSn

				}
			}
		}
	}

	//
	//if json["execution_time"] != nil && reflect.TypeOf(json["execution_time"]).String() == "string" {
	//	execution_time, _ := strconv.ParseInt(json["execution_time"].(string), 10,64)
	//	advice.ExecutionTime = execution_time
	//}
	//
	//
	//
	//if json["execution_staff"] != nil && reflect.TypeOf(json["execution_staff"]).String() == "string" {
	//	execution_staff, _ := strconv.ParseInt(json["execution_staff"].(string), 10,64)
	//	advice.ExecutionStaff = execution_staff
	//}
	//
	//
	//
	//if json["execution_state"] != nil && reflect.TypeOf(json["execution_state"]).String() == "string" {
	//	execution_state, _ := strconv.ParseInt(json["execution_state"].(string), 10,64)
	//	advice.ExecutionState = execution_state
	//}
	//
	//
	//if json["check_time"] != nil && reflect.TypeOf(json["check_time"]).String() == "string" {
	//	check_time, _ := strconv.ParseInt(json["check_time"].(string), 10,64)
	//	advice.CheckTime = check_time
	//}
	//
	//
	//if json["check_state"] != nil && reflect.TypeOf(json["check_state"]).String() == "string" {
	//	check_state, _ := strconv.ParseInt(json["check_state"].(string), 10,64)
	//	advice.CheckState = check_state
	//}
	//
	//
	//if json["checker"] != nil && reflect.TypeOf(json["checker"]).String() == "string" {
	//	checker, _ := strconv.ParseInt(json["checker"].(string), 10,64)
	//	advice.Checker = checker
	//}
	//
	//if json["start_time"] != nil && reflect.TypeOf(json["start_time"]).String() == "string" {
	//	start_time, _ := strconv.ParseInt(json["start_time"].(string), 10,64)
	//	advice.StartTime = start_time
	//}

	if json["min_unit"] != nil && reflect.TypeOf(json["min_unit"]).String() == "string" {
		drugSpecUnit, _ := json["min_unit"].(string)
		advice.DrugSpecUnit = drugSpecUnit
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		singleDose, _ := strconv.ParseFloat(json["single_dose"].(string), 64)
		advice.SingleDose = singleDose
	}
	if json["single_dose_unit"] != nil && reflect.TypeOf(json["single_dose_unit"]).String() == "string" {
		singleDoseUnit, _ := json["single_dose_unit"].(string)
		advice.SingleDoseUnit = singleDoseUnit
	}
	if json["prescribing_number"] != nil && reflect.TypeOf(json["prescribing_number"]).String() == "string" {
		prescribingNumber, _ := strconv.ParseFloat(json["prescribing_number"].(string), 64)
		advice.PrescribingNumber = prescribingNumber
	}
	if json["prescribing_number_unit"] != nil && reflect.TypeOf(json["prescribing_number_unit"]).String() == "string" {
		prescribingNumberUnit, _ := json["prescribing_number_unit"].(string)
		advice.PrescribingNumberUnit = prescribingNumberUnit
	}
	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		deliveryWay, _ := json["delivery_way"].(string)
		advice.DeliveryWay = deliveryWay
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		executionFrequency, _ := json["execution_frequency"].(string)
		advice.ExecutionFrequency = executionFrequency
	}

	if json["retail_price"] != nil || reflect.TypeOf(json["retail_price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["retail_price"].(string), 64)
		advice.Price = price
	}
	if json["medical_insurance_number"] != nil || reflect.TypeOf(json["medical_insurance_number"]).String() == "string" {
		med_list_codg, _ := json["medical_insurance_number"].(string)
		advice.MedListCodg = med_list_codg
	}
	if json["day"] != nil || reflect.TypeOf(json["day"]).String() == "float64" {
		day := int64(json["day"].(float64))
		advice.Day = day
	}
	return 0
}

func (c *HisApiController) setProjectWithJSONTwo(project *models.HisPrescriptionProject, json map[string]interface{}) int {
	if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
		id := int64(json["id"].(float64))
		project.ID = id
		historyProject, _ := service.GetHisProjectByID(id)
		project.FeedetlSn = historyProject.FeedetlSn

	}
	if json["project_id"] != nil || reflect.TypeOf(json["project_id"]).String() == "float64" {
		project_id := int64(json["project_id"].(float64))
		project.ProjectId = project_id

	}
	// if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "float64" {
	// 	price := int64(json["price"].(float64))
	// 	formatInt_price := strconv.FormatInt(price, 10)
	// 	float_price, _ := strconv.ParseFloat(formatInt_price, 64)
	// 	project.Price = float_price
	// }
	if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["price"].(string), 64)
		project.Price = price
	}

	if json["total"] != nil && reflect.TypeOf(json["total"]).String() == "string" {
		total, _ := json["total"].(string)
		totals, _ := strconv.ParseInt(total, 10, 64)
		project.Count = totals
	}

	if json["medical_code"] != nil && reflect.TypeOf(json["medical_code"]).String() == "string" {
		medical_code, _ := json["medical_code"].(string)
		project.MedListCodg = medical_code
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		single_dose, _ := json["single_dose"].(string)
		project.SingleDose = single_dose
	}

	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		delivery_way, _ := json["delivery_way"].(string)
		project.DeliveryWay = delivery_way
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		execution_frequency, _ := json["execution_frequency"].(string)
		project.ExecutionFrequency = execution_frequency
	}
	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		project.Remark = remark
	}
	if json["number_days"] != nil && reflect.TypeOf(json["number_days"]).String() == "string" {
		day, _ := json["number_days"].(string)
		project.Day = day
	}

	if json["unit"] != nil && reflect.TypeOf(json["unit"]).String() == "string" {
		unit, _ := json["unit"].(string)
		project.Unit = unit
	}
	return 0
}

func (c *HisApiController) setAddtionWithJSONTwo(additionalCharge *models.HisAdditionalCharge, json map[string]interface{}, org_id int64) int {
	if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
		id := int64(json["id"].(float64))
		historyAddtions, _ := service.GetHisAdditionByID(id)
		additionalCharge.ID = id
		additionalCharge.FeedetlSn = historyAddtions.FeedetlSn
	}
	if json["item_id"] != nil || reflect.TypeOf(json["item_id"]).String() == "float64" {
		item_id := int64(json["item_id"].(float64))
		additionalCharge.ItemId = item_id
		config, _ := service.GetAdditionChargeByID(org_id, item_id)
		if config.ID > 0 {
			if len(config.Code) > 0 {
				additionalCharge.MedListCodg = config.Code
			}
		}
	}
	// if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "float64" {
	// 	price := int64(json["price"].(float64))
	// 	formatInt_price := strconv.FormatInt(price, 10)
	// 	float_price, _ := strconv.ParseFloat(formatInt_price, 64)
	// 	additionalCharge.Price = float_price
	// }

	//if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "float64" {
	//	price := int64(json["price"].(float64))
	//	formatInt_price := strconv.FormatInt(price, 10)
	//	float_price, _ := strconv.ParseFloat(formatInt_price, 64)
	//	additionalCharge.Price = float_price
	//}

	if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["price"].(string), 64)
		additionalCharge.Price = price
	}
	if json["count"] != nil && reflect.TypeOf(json["count"]).String() == "string" {
		count, _ := json["count"].(string)
		counts, _ := strconv.ParseInt(count, 10, 64)
		additionalCharge.Count = counts
	}
	if json["item_name"] != nil && reflect.TypeOf(json["item_name"]).String() == "string" {
		item_name, _ := json["item_name"].(string)
		additionalCharge.ItemName = item_name
	}

	return 0
}

func (c *HisApiController) setAdviceWithJSON(advice *models.HisDoctorAdviceInfo, json map[string]interface{}) int {

	if json["drug_name"] == nil || reflect.TypeOf(json["drug_name"]).String() != "string" {
		utils.ErrorLog("drug_name")
		return enums.ErrorCodeParamWrong
	}
	adviceName, _ := json["drug_name"].(string)
	if len(adviceName) == 0 {
		utils.ErrorLog("len(advice_name) == 0")
		return enums.ErrorCodeParamWrong
	}
	advice.AdviceName = adviceName
	adviceDesc, _ := json["advice_desc"].(string)
	advice.AdviceDesc = adviceDesc
	if json["drug_spec"] != nil && reflect.TypeOf(json["drug_spec"]).String() == "string" {
		drugSpec, _ := strconv.ParseFloat(json["drug_spec"].(string), 64)
		advice.DrugSpec = drugSpec
	}
	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		advice.Remark = remark
	}
	if json["id"] == nil {
		advice.DrugId = 0
	} else {
		if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
			drug_id := int64(json["id"].(float64))
			advice.DrugId = drug_id
		}
	}
	if json["advice_id"] != nil && reflect.TypeOf(json["advice_id"]).String() == "float64" {
		advice_id := int64(json["advice_id"].(float64))
		advice.ID = advice_id
		if advice.ID > 0 {
			hisAdvice, err := service.GetHisDoctorAdvicesById(advice.ID)
			if err == nil {
				if hisAdvice.ID > 0 {
					advice.ExecutionTime = hisAdvice.ExecutionTime
					advice.ExecutionStaff = hisAdvice.ExecutionStaff
					advice.ExecutionState = hisAdvice.ExecutionState
					advice.CheckTime = hisAdvice.CheckTime
					advice.Checker = hisAdvice.Checker
					advice.CheckState = hisAdvice.CheckState
					advice.StartTime = hisAdvice.StartTime

				}
			}
		}
	}

	//
	//if json["execution_time"] != nil && reflect.TypeOf(json["execution_time"]).String() == "string" {
	//	execution_time, _ := strconv.ParseInt(json["execution_time"].(string), 10,64)
	//	advice.ExecutionTime = execution_time
	//}
	//
	//
	//
	//if json["execution_staff"] != nil && reflect.TypeOf(json["execution_staff"]).String() == "string" {
	//	execution_staff, _ := strconv.ParseInt(json["execution_staff"].(string), 10,64)
	//	advice.ExecutionStaff = execution_staff
	//}
	//
	//
	//
	//if json["execution_state"] != nil && reflect.TypeOf(json["execution_state"]).String() == "string" {
	//	execution_state, _ := strconv.ParseInt(json["execution_state"].(string), 10,64)
	//	advice.ExecutionState = execution_state
	//}
	//
	//
	//if json["check_time"] != nil && reflect.TypeOf(json["check_time"]).String() == "string" {
	//	check_time, _ := strconv.ParseInt(json["check_time"].(string), 10,64)
	//	advice.CheckTime = check_time
	//}
	//
	//
	//if json["check_state"] != nil && reflect.TypeOf(json["check_state"]).String() == "string" {
	//	check_state, _ := strconv.ParseInt(json["check_state"].(string), 10,64)
	//	advice.CheckState = check_state
	//}
	//
	//
	//if json["checker"] != nil && reflect.TypeOf(json["checker"]).String() == "string" {
	//	checker, _ := strconv.ParseInt(json["checker"].(string), 10,64)
	//	advice.Checker = checker
	//}
	//
	//if json["start_time"] != nil && reflect.TypeOf(json["start_time"]).String() == "string" {
	//	start_time, _ := strconv.ParseInt(json["start_time"].(string), 10,64)
	//	advice.StartTime = start_time
	//}

	if json["min_unit"] != nil && reflect.TypeOf(json["min_unit"]).String() == "string" {
		drugSpecUnit, _ := json["min_unit"].(string)
		advice.DrugSpecUnit = drugSpecUnit
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		singleDose, _ := strconv.ParseFloat(json["single_dose"].(string), 64)
		advice.SingleDose = singleDose
	}
	if json["single_dose_unit"] != nil && reflect.TypeOf(json["single_dose_unit"]).String() == "string" {
		singleDoseUnit, _ := json["single_dose_unit"].(string)
		advice.SingleDoseUnit = singleDoseUnit
	}
	if json["prescribing_number"] != nil && reflect.TypeOf(json["prescribing_number"]).String() == "string" {
		prescribingNumber, _ := strconv.ParseFloat(json["prescribing_number"].(string), 64)
		advice.PrescribingNumber = prescribingNumber
	}
	if json["prescribing_number_unit"] != nil && reflect.TypeOf(json["prescribing_number_unit"]).String() == "string" {
		prescribingNumberUnit, _ := json["prescribing_number_unit"].(string)
		advice.PrescribingNumberUnit = prescribingNumberUnit
	}
	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		deliveryWay, _ := json["delivery_way"].(string)
		advice.DeliveryWay = deliveryWay
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		executionFrequency, _ := json["execution_frequency"].(string)
		advice.ExecutionFrequency = executionFrequency
	}

	if json["retail_price"] != nil || reflect.TypeOf(json["retail_price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["retail_price"].(string), 64)
		advice.Price = price
	}
	if json["medical_insurance_number"] != nil || reflect.TypeOf(json["medical_insurance_number"]).String() == "string" {
		med_list_codg, _ := json["medical_insurance_number"].(string)
		advice.MedListCodg = med_list_codg
	}
	if json["day"] != nil || reflect.TypeOf(json["day"]).String() == "float64" {
		day := int64(json["day"].(float64))
		advice.Day = day
	}
	return 0
}

func (c *HisApiController) setProjectWithJSON(project *models.HisPrescriptionProject, json map[string]interface{}) int {
	if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
		id := int64(json["id"].(float64))
		project.ID = id
	}
	if json["project_id"] != nil || reflect.TypeOf(json["project_id"]).String() == "float64" {
		project_id := int64(json["project_id"].(float64))
		project.ProjectId = project_id
		fmt.Println(project_id)
		fmt.Println(project.ProjectId)
	}
	// if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "float64" {
	// 	price := int64(json["price"].(float64))
	// 	formatInt_price := strconv.FormatInt(price, 10)
	// 	float_price, _ := strconv.ParseFloat(formatInt_price, 64)
	// 	project.Price = float_price
	// }
	if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["price"].(string), 64)
		project.Price = price
	}

	if json["total"] != nil && reflect.TypeOf(json["total"]).String() == "string" {
		total, _ := json["total"].(string)
		totals, _ := strconv.ParseInt(total, 10, 64)
		project.Count = totals
	}

	if json["medical_code"] != nil && reflect.TypeOf(json["medical_code"]).String() == "string" {
		medical_code, _ := json["medical_code"].(string)
		project.MedListCodg = medical_code
	}
	if json["single_dose"] != nil && reflect.TypeOf(json["single_dose"]).String() == "string" {
		single_dose, _ := json["single_dose"].(string)
		project.SingleDose = single_dose
	}

	if json["delivery_way"] != nil && reflect.TypeOf(json["delivery_way"]).String() == "string" {
		delivery_way, _ := json["delivery_way"].(string)
		project.DeliveryWay = delivery_way
	}
	if json["execution_frequency"] != nil && reflect.TypeOf(json["execution_frequency"]).String() == "string" {
		execution_frequency, _ := json["execution_frequency"].(string)
		project.ExecutionFrequency = execution_frequency
	}
	if json["remark"] != nil && reflect.TypeOf(json["remark"]).String() == "string" {
		remark, _ := json["remark"].(string)
		project.Remark = remark
	}
	if json["number_days"] != nil && reflect.TypeOf(json["number_days"]).String() == "string" {
		day, _ := json["number_days"].(string)
		project.Day = day
	}

	if json["unit"] != nil && reflect.TypeOf(json["unit"]).String() == "string" {
		unit, _ := json["unit"].(string)
		project.Unit = unit
	}
	return 0
}

func (c *HisApiController) setAddtionWithJSON(additionalCharge *models.HisAdditionalCharge, json map[string]interface{}, org_id int64) int {
	if json["id"] != nil || reflect.TypeOf(json["id"]).String() == "float64" {
		id := int64(json["id"].(float64))
		additionalCharge.ID = id
	}
	if json["item_id"] != nil || reflect.TypeOf(json["item_id"]).String() == "float64" {
		item_id := int64(json["item_id"].(float64))
		additionalCharge.ItemId = item_id
		config, _ := service.GetAdditionChargeByID(org_id, item_id)
		if config.ID > 0 {
			if len(config.Code) > 0 {
				additionalCharge.MedListCodg = config.Code
			}
		}
	}
	// if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "float64" {
	// 	price := int64(json["price"].(float64))
	// 	formatInt_price := strconv.FormatInt(price, 10)
	// 	float_price, _ := strconv.ParseFloat(formatInt_price, 64)
	// 	additionalCharge.Price = float_price
	// }

	//if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "float64" {
	//	price := int64(json["price"].(float64))
	//	formatInt_price := strconv.FormatInt(price, 10)
	//	float_price, _ := strconv.ParseFloat(formatInt_price, 64)
	//	additionalCharge.Price = float_price
	//}

	if json["price"] != nil || reflect.TypeOf(json["price"]).String() == "string" {
		price, _ := strconv.ParseFloat(json["price"].(string), 64)
		additionalCharge.Price = price
	}
	if json["count"] != nil && reflect.TypeOf(json["count"]).String() == "string" {
		count, _ := json["count"].(string)
		counts, _ := strconv.ParseInt(count, 10, 64)
		additionalCharge.Count = counts
	}
	if json["item_name"] != nil && reflect.TypeOf(json["item_name"]).String() == "string" {
		item_name, _ := json["item_name"].(string)
		additionalCharge.ItemName = item_name
	}

	return 0
}

func (c *HisApiController) GetHisOrderList() {
	page, _ := c.GetInt64("page", -1)
	limit, _ := c.GetInt64("limit", -1)
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	types, _ := c.GetInt64("type", 0)
	keywords := c.GetString("keywords")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		if err != nil {
			fmt.Println(err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_time) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	adminUser := c.GetAdminUserInfo()
	org_id := adminUser.CurrentOrgId
	order, err, total := service.GetHisOrderList(org_id, page, limit, startTime, endTime, types, keywords)

	for _, item := range order {
		info, _ := service.GetHisPrescriptionByPatientID(item.PatientId, item.UserOrgId)
		item.DoctorName = info.Doctor
		item.DepartmentName = info.XtHisDepartment.Name
	}

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"order": order,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
}

func (c *HisApiController) GetHisOrder() {
	patient_id, _ := c.GetInt64("patient_id", 0)
	number := c.GetString("number")
	adminInfo := c.GetAdminUserInfo()
	order, err := service.GetHisOrder(adminInfo.CurrentOrgId, number, patient_id)
	prescriptions, _ := service.GetHisPrescriptionThree(adminInfo.CurrentOrgId, patient_id, order.Number)

	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"order":        order,
			"prescription": prescriptions,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

}

func (c *HisApiController) GetHisPrescriptionList() {
	record_date := c.GetString("record_date")
	keywords := c.GetString("keywords")
	page, _ := c.GetInt64("page")
	limit, _ := c.GetInt64("limit")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminInfo := c.GetAdminUserInfo()
	prescriptionOrder, err, total := service.GetHisPatientPrescriptionList(adminInfo.CurrentOrgId, keywords, recordDateTime, page, limit)

	//adminInfo := c.GetAdminUserInfo()
	//prescriptionOrder, err := service.GetHisPrescriptionOrderList(adminInfo.CurrentOrgId)
	//fmt.Println(prescriptionOrder)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"order": prescriptionOrder,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
}

func (c *HisApiController) GetHisPrescriptionInfo() {
	id, _ := c.GetInt64("id")
	adminInfo := c.GetAdminUserInfo()
	prescriptionOrder, err := service.GetHisPrescriptionOrderInfo(id, adminInfo.CurrentOrgId)
	prescription, err := service.GetHisPrescriptionFour(adminInfo.CurrentOrgId, prescriptionOrder.PatientId, prescriptionOrder.RecordDate, prescriptionOrder.PrescriptionNumber)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"order":        prescriptionOrder,
			"prescription": prescription,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
}

func (c *HisApiController) GetMedicalInsuranceConfig() {
	adminUser := c.GetAdminUserInfo()
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"config": config,
	})

}

type ResultTwo struct {
	ErrMsg      interface{} `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                   int64       `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           interface{} `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      interface{} `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 {
	Insutype string `json:"insutype"`
}
type ResultSix struct {
	Cainfo      interface{} `json:"cainfo"`
	ErrMsg      interface{} `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"`
			HifobPay        float64 `json:"hifob_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"`
			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 ResultEleven struct {
	Cainfo      string `json:"cainfo"`
	ErrMsg      string `json:"err_msg"`
	InfRefmsgid string `json:"inf_refmsgid"`
	Infcode     int64  `json:"infcode"`
	Output      struct {
		Setlinfo struct {
			FixmedinsName   string  `json:"fixmedins_name"`
			FixmedinsCode   string  `json:"fixmedins_code"`
			PsnNo           string  `json:"psn_no"`
			PsnName         string  `json:"psn_name"`
			HifobPay        float64 `json:"hifob_pay"`
			Gend            string  `json:"gend"`
			Brdy            string  `json:"brdy"`
			PsnCertType     string  `json:"psn_cert_type"`
			PsnType         string  `json:"psn_type"`
			EmpName         string  `json:"emp_name"`
			Certno          string  `json:"certno"`
			Insutype        string  `json:"insutype"`
			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"`
			PoolPropSelfpay float64 `json:"pool_prop_selfpay"`
			CvlservPay      float64 `json:"cvlserv_pay"`
			HifesPay        float64 `json:"hifes_pay"`
			HifmiPay        float64 `json:"hifmi_pay"`
			MafPay          float64 `json:"maf_pay"`
			OthPay          float64 `json:"oth_pay"`
			FundPaySumamt   float64 `json:"fund_pay_sumamt"`
			PsnPay          float64 `json:"psn_pay"`
			AcctPay         float64 `json:"acct_pay"`
			CashPayamt      float64 `json:"cash_payamt"`
			Balc            float64 `json:"balc"`
			AcctMulaidPay   float64 `json:"acct_mulaid_pay"`
			MedinsSetlId    string  `json:"medins_setl_id"`
			RefdSetlFlag    string  `json:"refd_setl_flag"`
			SetlTime        string  `json:"setl_time"`
			MedType         string  `json:"med_type"`
		} `json:"setlinfo"`
	} `json:"output"`
	RefmsgTime  string      `json:"refmsg_time"`
	RespondTime string      `json:"respond_time"`
	Signtype    interface{} `json:"signtype"`
	WarnMsg     interface{} `json:"warn_msg"`
}

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

//获取个人信息----挂号-----上传就诊信息
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")

	diagnosis_id, _ := c.GetInt64("diagnosis")
	sick_type, _ := c.GetInt64("sick_type")
	reg_type := c.GetString("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()
	tempPatient, _ := service.GetPatientByIDCardAndName(id_card, adminInfo.CurrentOrgId, name)
	if tempPatient.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeNoBloodPatientException)
		return
	}
	var patient service.Patients
	if id == 0 {
		patient, _ = service.GetPatientByIDCard(id_card, adminInfo.CurrentOrgId)

	} else {
		patient, _ = service.GetPatientByIDTwo(adminInfo.CurrentOrgId, id)

	}

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

	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:            adminInfo.AdminUser.Id,
			UserOrgId:              adminInfo.CurrentOrgId,
			Status:                 1,
			RecordDate:             recordDateTime,
			IsReturn:               1,
			PatientId:              patient.ID,
			Ctime:                  time.Now().Unix(),
			Mtime:                  time.Now().Unix(),
			Number:                 str,
			IdCardType:             id_card_type,
			Departments:            department,
			Doctor:                 doctor,
			PType:                  reg_type,
			Diagnosis:              diagnosis_id,
			SickType:               sick_type,
		}
		service.CreateHisPatient(&hisPatient)
		c.ServeSuccessJSON(map[string]interface{}{
			"his_info": hisPatient,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisRegisterException)
		return
	}
}

//上传明细----结算
func (c *HisApiController) GetUploadInfo() {
	id, _ := c.GetInt64("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")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	settle_accounts_type, _ := c.GetInt64("settle_accounts_type")

	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 settle_accounts_type == 1 { //日结

		prescriptions, _ = service.GetSettleHisPrescription(adminUser.CurrentOrgId, id, recordDateTime)

	} else { //月结
		start_time_str := c.GetString("start_time")
		end_time_str := c.GetString("end_time")
		timeLayout := "2006-01-02"
		loc, _ := time.LoadLocation("Local")
		theStartTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time_str+" 00:00:00", loc)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		recordStartTime := theStartTime.Unix()
		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)
	}

	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)
	strconv.FormatInt(his.PatientId, 10)

	var ids []int64

	for _, item := range prescriptions {
		ids = append(ids, item.ID)
	}

	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,
		SettleEndTime:         end_time,
		SettleStartTime:       start_time,
		SettleType:            settle_accounts_type,
	}
	err = service.CreateOrder(order)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateOrderException)
		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.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": "结算成功",
		})
	}
}

//退款
func (c *HisApiController) Refund() {
	order_id, _ := c.GetInt64("order_id")
	number := c.GetString("number")

	adminUser := c.GetAdminUserInfo()
	config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)
	if config.IsOpen == 1 { //对接了医保,走医保流程

	} 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 (this *HisApiController) AdditionalCharge() {

	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	fmt.Println(err)
	his_patient_id := int64(dataBody["his_patient_id"].(float64))
	patient_id := int64(dataBody["patient_id"].(float64))
	medicineData, _ := dataBody["medicineData"].([]interface{})
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	admin_user_id := adminUserInfo.AdminUser.Id
	timeStr := time.Now().Format("2006-01-02")
	timeLayout := "2006-01-02 15:04:05"
	timeStringToTime, _ := utils.ParseTimeStringToTime(timeLayout, timeStr+" 00:00:00")
	timenow := timeStringToTime.Unix()
	var additionalCharges []*models.HisAdditionalCharge
	for _, item := range medicineData {

		var randNum int
		randNum = rand.Intn(10000) + 1000
		timestamp := time.Now().Unix()
		tempTime := time.Unix(timestamp, 0)
		timeFormat := tempTime.Format("20060102150405")
		p_number := timeFormat + strconv.FormatInt(int64(randNum), 10) + strconv.FormatInt(int64(adminUserInfo.CurrentOrgId), 10) + strconv.FormatInt(int64(patient_id), 10)

		items := item.(map[string]interface{})
		money := items["price"].(string)
		item_id_str := items["item_id"].(string)
		name := items["name"].(string)
		id_str := items["id"].(string)
		moneys, _ := strconv.ParseInt(money, 10, 64)
		monStr := strconv.FormatInt(moneys, 10)
		monneyStr, _ := strconv.ParseFloat(monStr, 64)
		item_id, _ := strconv.ParseInt(item_id_str, 10, 64)
		id, _ := strconv.ParseInt(id_str, 10, 64)
		additionalCharge := &models.HisAdditionalCharge{
			ID:                 id,
			HisPatientId:       his_patient_id,
			UserOrgId:          orgId,
			PatientId:          patient_id,
			RecordDate:         timenow,
			Price:              monneyStr,
			Status:             1,
			ItemName:           name,
			ItemId:             item_id,
			AdminUserId:        admin_user_id,
			CreatedTime:        time.Now().Unix(),
			OrderStatus:        0,
			PrescriptionNumber: "",
			BatchNumber:        "",
			FeedetlSn:          p_number,
		}
		service.CreateAdditionalCharge(additionalCharge)

		additionalCharges = append(additionalCharges, additionalCharge)
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"msg":                "添加成功",
		"additional_charges": additionalCharges,
	})
}

func (this *HisApiController) DeleteAddition() {
	id, _ := this.GetInt64("id")
	//TODO 需要判断是否已经结算
	err := service.DelelteAddition(id, this.GetAdminUserInfo().CurrentOrgId)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"msg": "删除成功",
		})
		return
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

}

func (this *HisApiController) GetAdminUsers() {
	adminUser := this.GetAdminUserInfo()
	doctors, _ := service.GetAllHisDoctor(adminUser.CurrentOrgId)
	this.ServeSuccessJSON(map[string]interface{}{
		"doctors": doctors,
	})
}

func (this *DialysisApiController) GetLastOrNextHisPrescription() {
	change_type, _ := this.GetInt64("type", 0)
	record_date := this.GetString("record_time")
	patient_id, _ := this.GetInt64("patient_id", 0)

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
	record_time := theAdviceRecordTime.Unix()
	adminUserInfo := this.GetAdminUserInfo()
	prescriptions, err := service.GetHisPrescriptionByType(change_type, record_time, adminUserInfo.CurrentOrgId, patient_id)
	if err == nil {
		if len(prescriptions) == 0 {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
			return
		} else {
			this.ServeSuccessJSON(map[string]interface{}{
				"prescriptions": prescriptions,
			})
			return
		}
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}

func (this *DialysisApiController) GetCallHisPrescription() {
	patient_id, _ := this.GetInt64("patient_id", 0)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("start_time")
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	end_time := this.GetString("end_time")
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	adminUserInfo := this.GetAdminUserInfo()
	prescriptions, err := service.GetCallHisPrescriptions(startime.Unix(), endtime.Unix(), adminUserInfo.CurrentOrgId, patient_id)
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"prescriptions": prescriptions,
		})
		return
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}

func (this *HisApiController) GetHisDayPrescription() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	start_time := this.GetString("start_time")
	patient_id, _ := this.GetInt64("patient_id", 0)
	startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	end_time := this.GetString("end_time")
	endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	adminUserInfo := this.GetAdminUserInfo()
	dayHisPrescription, err := service.GetMonthHisPrescriptionThree(adminUserInfo.CurrentOrgId, patient_id, startime.Unix(), endtime.Unix())
	if err == nil {
		this.ServeSuccessJSON(map[string]interface{}{
			"day_prescription": dayHisPrescription,
		})
		return
	} else {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}

func (c *HisApiController) GetHisChargePatientList() {
	record_date := c.GetString("record_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_date+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminInfo := c.GetAdminUserInfo()
	tempPatients, _ := service.GetAllChargeHisPatientList(adminInfo.CurrentOrgId, "", recordDateTime)
	var patients []*service.Patients
	var patients_two []*service.Patients

	for _, item := range tempPatients {
		//过滤掉没挂号的和没开处方的
		if item.HisPatient.ID > 0 || len(item.HisPrescription) > 0 {
			patients = append(patients, item)
		}
		//过滤掉没挂号的
		if item.HisPatient.ID > 0 {
			patients_two = append(patients_two, item)
		}
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"list":     patients,
		"list_two": patients_two,
	})
}

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

	tempPatients, _ := service.GetHisPatientList(adminUser.CurrentOrgId, "", recordDateTime)

	var patients []*service.Patients
	for _, item := range tempPatients {
		if item.HisPatient.ID == 0 {
			patients = append(patients, item)
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"list": patients,
		//"list_two":	patients_two,
	})

}

func RemoveRepeatedPatient(patient []*service.Patients) (newArr []*service.Patients) {
	newArr = make([]*service.Patients, 0)
	for i := 0; i < len(patient); i++ {
		repeat := false
		for j := i + 1; j < len(patient); j++ {
			if patient[i].ID == patient[j].ID {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, patient[i])
		}
	}
	return
}

func (c *HisApiController) GetHisChargePatientInfo() {
	patient_id, _ := c.GetInt64("patient_id")
	record_date := c.GetString("record_date")
	number := c.GetString("number")

	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")

	order_status, _ := c.GetInt64("type", 0)

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

	startTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
	if err != nil {

	}
	startRecordDateTime := startTime.Unix()

	endTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
	if err != nil {

	}
	endRecordDateTime := endTime.Unix()

	admin := c.GetAdminUserInfo()
	his_patient_info, _ := service.GetHisPatientInfo(admin.CurrentOrgId, patient_id, recordDateTime)
	xt_patient_info, _ := service.GetXTPatientInfo(admin.CurrentOrgId, patient_id)

	var prescriptions []*models.HisPrescription

	if order_status == 1 || order_status == 0 {
		prescriptions, _ = service.GetUnChargeHisPrescriptionFive(admin.CurrentOrgId, patient_id, recordDateTime)
	} else if order_status == 2 {
		prescriptions, _ = service.GetChargeHisPrescriptionFive(admin.CurrentOrgId, patient_id, recordDateTime)
	}

	var monthPrescriptions []*models.HisPrescription

	if order_status == 1 || order_status == 0 {
		monthPrescriptions, _ = service.GetUnChargeMonthHisPrescriptionThree(admin.CurrentOrgId, patient_id, startRecordDateTime, endRecordDateTime)
	} else if order_status == 2 {
		monthPrescriptions, _ = service.GetChargeMonthHisPrescriptionFour(admin.CurrentOrgId, patient_id, startRecordDateTime, endRecordDateTime)

	}

	case_history, _ := service.GetHisPatientCaseHistoryInfo(admin.CurrentOrgId, patient_id, recordDateTime)
	patientPrescriptionInfo, _ := service.FindPatientPrescriptionInfo(admin.CurrentOrgId, patient_id, recordDateTime)
	order, _ := service.GetHisOrder(admin.CurrentOrgId, number, patient_id)

	doctors, _ := service.GetHisAdminUserDoctors(admin.CurrentOrgId)
	//获取所有科室信息
	department, _ := service.GetAllDepartMent(admin.CurrentOrgId)

	c.ServeSuccessJSON(map[string]interface{}{
		"his_info":            his_patient_info,
		"xt_info":             xt_patient_info,
		"prescription":        prescriptions,
		"case_history":        case_history,
		"info":                patientPrescriptionInfo,
		"month_prescriptions": monthPrescriptions,
		"order":               order,
		"doctors":             doctors,
		"department":          department,
	})
	return

}

func (c *HisApiController) GetAllOrderDetail() {
	order_id, _ := c.GetInt64("id", 0)
	order, _ := service.GetHisOrderByID(order_id)
	if order.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOrderParamWrong)
		return
	}
	org_id := c.GetAdminUserInfo().CurrentOrgId
	adminInfo, _ := service.GetAdminUserInfoByID(org_id, order.Creator)
	patient, _ := service.GetPatientByID(org_id, order.PatientId)
	order_info, _ := service.GetHisOrderDetailByNumber(order.Number, org_id)
	c.ServeSuccessJSON(map[string]interface{}{
		"order":      order,
		"order_info": order_info,
		"patient":    patient,
		"admin_info": adminInfo,
	})
	return

}

func (c *HisApiController) GetAllOrderDetailCollect() {
	order_id, _ := c.GetInt64("id", 0)
	order, _ := service.GetHisOrderByID(order_id)
	if order.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOrderParamWrong)
		return
	}
	org_id := c.GetAdminUserInfo().CurrentOrgId
	adminInfo, _ := service.GetAdminUserInfoByID(org_id, order.Creator)
	order_info, _ := service.GetHisOrderDetailByNumber(order.Number, org_id)
	patient, _ := service.GetPatientByID(org_id, order.PatientId)
	c.ServeSuccessJSON(map[string]interface{}{
		"order":      order,
		"order_info": order_info,
		"patient":    patient,
		"admin_info": adminInfo,
	})
	return
}