package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/shopspring/decimal"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

type HisHospitalApiController struct {
	BaseAuthAPIController
}

func HisHospitalManagerApiRegistRouters() {
	beego.Router("/api/hishospitalpatient/list", &HisHospitalApiController{}, "get:GetHisHospitalPatientList")
	beego.Router("/api/hospitalcharge/list", &HisHospitalApiController{}, "get:GetHisHospitalChargePatientList")
	beego.Router("/api/hospotalcharge/info", &HisHospitalApiController{}, "get:GetHisHospitalChargePatientInfo")
	beego.Router("/api/hospitalprescription/list", &HisHospitalApiController{}, "get:GetHisHospitalPrescriptionList")

	beego.Router("/api/hospital/inhopitalcheck/get", &HisHospitalApiController{}, "get:GetZHInHospitalCheck")
	beego.Router("/api/hospital/outhopitalcheck/get", &HisHospitalApiController{}, "get:GetZHOutHospitalCheck")
	beego.Router("/api/hospital/settle/get", &HisHospitalApiController{}, "get:GetSettleInfo")
	beego.Router("/api/hospital/inthopitaluncheck/get", &HisHospitalApiController{}, "get:GetZHInHospitalUnCheck")
	beego.Router("/api/hospital/outhopitaluncheck/get", &HisHospitalApiController{}, "get:GetZHOutHospitalUnCheck")
	beego.Router("/api/hospital/refund", &HisHospitalApiController{}, "get:ZHRefund")
	beego.Router("/api/hospital/upload", &HisHospitalApiController{}, "get:GetUploadInfo")
	beego.Router("/api/hospital/refunddetail", &HisHospitalApiController{}, "get:RefundDetail")

	beego.Router("/api/hospitaldetail/list", &HisHospitalApiController{}, "get:GetHisHospitalDetailPatientList")
	beego.Router("/api/hospitaldetail/info", &HisHospitalApiController{}, "get:GetHisHospitalDetailInfo")

	beego.Router("/api/monthhospitaldetail/get", &HisHospitalApiController{}, "get:GetHisHospitalMonthDetailInfo")

	beego.Router("/api/exportuncharge/get", &HisHospitalApiController{}, "get:GetExportHisHospitalUnChargeData")

	beego.Router("/api/hospital/inhopitalcheck/list", &HisHospitalApiController{}, "get:GetZHInHospitalCheckList")

	beego.Router("/api/fapiao/modifytwo", &HisHospitalApiController{}, "post:ModifyFaPiaoCode")

}
func (this *HisHospitalApiController) ModifyFaPiaoCode() {
	order_id, _ := this.GetInt64("id")
	fapiao_number := this.GetString("fapiao_number")

	order, _ := service.GetHisOrderByID(order_id)
	if order.ID == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

	order.FaPiaoNumber = fapiao_number
	err := service.SaveOrderTwo(&order)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"order": order,
		"msg":   "修改成功",
	})
}

func (this *HisHospitalApiController) GetZHInHospitalCheckList() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := this.GetString("keyword")
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	limit, _ := this.GetInt64("limit")
	page, _ := this.GetInt64("page")
	startTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+":00", loc)
	endTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+":59", loc)
	adminUserInfo := this.GetAdminUserInfo()
	orgId := adminUserInfo.CurrentOrgId
	history, total, err := service.GetHisInHospitalHistory(keyword, startTime.Unix(), endTime.Unix(), limit, page, orgId)
	department, err := service.GetAllDepartMent(orgId)
	appId := adminUserInfo.CurrentAppId
	doctor, err := service.GetAllDoctor(orgId, appId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeUpdateConfig)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"history":    history,
		"total":      total,
		"department": department,
		"doctor":     doctor,
	})
}
func (c *HisHospitalApiController) RefundDetail() {
	patient_id, _ := c.GetInt64("patient_id")
	his_patient_id, _ := c.GetInt64("his_patient_id")
	record_time := c.GetString("record_time")
	settle_accounts_type, _ := c.GetInt64("settle_accounts_type")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminUser := c.GetAdminUserInfo()
	theTimeTwo, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 23:59:59", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTimeTwo := theTimeTwo.Unix()
	if settle_accounts_type == 1 { //日结
		err := service.UpDateOrderInfoStatus(patient_id, recordDateTime, adminUser.CurrentOrgId, recordDateTimeTwo)

		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		err1 := service.UpDatePrescriptionOrderStatusTwo(patient_id, recordDateTime, adminUser.CurrentOrgId)
		if err1 != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "撤销明细成功",
		})

	} else {
		record, _ := service.GetInHospitalRecord(his_patient_id)
		err := service.UpdataHospitalOrderStatusTwo(record.Number, adminUser.CurrentOrgId)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "撤销明细成功",
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	}
}

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

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

	var prescriptions []*models.HisPrescription

	if settle_accounts_type == 1 { //日结
		prescriptions, _ = service.GetZHHisPrescription(adminUser.CurrentOrgId, id, recordDateTime)

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

	}

	record, _ := service.GetInHospitalRecord(in_hospital_id)

	if record.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

	var ids []int64

	for _, item := range prescriptions {
		ids = append(ids, item.ID)
	}
	//config, _ := service.GetMedicalInsuranceConfig(adminUser.CurrentOrgId)

	var customs []*models.NewCustom

	for _, item := range prescriptions {
		tm := time.Unix(item.PreTime, 0)
		if item.Type == 1 { //药品
			for _, subItem := range item.HisDoctorAdviceInfo {
				//if subItem.Drug.IsUser != 1 {
				//var randNum int
				//randNum = rand.Intn(10000) + 1000
				if len(subItem.FeedetlSn) == 0 {
					fmt.Println("drug")
					fmt.Println(subItem.ID)
				}

				cus := &models.NewCustom{
					DetItemFeeSumamt: subItem.Price * subItem.PrescribingNumber,
					Cut:              subItem.PrescribingNumber,
					FeedetlSn:        subItem.FeedetlSn,
					Price:            subItem.Price,
					MedListCodg:      subItem.Drug.MedicalInsuranceNumber,
					HospApprFlag:     subItem.Drug.HospApprFlag,
					FeeOcurTime:      tm.Format("2006-01-02 15:04:05"),
				}

				customs = append(customs, cus)
				//}
			}
		}

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

				if subItem.Type == 2 {
					if len(subItem.FeedetlSn) == 0 {
						fmt.Println("project")
						fmt.Println(subItem.ID)
					}
					//if len(subItem.HisProject.MedicalCode) > 0 {
					cnt, _ := strconv.ParseFloat(subItem.Count, 64)
					cus := &models.NewCustom{
						DetItemFeeSumamt: subItem.Price * cnt,
						Cut:              cnt,
						FeedetlSn:        subItem.FeedetlSn,
						Price:            float64(subItem.Price),
						MedListCodg:      subItem.HisProject.MedicalCode,
						HospApprFlag:     -1,
						FeeOcurTime:      tm.Format("2006-01-02 15:04:05"),
					}
					customs = append(customs, cus)
					//}/* *//**/
				} else if subItem.Type == 3 {
					if len(subItem.FeedetlSn) == 0 {
						fmt.Println("good")
						fmt.Println(subItem.ID)
					}
					//if subItem.GoodInfo.IsUser != 1 {
					cnt, _ := strconv.ParseFloat(subItem.Count, 64)

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

	}

	fmt.Println(settle_accounts_type)

	if settle_accounts_type == 1 {
		fmt.Println(customs)
		for _, subItem := range customs {
			if len(subItem.FeedetlSn) > 0 {
				temp := strings.Split(subItem.FeedetlSn, "-")
				var advice_id int64 = 0
				var project_id int64 = 0
				var types int64 = 0

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

				if temp[1] == "1" {
					advice_id = id
					project_id = 0
				} else if temp[1] == "2" {
					advice_id = 0
					project_id = id
				}
				info := &models.HisOrderInfo{
					OrderNumber:      record.Number,
					FeedetlSn:        subItem.FeedetlSn,
					UploadDate:       recordDateTime,
					AdviceId:         advice_id,
					DetItemFeeSumamt: subItem.DetItemFeeSumamt,
					Cnt:              subItem.Cut,
					Pric:             float64(subItem.Price),
					PatientId:        record.PatientId,
					PricUplmtAmt:     0,
					SelfpayProp:      0,
					FulamtOwnpayAmt:  0,
					OverlmtAmt:       0,
					PreselfpayAmt:    0,
					Status:           1,
					Mtime:            time.Now().Unix(),
					Ctime:            time.Now().Unix(),
					UserOrgId:        adminUser.CurrentOrgId,
					HisPatientId:     record.ID,
					OrderId:          0,
					ProjectId:        project_id,
					Type:             types,
					SettleType:       settle_accounts_type,
				}
				if info.AdviceId > 0 && info.ProjectId == 0 {
					info.MedChrgitmType = "09"
				} else if info.AdviceId == 0 && info.ProjectId > 0 {
					p, _ := service.GetHisPrescriptionProjectByIDTwo(info.ProjectId)
					if p.Type == 2 {
						if p.HisProject.CostClassify == 3 {
							info.MedChrgitmType = "04"
						}
						if p.HisProject.CostClassify == 2 {
							info.MedChrgitmType = "05"
						}
						if p.HisProject.CostClassify == 8 {
							info.MedChrgitmType = "03"
						}
					} else {
						info.MedChrgitmType = "08"

					}
				}
				service.CreateOrderInfo(info)
			}
		}

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

	} else {

		for _, subItem := range customs {
			if len(subItem.FeedetlSn) == 0 {
				fmt.Println("1111111")
				fmt.Println(subItem.FeedetlSn)
				fmt.Println("1111111")

			}
			if len(subItem.FeedetlSn) > 0 {
				fmt.Println(subItem.FeedetlSn)
				temp := strings.Split(subItem.FeedetlSn, "-")
				var advice_id int64 = 0
				var project_id int64 = 0
				var types int64 = 0

				fmt.Println("~~~~")

				fmt.Println(temp)
				fmt.Println("~~~~~")

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

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

			}

		}

		service.UpDatePrescriptionOrderStatus(adminUser.CurrentOrgId, ids)
		service.UpDatePrescriptionNumber(adminUser.CurrentOrgId, ids, record.Number)
		service.UpDatePrescriptionInfoNumber(adminUser.CurrentOrgId, record.PatientId, record.Number, recordDateTime)
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "上传费用明细成功",
		})

	}
}

func (c *HisHospitalApiController) GetHisHospitalPatientList() {
	record_date := c.GetString("record_date")
	types, _ := c.GetInt64("type", 0)
	sch_type, _ := c.GetInt64("sch_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()
	adminInfo := c.GetAdminUserInfo()
	//var patients []*service.HospitalPatient
	var all_tempPatients []*service.HospitalPatient
	tempPatients, _ := service.GetHisHospitalPatientList(adminInfo.CurrentOrgId, recordDateTime, sch_type)
	tempPatients_two, _ := service.GetHisHospitalSchPatientList(adminInfo.CurrentOrgId, recordDateTime, sch_type)

	if types == 0 {
		all_tempPatients, _ = service.GetAllHisHospitalPatientList(adminInfo.CurrentOrgId, recordDateTime, sch_type)
		for _, item := range all_tempPatients {
			for index, subItem := range tempPatients_two {
				if item.ID == subItem.ID {
					tempPatients_two = append(tempPatients_two[:index], tempPatients_two[index+1:]...)

				}
			}
		}
		all_tempPatients = append(all_tempPatients, tempPatients_two...)

	}

	//当天有登记住院的和排班同时存在的话,删除掉排班的记录
	for _, item := range tempPatients {
		for index, subItem := range tempPatients_two {
			if item.ID == subItem.ID {
				tempPatients_two = append(tempPatients_two[:index], tempPatients_two[index+1:]...)

			}
		}
	}
	tempPatients = append(tempPatients, tempPatients_two...)

	var total_one int64
	var total_two int64

	for _, item := range tempPatients {

		if item.VMHisPrescriptionInfo.ID == 0 {
			total_one = total_one + 1
		}
		if item.VMHisPrescriptionInfo.ID > 0 {
			total_two = total_two + 1
		}
	}

	adminUserInfo, _ := service.GetAdminUserInfoByID(adminInfo.CurrentOrgId, adminInfo.AdminUser.Id)
	doctors, _ := service.GetHisAdminUserDoctors(adminInfo.CurrentOrgId)
	department, _ := service.GetAllDepartMent(adminInfo.CurrentOrgId)

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

	} else if types == 1 { //未就诊
		var patientsOne []*service.HospitalPatient
		for _, item := range tempPatients {
			if item.VMHisPrescriptionInfo.ID == 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.HospitalPatient
		for _, item := range tempPatients {

			if item.VMHisPrescriptionInfo.ID > 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 *HisHospitalApiController) GetHisHospitalChargePatientList() {
	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)
	orders, _ := service.GetNewAllChargeHisHospitalPatientList(adminInfo.CurrentOrgId, recordDateTime)
	tempPatients, _ := service.GetNewAllUnChargeHisHospitalPatientList(adminInfo.CurrentOrgId, recordDateTime)

	var patients []*models.HisHospitalCheckRecord
	for _, item := range tempPatients {
		fmt.Println(item.ID)
		if item.ID > 0 && item.InHospitalStatus == 1 && item.HisHospitalOrder.OrderStatus != 2 {
			patients = append(patients, item)
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"list":        patients,
		"list_two":    patients,
		"charge_list": orders,
	})
}
func (c *HisHospitalApiController) GetHisHospitalChargePatientInfo() {
	patient_id, _ := c.GetInt64("patient_id")
	his_patient_id, _ := c.GetInt64("his_patient_id")
	record_date := c.GetString("record_date")
	start_time := c.GetString("start_time")
	end_time := c.GetString("end_time")
	order_status, _ := c.GetInt64("type", 0)
	p_type, _ := c.GetInt64("p_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.GetNewHisHospitalPatientInfo(his_patient_id)
	xt_patient_info, _ := service.GetXTPatientInfo(admin.CurrentOrgId, patient_id)

	var prescriptions []*models.HisHospitalPrescription
	if order_status == 1 || order_status == 0 {
		prescriptions, _ = service.GetNewUnChargeHisHospitalPrescriptionFive(admin.CurrentOrgId, patient_id, his_patient_id, recordDateTime)
	} else if order_status == 2 {
		prescriptions, _ = service.GetNewChargeHisHospitalPrescriptionFive(admin.CurrentOrgId, patient_id, his_patient_id, recordDateTime)
	}

	var monthPrescriptions []*models.HisPrescription
	var settle_prescriptions []*models.HisHospitalPrescription
	if order_status == 1 || order_status == 0 {
		monthPrescriptions, _ = service.GetUnChargeMonthHisPrescriptionThree(admin.CurrentOrgId, patient_id, startRecordDateTime, endRecordDateTime, p_type)
	} else if order_status == 2 {
		monthPrescriptions, _ = service.GetChargeMonthHisPrescriptionFour(admin.CurrentOrgId, patient_id, startRecordDateTime, endRecordDateTime, p_type)
	}

	if order_status == 1 || order_status == 0 {
		settle_prescriptions, _ = service.GetSettleHisHospitalPrescription(admin.CurrentOrgId, patient_id, his_patient_info.Number)
	} else if order_status == 2 {
		settle_prescriptions, _ = service.GetSettleHisHospitalPrescriptionTwo(admin.CurrentOrgId, patient_id, his_patient_info.Number)
	}

	var settle_total float64
	for _, item := range settle_prescriptions {
		if len(item.HisPrescriptionProject) > 0 {
			for _, subItem := range item.HisPrescriptionProject {
				count, _ := strconv.ParseFloat(subItem.Count, 64)
				total, _ := decimal.NewFromFloat(count * subItem.Price).Round(2).Float64()
				settle_total = settle_total + total
			}
		}
		if len(item.HisDoctorAdviceInfo) > 0 {
			for _, subItem := range item.HisDoctorAdviceInfo {
				total, _ := decimal.NewFromFloat(subItem.PrescribingNumber * subItem.Price).Round(2).Float64()
				settle_total = settle_total + total
			}
		}

	}
	settle_total, _ = decimal.NewFromFloat(settle_total).Round(2).Float64()

	case_history, _ := service.GetHisPatientCaseHistoryInfo(admin.CurrentOrgId, patient_id, recordDateTime)
	patientPrescriptionInfo, _ := service.FindPatientPrescriptionInfoTwo(admin.CurrentOrgId, patient_id, recordDateTime, p_type)
	order, _ := service.GetNewHisOrder(admin.CurrentOrgId, his_patient_info.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,
		"settle_prescriptions": settle_prescriptions,
		"settle_total":         settle_total,
	})
	return

}
func (c *HisHospitalApiController) GetHisHospitalrescriptionList() {
	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 *HisHospitalApiController) GetHisHospitalPrescriptionList() {
	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.GetHisHospitalPatientPrescriptionList(adminInfo.CurrentOrgId, keywords, recordDateTime, page, limit)
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"order": prescriptionOrder,
			"total": total,
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}

}

func (c *HisHospitalApiController) GetZHInHospitalCheck() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	name := c.GetString("name")
	phone := c.GetString("phone")
	id_card_type, _ := c.GetInt64("id_card_type")
	certificates, _ := c.GetInt64("certificates")
	id_card_no := c.GetString("id_card_no")
	doctor, _ := c.GetInt64("doctor")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	department, _ := c.GetInt64("department")
	adm_bed, _ := c.GetInt64("adm_bed")
	diagnosis_ids := c.GetString("diagnosis")
	sick_type, _ := c.GetInt64("sick_type")
	start_time := c.GetString("start_time")
	balance_accounts_type, _ := c.GetInt64("balance_accounts_type")
	med_type, _ := c.GetInt64("med_type")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordDateTime := theTime.Unix()
	adminInfo := c.GetAdminUserInfo()
	record, _ := service.GetLastHospitalRecord(id, adminInfo.CurrentOrgId)
	if record.ID != 0 {
		if record.InHospitalStatus == 1 && record.OutHospitalStatus != 1 {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHospitalExistDataException)
			return
		}
	}
	timestamp := time.Now().Unix()
	tempTime := time.Unix(timestamp, 0)
	timeFormat := tempTime.Format("20060102150405")
	chrgBchno := rand.Intn(100000) + 10000
	ipt_otp_no := timeFormat + strconv.FormatInt(int64(chrgBchno), 10) + strconv.FormatInt(id, 10)

	timeStr := time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(timeStr)
	timeArr := strings.Split(timeStr, " ")
	fmt.Println(timeArr)

	timeArrTwo := strings.Split(timeArr[0], "-")
	timeArrThree := strings.Split(timeArr[1], ":")
	var str = timeArrTwo[0] + timeArrTwo[1] + timeArrTwo[2] + timeArrThree[0] + timeArrThree[1] + timeArrThree[2] + strconv.FormatInt(id, 10)

	inHospital := &models.HisHospitalCheckRecord{
		PatientId:            id,
		Name:                 name,
		MedicalTreatmentType: med_type,
		RecordDate:           recordDateTime,
		IdCardNo:             id_card_no,
		AdminUserId:          admin_user_id,
		Departments:          department,
		UserOrgId:            adminInfo.CurrentOrgId,
		Status:               1,
		Ctime:                time.Now().Unix(),
		Mtime:                time.Now().Unix(),
		Number:               str,
		Doctor:               doctor,
		Certno:               id_card_no,
		MedType:              med_type,
		IptOtpNo:             ipt_otp_no,
		AdmBed:               adm_bed,
		IdCardType:           id_card_type,
		Diagnosis:            diagnosis_ids,
		SickType:             sick_type,
		MdtrtCertType:        "02",
		InHosptialTime:       start_time,
		OutHosptialTime:      "",
		InHospitalStatus:     1,
		Certificates:         certificates,
		Phone:                phone,
		BalanceAccountsType:  balance_accounts_type,
	}
	service.CreateHospitalRecord(inHospital)
	c.ServeSuccessJSON(map[string]interface{}{
		"msg":  "办理入院成功",
		"info": inHospital,
	})
}
func (this *HisHospitalApiController) GetZHOutHospitalCheck() {
	id, _ := this.GetInt64("id")
	record_time := this.GetString("record_time")
	out_time := this.GetString("out_time")

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

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", record_time+" 00:00:00", loc)

	recordDateTime := theTime.Unix()

	//timestamp := time.Now().Unix()
	//tempTime := time.Unix(timestamp, 0)
	//timeFormatOne := tempTime.Format("2006-01-02 15:04:05")
	record.OutHospitalStatus = 1
	record.OutHosptialTime = out_time
	record.OutWay = 1
	service.CreateHospitalRecord(&record)

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

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

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

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

	id, _ := c.GetInt64("patient_id")
	dec_way := c.GetString("dec_way") //是否使用押金支付bool类型
	tmp_decimal := c.GetString("tmp_decimal")
	var decimal float64 //本次使用的押金
	var errmsg error
	tx := service.XTWriteDB().Begin() //开了事务
	//只检测扣费函数SpendDeposit有没有返回错误,如果有则回滚所有以TX结尾的方法(去掉TX即为原先的方法)
	defer func() {
		if errmsg != nil {
			utils.ErrorLog("事务失败,原因为: %v", errmsg.Error())
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	if dec_way == "true" && tmp_decimal == "0" || dec_way == "true" && tmp_decimal == "" {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金不能为0")
		return
	}
	if len(tmp_decimal) > 0 {
		if tmp_decimal[0] == 45 {
			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金不能为负数")
			return
		}
	}
	tt, errs := strconv.ParseFloat(tmp_decimal, 64)
	if errs != nil {
		c.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金金额错误")
		return
	}
	decimal = tt

	record, _ := service.GetInHospitalRecordTX(in_hospital_id, tx)
	order, _ := service.GetHisOrderByIDTX(order_id, tx)
	chrg_bchno := order.Number
	if record.ID == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	if record.InHospitalStatus == 1 && record.OutHospitalStatus == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHospitalNoExistDataException)
		return
	}
	order.OrderStatus = 2
	order.DiscountPrice = discount_price
	order.MedicalInsurancePrice = medical_insurance_price
	order.FaPiaoNumber = fapiao_number
	order.FaPiaoCode = fapiao_code
	order.PayWay = pay_way
	order.PayPrice = pay_price
	order.PayCardNo = pay_card_no
	order.PreferentialPrice = preferential_price
	order.RealityPrice = reality_price
	order.FoundPrice = found_price
	order.PrivatePrice = private_price
	order.MdtrtId = record.Number
	order.MedfeeSumamt = order.MedfeeSumamt
	order.PsnCashPay = order.MedfeeSumamt
	order.PsnName = record.Name
	order.Certno = record.IdCardNo
	order.IsMedicineInsurance = 0
	order.Decimal = decimal
	year2 := time.Now().Format("2006")
	month2 := time.Now().Format("01")
	day2 := time.Now().Format("02")
	hour := time.Now().Format("15")
	min := time.Now().Format("04")
	second := time.Now().Format("05")

	order.SetlTime = year2 + "-" + month2 + "-" + day2 + " " + hour + ":" + min + ":" + second
	//order.SetlTime =
	err := service.UpdataOrderStatusTwoTX(chrg_bchno, c.GetAdminUserInfo().CurrentOrgId, tx)
	err = service.UpDateOrderTX(order, tx)
	//判断是否使用了押金
	if dec_way == "true" {
		tmpstring := strconv.FormatInt(order.ID, 10)
		//扣押金
		errmsg = service.SpendDeposit(c.GetAdminUserInfo().CurrentOrgId, id, c.GetAdminUserInfo().AdminUser.Id, tmpstring, decimal)
		if errmsg != nil {
			c.ServeFailJsonSend(enums.ErrorCodeParamWrong, errmsg.Error())
			//c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateOrderException)
			return
		}
	}
	if err == nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"msg": "结算成功",
		})
	} else {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
}
func (c *HisHospitalApiController) ZHRefund() {
	order_id, _ := c.GetInt64("order_id")
	order, _ := service.GetHisOrderByID(order_id)
	adminUser := c.GetAdminUserInfo()
	orgid := c.GetAdminUserInfo().CurrentOrgId
	err := service.UpdataHospitalOrderStatus(order_id, order.Number, adminUser.CurrentOrgId, "", "")
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	tmp := strconv.FormatInt(order.ID, 10)
	//当押金不为零时产生退费记录
	if order.Decimal != 0 {
		err = service.MoneyIncrease(orgid, order.PatientId, tmp, order.Decimal)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	}

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

}
func (this *HisHospitalApiController) GetZHOutHospitalUnCheck() {
	id, _ := this.GetInt64("id")
	record, _ := service.GetInHospitalRecord(id)
	if record.ID == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeInHospitalNoExistDataException)
		return
	}
	record.OutHospitalStatus = 0
	service.CreateHospitalRecord(&record)
	this.ServeSuccessJSON(map[string]interface{}{
		"msg": "撤销出院成功",
	})

}
func (this *HisHospitalApiController) GetZHInHospitalUnCheck() {
	id, _ := this.GetInt64("id")

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

	record.Status = 0
	service.CreateHospitalRecord(&record)

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

}

func (c *HisHospitalApiController) GetHisHospitalDetailPatientList() {
	record_date := c.GetString("record_date")
	sch_type, _ := c.GetInt64("sch_type")

	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()
	UnUploadPrescriptionPatients, _ := service.GetHisHospitalUnUploadPrescriptionDetailPatientList(adminInfo.CurrentOrgId, recordDateTime, sch_type)
	UploadPrescriptionPatients, _ := service.GetHisHospitalUploadPrescriptionDetailPatientList(adminInfo.CurrentOrgId, recordDateTime, sch_type)
	//var patients []*models.HisHospitalCheckRecord
	/*	for _, item := range tempPatients {
		fmt.Println(item.ID)
		if item.ID > 0 && item.InHospitalStatus == 1 && item.HisHospitalOrder.OrderStatus != 2 {
			patients = append(patients, item)
		}
	}*/

	c.ServeSuccessJSON(map[string]interface{}{
		"list":          UnUploadPrescriptionPatients,
		"list_two":      UploadPrescriptionPatients,
		"upload_num":    len(UploadPrescriptionPatients),
		"un_upload_num": len(UnUploadPrescriptionPatients),
	})
}
func (c *HisHospitalApiController) GetHisHospitalDetailInfo() {
	record_date := c.GetString("record_date")
	id, _ := c.GetInt64("id")
	is_upload, _ := c.GetInt64("is_upload")
	patient_id, _ := c.GetInt64("patient_id")
	start_time_str := c.GetString("start_time")
	end_time_str := c.GetString("end_time")

	record, _ := service.GetInHospitalRecord(id)
	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()
	theStartTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time_str+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordStartTime := theStartTime.Unix()
	theEndTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time_str+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordEndTime := theEndTime.Unix()
	var prescriptions []*models.HisPrescription
	if is_upload == 1 { //未上传
		prescriptions, _ = service.GetUnUploadHisHospitalPrescription(adminInfo.CurrentOrgId, patient_id, recordDateTime)
	} else if is_upload == 2 { //已上传
		prescriptions, _ = service.GetUploadHisHospitalPrescription(adminInfo.CurrentOrgId, patient_id, recordDateTime)
	}
	var monthPrescriptions []*models.HisPrescription
	if is_upload == 1 {
		monthPrescriptions, _ = service.GetMonthUnUploadHisHospitalPrescription(adminInfo.CurrentOrgId, patient_id, recordStartTime, recordEndTime)
	} else if is_upload == 2 {
		monthPrescriptions, _ = service.GetMonthUploadHisHospitalPrescription(adminInfo.CurrentOrgId, patient_id, recordStartTime, recordEndTime)
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"prescription":        prescriptions,
		"month_prescriptions": monthPrescriptions,
		"his_info":            record,
	})
}
func (c *HisHospitalApiController) GetHisHospitalMonthDetailInfo() {
	id, _ := c.GetInt64("id")
	is_upload, _ := c.GetInt64("is_upload")
	patient_id, _ := c.GetInt64("patient_id")
	start_time_str := c.GetString("start_time")
	end_time_str := c.GetString("end_time")

	record, _ := service.GetInHospitalRecord(id)
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminInfo := c.GetAdminUserInfo()
	theStartTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time_str+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordStartTime := theStartTime.Unix()
	theEndTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time_str+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordEndTime := theEndTime.Unix()
	//var prescriptions []*models.HisPrescription

	var monthPrescriptions []*models.HisPrescription
	if is_upload == 1 {
		monthPrescriptions, _ = service.GetMonthUnUploadHisHospitalPrescription(adminInfo.CurrentOrgId, patient_id, recordStartTime, recordEndTime)
	} else if is_upload == 2 {
		monthPrescriptions, _ = service.GetMonthUploadHisHospitalPrescription(adminInfo.CurrentOrgId, patient_id, recordStartTime, recordEndTime)
	} else {
		monthPrescriptions, _ = service.GetAllMonthHisHospitalPrescription(adminInfo.CurrentOrgId, patient_id, recordStartTime, recordEndTime)
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"month_prescriptions": monthPrescriptions,
		"his_info":            record,
	})
}

func (c *HisHospitalApiController) GetExportHisHospitalUnChargeData() {
	start_time_str := c.GetString("start_time")
	end_time_str := c.GetString("end_time")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminInfo := c.GetAdminUserInfo()
	theStartTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time_str+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordStartTime := theStartTime.Unix()
	theEndTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time_str+" 00:00:00", loc)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	recordEndTime := theEndTime.Unix()
	//var prescriptions []*models.HisPrescription
	var prescriptions []*models.ExportHisPrescription
	prescriptions, _ = service.GetUnChargeHisHospitalPrescription(adminInfo.CurrentOrgId, recordStartTime, recordEndTime)
	c.ServeSuccessJSON(map[string]interface{}{
		"month_prescriptions": prescriptions,
	})
}