package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"math/rand"
	"os"
	"strconv"
	"strings"
	"time"
)

type CoordinateController struct {
	BaseAPIController
}

type ResultReg struct {
	ResultCode string `json:"resultCode"`
	ResultDesc string `json:"resultDesc"`
	InfoSeq    string `json:"infoSeq"`
}

type ResultSettle struct {
	ResultCode string `json:"resultCode"`
	ResultDesc string `json:"resultDesc"`
}

type ResultCancelSettle struct {
	ResultCode string `json:"resultCode"`
	ResultDesc string `json:"resultDesc"`
}

type Settle struct {
	PatientId string `json:"resultCode"`
	DocId     string `json:"docId"`
	InfoSeq   string `json:"infoSeq"`
}

type Refund struct {
	PatientId string `json:"resultCode"`
	DocId     string `json:"docId"`
	InfoSeq   string `json:"infoSeq"`
}

type RefundDetail struct {
	Msg    string `json:"msg"`
	Result []struct {
		ResultMsg string `json:"resultMsg"`
		Code      string `json:"code"`
		Records   int    `json:"records"`
		TotalPage int    `json:"totalPage"`
		List      []struct {
			Zae01 int64 `json:"ZAE01"`
		} `json:"list"`
		RecordsTotal  int    `json:"recordsTotal"`
		Pagenumber    int    `json:"pagenumber"`
		Result        string `json:"result"`
		Total         int    `json:"total"`
		RecordsFtered int    `json:"recordsFtered"`
		Page          int    `json:"page"`
	} `json:"result"`
	Code string `json:"code"`
}

type ResultQuery struct {
	Msg    string `json:"msg"`
	Result []struct {
		Type      string `json:"type"`
		Name      string `json:"name"`
		Vaa01     int    `json:"vaa01"`
		Vaa07     int    `json:"vaa07"`
		Visittime string `json:"visittime"`
	} `json:"result"`
	Code string `json:"code"`
}

type ResultUpload struct {
	Code   string `json:"code"`
	Msg    string `json:"msg"`
	Result []struct {
		List            []interface{} `json:"list"`
		Page            int64         `json:"page"`
		Pagenumber      int64         `json:"pagenumber"`
		Records         int64         `json:"records"`
		RecordsFiltered int64         `json:"recordsFiltered"`
		RecordsTotal    int64         `json:"recordsTotal"`
		Result          string        `json:"result"`
		ResultMsg       string        `json:"resultMsg"`
		Total           int64         `json:"total"`
		TotalPage       int64         `json:"totalPage"`
		Userdata        string        `json:"userdata"`
	} `json:"result"`
}

func CoordinateRcegistRouters() {
	beego.Router("/coordinate/check", &CoordinateController{}, "get:SavePatientMessageInfo")
	//坐标挂号
	beego.Router("/coordinate/register", &CoordinateController{}, "get:Register")
	//坐标记账
	beego.Router("/coordinate/opKeepAccounts", &CoordinateController{}, "get:OpKeepAccounts")
	//坐标撤销记账
	beego.Router("/coordinate/opCancelKeepAccounts", &CoordinateController{}, "get:OpCancelKeepAccounts")
	//坐标结算回调
	beego.Router("/coordinate/settle", &CoordinateController{}, "post:Settle")
	//坐标退费回调
	beego.Router("/coordinate/refund", &CoordinateController{}, "post:Refund")
	//坐标患者查询~上传医嘱~结算功能
	beego.Router("/coordinate/settleAccount", &CoordinateController{}, "get:SettleAccount")

}

func (c *CoordinateController) SettleAccount() {
	patient_id, _ := c.GetInt64("patient_id")
	record_date := c.GetString("record_date")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	diagnosis_id := c.GetString("diagnosis")
	sick_type, _ := c.GetInt64("sick_type")
	reg_type, _ := c.GetInt64("p_type")
	org_id, _ := c.GetInt64("org_id")
	org_id = 3877
	org, _ := service.GetOrgById(org_id)
	patient, _ := service.GetPatientByID(org.Id, patient_id)
	settle_accounts_type, _ := c.GetInt64("settle_accounts_type")

	result, request := service.GetHisPatientForCoordinate(patient.IdCardNo)
	saveLog(result, request, "查询", "查询", org.OrgName)
	var res ResultQuery
	if err := json.Unmarshal([]byte(result), &res); err != nil {
		utils.ErrorLog("解析失败:%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	if res.Code == "10000" {
		if len(res.Result) == 0 {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeHisPatientNoRegException)
			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
		}
		org_id := org.Id
		recordDateTime := theTime.Unix()
		patientPrescription, _ := service.FindPatientPrescriptionInfoTwo(org_id, patient.ID, recordDateTime, 2)
		if patientPrescription.ID == 0 {
			patientPrescription, _ = service.FindLastPatientPrescriptionInfo(org_id, patient.ID, recordDateTime)
		}
		departmwnt, _ := service.GetDepartMentDetail(patientPrescription.Departments)
		doctor_info, _ := service.GetAdminUserInfoByID(org_id, patientPrescription.DoctorId)
		//admin_user_info, _ := service.GetAdminUserInfoByID(org_id, admin_user_id)

		var prescriptions []*models.HisPrescription

		if settle_accounts_type == 1 { //日结
			prescriptions, _ = service.GetUnSettleHisPrescriptionFive(org_id, patient_id, recordDateTime, 2)
		} 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.GetUnSettleMonthHisPrescription(org_id, patient_id, recordStartTime, recordEndTime)
		}
		var total float64

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

		}

		var ids []int64

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

		var customs []*models.NewCustomTwo
		for _, item := range prescriptions {
			if item.Type == 1 { //药品
				for _, subItem := range item.HisDoctorAdviceInfo {
					cus := &models.NewCustomTwo{
						AdviceId:         subItem.ID,
						ProjectId:        0,
						DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*subItem.PrescribingNumber),
						Cut:              fmt.Sprintf("%.4f", subItem.PrescribingNumber),
						FeedetlSn:        subItem.FeedetlSn,
						Price:            fmt.Sprintf("%.2f", subItem.Price),
						MedListCodg:      subItem.Drug.MedicalInsuranceNumber,
						Type:             1,
					}
					customs = append(customs, cus)
				}
			}
			if item.Type == 2 { //项目
				for _, subItem := range item.HisPrescriptionProject {
					if subItem.Type == 2 {
						cnt, _ := strconv.ParseFloat(subItem.Count, 64)
						cus := &models.NewCustomTwo{
							AdviceId:         0,
							ProjectId:        subItem.ID,
							DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*cnt),
							Cut:              fmt.Sprintf("%.4f", cnt),
							FeedetlSn:        subItem.FeedetlSn,
							Price:            fmt.Sprintf("%.4f", float64(subItem.Price)),
							MedListCodg:      subItem.HisProject.MedicalCode,
							Type:             2,
						}
						customs = append(customs, cus)

					} else {
						cnt, _ := strconv.ParseFloat(subItem.Count, 64)
						cus := &models.NewCustomTwo{
							AdviceId:         0,
							ProjectId:        subItem.ID,
							DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*cnt),
							Cut:              fmt.Sprintf("%.4f", cnt),
							FeedetlSn:        subItem.FeedetlSn,
							Price:            fmt.Sprintf("%.4f", float64(subItem.Price)),
							MedListCodg:      subItem.GoodInfo.MedicalInsuranceNumber,
							Type:             3,
						}
						customs = append(customs, cus)
					}

				}
			}
		}

		var info models.UploadInfo
		info.Vaa01 = res.Result[0].Vaa01
		info.Fasong = "1"
		info.Vaa07 = res.Result[0].Vaa07
		info.Bck01c = departmwnt.Number
		info.Bce02a = doctor_info.DoctorNumber

		diagnosis_ids := strings.Split(patientPrescription.Diagnosis, ",")
		var config []*models.HisXtDiagnoseConfig
		for _, item := range diagnosis_ids {
			id, _ := strconv.ParseInt(item, 10, 64)
			diagnosisConfig, _ := service.FindDiagnoseById(id)
			config = append(config, diagnosisConfig)
		}
		for index, item := range config {
			var diag models.Diag
			diag.Vao06 = strconv.FormatInt(int64(index+1), 10)
			diag.Bak02 = item.CountryCode
			info.Diag = append(info.Diag, &diag)
		}
		var presInfos []*models.PresInfo
		var presDetails []*models.PresDetail
		for index, item := range prescriptions {
			var presDetail models.PresDetail
			var presInfo models.PresInfo
			presInfo.Cbmid = strconv.FormatInt(item.ID, 10)
			if item.Type == 1 {
				presInfo.Cbm06 = "0"
			} else {
				presInfo.Cbm06 = "5"
			}

			if item.Type == 1 {
				presInfo.Cbm07 = item.MedType
			} else {
				presInfo.Cbm07 = item.MedType
			}

			presDetail.Vaf59 = strconv.FormatInt(int64(index+1), 10)
			var infoItems []*models.Item
			for _, subItem := range item.HisDoctorAdviceInfo {
				ef, _ := service.GetExecutionFrequencyByName(subItem.ExecutionFrequency, subItem.UserOrgId)

				var infoItem models.Item
				infoItem.Rownr = "0"
				infoItem.Vaf11 = "1"
				infoItem.Vaf36 = time.Unix(subItem.ExecutionTime, 0).Format("2006-01-02 15:04:05")
				infoItem.Bbx01 = subItem.Drug.MedicalInsuranceNumber
				infoItem.Bda01 = "1"
				infoItem.Bby01 = ""
				if subItem.Drug.MinUnit != subItem.Drug.DoseUnit {
					infoItem.Vaf22 = subItem.Drug.DrugName + " " + subItem.Drug.Dose + subItem.Drug.DoseUnit + "*" + strconv.FormatInt(subItem.Drug.MinNumber, 10) + subItem.Drug.MinUnit + "/" + subItem.Drug.MaxUnit
				}
				infoItem.Vaf14 = subItem.Drug.DrugName
				infoItem.Bdi01 = ef.Code
				infoItem.Vaf17 = strconv.FormatInt(subItem.Day, 10)
				infoItem.Vaf20 = fmt.Sprintf("%.2f", subItem.SingleDose)
				infoItem.Vaf21 = fmt.Sprintf("%.2f", subItem.PrescribingNumber)
				infoItem.Vaf35 = "0"
				infoItem.Vaf32 = "0"
				infoItem.Bck01b = departmwnt.Number
				infoItem.Bck01d = departmwnt.Number
				infoItem.Vaf58 = "0"
				infoItem.Vaf61 = "1"
				infoItems = append(infoItems, &infoItem)
			}
			for _, subItem := range item.HisPrescriptionProject {
				ef, _ := service.GetExecutionFrequencyByName(subItem.ExecutionFrequency, subItem.UserOrgId)

				if subItem.Type == 2 {
					var infoItem models.Item
					infoItem.Rownr = "0"
					infoItem.Vaf11 = "1"
					infoItem.Vaf36 = time.Unix(subItem.ExecutionTime, 0).Format("2006-01-02 15:04:05")
					infoItem.Bbx01 = subItem.HisProject.MedicalCode

					if subItem.HisProject.CostClassify == 2 {
						infoItem.Bda01 = "T"
					} else if subItem.HisProject.CostClassify == 3 {
						infoItem.Bda01 = "L"
					} else {
						infoItem.Bda01 = "T"
					}
					infoItem.Bby01 = ""
					infoItem.Vaf22 = subItem.HisProject.ProjectName
					infoItem.Bdi01 = ef.Code
					infoItem.Vaf17 = subItem.Day
					infoItem.Vaf20 = fmt.Sprintf("%.2f", subItem.SingleDose)
					infoItem.Vaf21 = fmt.Sprintf("%.2f", subItem.Count)
					infoItem.Vaf35 = "0"
					infoItem.Vaf18 = 0
					infoItem.Vaf32 = "0"
					infoItem.Bck01b = departmwnt.Number
					infoItem.Bck01d = departmwnt.Number
					infoItem.Vaf58 = "0"
					infoItem.Vaf61 = "1"
					infoItems = append(infoItems, &infoItem)

				} else {
					var infoItem models.Item
					infoItem.Rownr = "0"
					infoItem.Vaf11 = "1"
					infoItem.Vaf36 = time.Unix(subItem.ExecutionTime, 0).Format("2006-01-02 15:04:05")
					infoItem.Bbx01 = subItem.GoodInfo.MedicalInsuranceNumber
					infoItem.Bda01 = "M"
					infoItem.Bby01 = ""
					infoItem.Vaf22 = subItem.GoodInfo.GoodName + " " + subItem.GoodInfo.SpecificationName
					infoItem.Bdi01 = ef.Code
					infoItem.Vaf17 = subItem.Day
					infoItem.Vaf20 = fmt.Sprintf("%.2f", subItem.SingleDose)
					infoItem.Vaf21 = fmt.Sprintf("%.2f", subItem.Count)
					infoItem.Vaf35 = "0"
					infoItem.Vaf32 = "0"
					infoItem.Bck01b = departmwnt.Number
					infoItem.Bck01d = departmwnt.Number
					infoItem.Vaf58 = "0"
					infoItem.Vaf61 = "1"
					infoItems = append(infoItems, &infoItem)

				}

			}
			presDetail.Item = infoItems
			presDetails = append(presDetails, &presDetail)
			presInfo.PresDetail = presDetails
			presInfos = append(presInfos, &presInfo)
		}
		info.PresInfo = presInfos

		result2, request2 := service.UploadPrescriptionForCoordinate(info)
		saveLog(result2, request2, "上传明细", "上传明细", org.OrgName)

		var res2 ResultUpload
		if err := json.Unmarshal([]byte(result2), &res2); err != nil {
			utils.ErrorLog("解析失败:%v", err)
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		if res2.Code == "10000" {

			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(patient.ID, 10)
			his := models.VMHisPatient{
				Name:                   patient.Name,
				Gender:                 patient.Gender,
				Birthday:               patient.Birthday,
				MedicalTreatmentType:   0,
				IdType:                 1,
				IdCardNo:               patient.IdCardNo,
				BalanceAccountsType:    1,
				MedicalInsuranceNumber: "",
				RegisterType:           0,
				RegisterCost:           0,
				TreatmentCost:          0,
				Status:                 1,
				Ctime:                  time.Now().Unix(),
				Mtime:                  time.Now().Unix(),
				PsnNo:                  strconv.FormatInt(int64(res.Result[0].Vaa01), 10),
				PsnCertType:            "",
				Certno:                 patient.IdCardNo,
				PsnName:                patient.Name,
				Gend:                   "",
				Naty:                   "",
				Brdy:                   "",
				Age:                    0,
				Iinfo:                  "",
				Idetinfo:               "",
				PatientId:              patient.ID,
				RecordDate:             theTime.Unix(),
				UserOrgId:              org_id,
				AdminUserId:            admin_user_id,
				IsReturn:               1,
				Doctor:                 patientPrescription.DoctorId,
				Departments:            patientPrescription.Departments,
				IptOtpNo:               ipt_otp_no,
				Number:                 strconv.FormatInt(int64(res.Result[0].Vaa07), 10),
				PhoneNumber:            patient.Phone,
			}
			service.UpdateHisPatientStatus(&his)
			service.UpdateHisPrescriptionHisID(his.ID, patient.ID, recordDateTime, org_id)
			tm := time.Unix(time.Now().Unix(), 0)

			order := &models.HisOrder{
				PsnNo:              his.PsnNo,
				UserOrgId:          org_id,
				HisPatientId:       his.ID,
				PatientId:          patient_id,
				SettleAccountsDate: recordDateTime,
				Ctime:              time.Now().Unix(),
				Mtime:              time.Now().Unix(),
				Status:             1,
				OrderStatus:        1,
				MdtrtId:            his.Number,
				Number:             ipt_otp_no,
				SetlId:             "",
				MedfeeSumamt:       total,
				MedType:            strconv.Itoa(int(reg_type)),
				SettleEndTime:      0,
				SettleStartTime:    0,
				SettleType:         settle_accounts_type,
				Diagnosis:          diagnosis_id,
				PType:              2,
				SetlTime:           tm.Format("2006-01-02 15:04:05"),
			}
			err = service.CreateOrder(order)
			if err != nil {
				c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateOrderException)
				return
			}

			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:        patient_id,
					Status:           1,
					Mtime:            time.Now().Unix(),
					Ctime:            time.Now().Unix(),
					UserOrgId:        org_id,
					HisPatientId:     his.ID,
					OrderId:          order.ID,
					ProjectId:        project_id,
					Type:             types,
					ItemId:           item_id,
				}
				service.CreateOrderInfo(info)
			}
			his.Diagnosis = diagnosis_id
			his.SickType = sick_type
			his.RegisterType = reg_type
			his.MedicalTreatmentType = reg_type
			service.UpdataHisPateintTwo(&his)
			err = service.UpDatePrescriptionNumber(org_id, ids, strconv.FormatInt(int64(chrgBchno), 10))
			err = service.UpDateHisPrescriptionInfoNumber(org_id, patient_id, strconv.FormatInt(int64(chrgBchno), 10), recordDateTime, his.ID)
			err = service.UpdataOrderStatusThree(strconv.FormatInt(int64(chrgBchno), 10), org_id)

			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "医嘱保存成功",
			})

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

		}

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

	}

}

func (c *CoordinateController) Settle() {
	//参数1 patient_id
	//参数2 就诊号
	//参数3 单据id
	fmt.Println(c.Ctx.Request.Body)

	body, _ := ioutil.ReadAll(c.Ctx.Request.Body)
	fmt.Println(string(body))

	var respJSON map[string]interface{}
	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
		utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
		return
	}
	patien_id := respJSON["vaa01"].(float64)
	infoSeq := respJSON["vaa07"].(float64)

	//strconv.For(patien_id, 10)

	vaa001 := fmt.Sprintf("%f", patien_id)
	vaa007 := fmt.Sprintf("%f", infoSeq)

	setl_id := respJSON["setl_id"].(string)
	order, _ := service.GetHisOrderFour(vaa001, vaa007, "")
	order.SetlId = setl_id
	if order.ID == 0 {
		json := make(map[string]interface{})
		json["msg"] = "结算记录不存在,请检查参数是否正确"
		json["code"] = "-1"
		c.Data["json"] = json
		c.ServeJSON()
		return
	}
	order.OrderStatus = 2
	service.UpDateOrder(order)
	service.UpdataOrderStatusTwo(order.Number, order.UserOrgId)
	json := make(map[string]interface{})
	json["msg"] = "结算成功"
	json["code"] = "0"
	c.Data["json"] = json
	c.ServeJSON()
	return
}
func (c *CoordinateController) Refund() {
	//参数1 patient_id
	//参数2 就诊号
	//参数3 单据id
	body, _ := ioutil.ReadAll(c.Ctx.Request.Body)
	var respJSON map[string]interface{}
	if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
		utils.ErrorLog("接口返回数据解析JSON失败: %v", err)
		return
	}
	patien_id := respJSON["vaa01"].(float64)
	infoSeq := respJSON["vaa07"].(float64)

	//strconv.For(patien_id, 10)

	vaa001 := fmt.Sprintf("%f", patien_id)
	vaa007 := fmt.Sprintf("%f", infoSeq)

	docId := respJSON["setl_id"].(string)
	order, _ := service.GetHisOrderFour(vaa001, vaa007, docId)
	if order.ID == 0 {
		json := make(map[string]interface{})
		json["msg"] = "结算记录不存在,请检查参数是否正确"
		json["code"] = "-1"
		c.Data["json"] = json
		c.ServeJSON()
		return
	}
	service.UpdataOrderStatus(order.ID, order.Number, order.UserOrgId)
	json := make(map[string]interface{})
	json["msg"] = "退费成功"
	json["code"] = "0"
	c.Data["json"] = json
	c.ServeJSON()
	return
}

func (c *CoordinateController) SavePatientMessageInfo() {
	result, request_log := service.SavePatientMessageInfo()
	fmt.Println(result)
	fmt.Println(request_log)

}

func (c *CoordinateController) Register() {
	patient_id, _ := c.GetInt64("patient_id")
	diagnosis_time := c.GetString("diagnosis_time")
	record_date := c.GetString("record_date")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	org_id, _ := c.GetInt64("org_id")
	patient, _ := service.GetPatientByID(org_id, patient_id)
	org, _ := service.GetOrgById(org_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
	}
	if len(patient.ZbPatientId) == 0 {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorPsnNoEmpty)
		return
	}

	recordDateTime := theTime.Unix()
	patientPrescription, _ := service.FindPatientPrescriptionInfoTwo(org_id, patient.ID, recordDateTime, 2)
	if patientPrescription.ID == 0 {
		patientPrescription, _ = service.FindLastPatientPrescriptionInfo(org_id, patient.ID, recordDateTime)
	}
	doctor_info, _ := service.GetAdminUserInfoByID(org_id, patientPrescription.DoctorId)
	admin_user_info, _ := service.GetAdminUserInfoByID(org_id, admin_user_id)
	reg := models.Reg{
		DeptId:      "0112",
		PatientId:   patient.ZbPatientId,
		PatientName: patient.Name,
		DoctorId:    doctor_info.DoctorNumber,
		RegDate:     strings.Split(diagnosis_time, " ")[0],
		RegFee:      "0",
		TreatFee:    "0",
		OperatorId:  admin_user_info.UserName,
		IdCardNo:    patient.IdCardNo,
	}

	result, request_log := service.SaveReg(reg)
	fmt.Println(result)
	fmt.Println(request_log)
	saveLog(result, request_log, "登记", "登记", org.OrgName)
	var res ResultReg
	if err := json.Unmarshal([]byte(result), &res); err != nil {
		utils.ErrorLog("解析失败:%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	if res.ResultCode == "0" {
		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(patient.ID, 10)
		his := models.VMHisPatient{
			Name:                   patient.Name,
			Gender:                 patient.Gender,
			Birthday:               patient.Birthday,
			MedicalTreatmentType:   0,
			IdType:                 1,
			IdCardNo:               patient.IdCardNo,
			BalanceAccountsType:    1,
			MedicalInsuranceNumber: "",
			RegisterType:           0,
			RegisterCost:           0,
			TreatmentCost:          0,
			Status:                 1,
			Ctime:                  time.Now().Unix(),
			Mtime:                  time.Now().Unix(),
			PsnNo:                  patient.ZbPatientId,
			PsnCertType:            "",
			Certno:                 patient.IdCardNo,
			PsnName:                patient.Name,
			Gend:                   "",
			Naty:                   "",
			Brdy:                   "",
			Age:                    0,
			Iinfo:                  "",
			Idetinfo:               "",
			PatientId:              patient.ID,
			RecordDate:             theTime.Unix(),
			UserOrgId:              org_id,
			AdminUserId:            admin_user_id,
			IsReturn:               1,
			Doctor:                 patientPrescription.DoctorId,
			Departments:            patientPrescription.Departments,
			IptOtpNo:               ipt_otp_no,
			Number:                 res.InfoSeq,
			PhoneNumber:            patient.Phone,
		}
		service.UpdateHisPatientStatus(&his)
		service.UpdateHisPrescriptionHisID(his.ID, patient.ID, recordDateTime, org_id)
		c.ServeSuccessJSON(map[string]interface{}{
			"his_info": his,
		})
	} else {

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

	}
}

//func (c *CoordinateController) GetWaitPayDetail() {
//	result, request_log := service.GetWaitPayDetail()
//	fmt.Println(result)
//	fmt.Println(request_log)
//
//}

func (c *CoordinateController) OpKeepAccounts() {
	id, _ := c.GetInt64("id")
	record_time := c.GetString("record_time")
	his_patient_id, _ := c.GetInt64("his_patient_id")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	settle_accounts_type, _ := c.GetInt64("settle_accounts_type")
	fapiao_code := c.GetString("fapiao_code")
	fapiao_number := c.GetString("fapiao_number")
	diagnosis_id := c.GetString("diagnosis")
	sick_type, _ := c.GetInt64("sick_type")
	reg_type, _ := c.GetInt64("p_type")
	org_id, _ := c.GetInt64("org_id")
	org, _ := service.GetOrgById(org_id)

	his, _ := service.GetHisPatientByIdThree(his_patient_id)

	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

	//ids_str := c.GetString("ids")
	//ids_arr := strings.Split(ids_str, ",")

	if settle_accounts_type == 1 { //日结
		//fmt.Println(reg_type)
		prescriptions, _ = service.GetUnSettleHisPrescriptionFive(org_id, id, recordDateTime, 2)

	} 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.GetUnSettleMonthHisPrescription(org_id, id, recordStartTime, recordEndTime)
	}

	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 {
		fmt.Println(item)
		if item.Type == 1 { //药品
			for _, subItem := range item.HisDoctorAdviceInfo {
				total = total + (subItem.Price * subItem.PrescribingNumber)
			}
		}
		if item.Type == 2 { //项目
			for _, subItem := range item.HisPrescriptionProject {
				cnt, _ := strconv.ParseFloat(subItem.Count, 64)
				total = total + (subItem.Price * cnt)
			}
		}

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

	tm := time.Unix(time.Now().Unix(), 0)

	var customs []*models.NewCustomTwo
	for _, item := range prescriptions {
		if item.Type == 1 { //药品
			for _, subItem := range item.HisDoctorAdviceInfo {
				cus := &models.NewCustomTwo{
					AdviceId:         subItem.ID,
					ProjectId:        0,
					DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*subItem.PrescribingNumber),
					Cut:              fmt.Sprintf("%.4f", subItem.PrescribingNumber),
					FeedetlSn:        subItem.FeedetlSn,
					Price:            fmt.Sprintf("%.2f", subItem.Price),
					MedListCodg:      subItem.Drug.MedicalInsuranceNumber,
					Type:             1,
				}
				customs = append(customs, cus)
			}
		}
		if item.Type == 2 { //项目
			for _, subItem := range item.HisPrescriptionProject {
				if subItem.Type == 2 {
					cnt, _ := strconv.ParseFloat(subItem.Count, 64)
					cus := &models.NewCustomTwo{
						AdviceId:         0,
						ProjectId:        subItem.ID,
						DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*cnt),
						Cut:              fmt.Sprintf("%.4f", cnt),
						FeedetlSn:        subItem.FeedetlSn,
						Price:            fmt.Sprintf("%.4f", float64(subItem.Price)),
						MedListCodg:      subItem.HisProject.MedicalCode,
						Type:             2,
					}
					customs = append(customs, cus)

				} else {
					cnt, _ := strconv.ParseFloat(subItem.Count, 64)
					cus := &models.NewCustomTwo{
						AdviceId:         0,
						ProjectId:        subItem.ID,
						DetItemFeeSumamt: fmt.Sprintf("%.4f", subItem.Price*cnt),
						Cut:              fmt.Sprintf("%.4f", cnt),
						FeedetlSn:        subItem.FeedetlSn,
						Price:            fmt.Sprintf("%.4f", float64(subItem.Price)),
						MedListCodg:      subItem.GoodInfo.MedicalInsuranceNumber,
						Type:             3,
					}
					customs = append(customs, cus)

				}

			}
		}
		for _, item := range item.HisAdditionalCharge {
			cus := &models.NewCustomTwo{
				ItemId:           item.ID,
				AdviceId:         0,
				ProjectId:        0,
				DetItemFeeSumamt: fmt.Sprintf("%.4f", item.Price),
				Cut:              fmt.Sprintf("%.4f", float64(item.Count)),
				FeedetlSn:        item.FeedetlSn,
				Price:            fmt.Sprintf("%.4f", float64(item.Price)),
				MedListCodg:      item.XtHisAddtionConfig.Code,
				Type:             3,
			}
			customs = append(customs, cus)
		}
	}
	result, request_log := service.OpKeepAccounts(his.Number, customs)
	saveLog(result, request_log, "记账", "记账", org.OrgName)

	var res ResultSettle
	if err := json.Unmarshal([]byte(result), &res); err != nil {
		utils.ErrorLog("解析失败:%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	if res.ResultCode == "0" {

		//totals, _ := strconv.ParseFloat(total, 64)
		order := &models.HisOrder{
			PsnNo:              his.PsnNo,
			UserOrgId:          org_id,
			HisPatientId:       his.ID,
			PatientId:          id,
			SettleAccountsDate: recordDateTime,
			Ctime:              time.Now().Unix(),
			Mtime:              time.Now().Unix(),
			Status:             1,
			OrderStatus:        1,
			MdtrtId:            his.Number,
			Number:             chrg_bchno,
			SetlId:             "",
			MedfeeSumamt:       total,
			MedType:            strconv.Itoa(int(reg_type)),
			SettleEndTime:      end_time,
			SettleStartTime:    start_time,
			SettleType:         settle_accounts_type,
			FaPiaoCode:         fapiao_code,
			FaPiaoNumber:       fapiao_number,
			Diagnosis:          diagnosis_id,
			PType:              2,
			SetlTime:           tm.Format("2006-01-02 15:04:05"),
		}
		err = service.CreateOrder(order)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateOrderException)
			return
		}

		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:        org_id,
				HisPatientId:     his.ID,
				OrderId:          order.ID,
				ProjectId:        project_id,
				Type:             types,
				ItemId:           item_id,
			}
			service.CreateOrderInfo(info)
		}
		his.Diagnosis = diagnosis_id
		his.SickType = sick_type
		his.RegisterType = reg_type
		his.MedicalTreatmentType = reg_type
		service.UpdataHisPateint(&his)
		err = service.UpDatePrescriptionNumber(org_id, ids, chrg_bchno)
		err = service.UpDateHisPrescriptionInfoNumber(org_id, id, chrg_bchno, recordDateTime, his_patient_id)
		err = service.UpdataOrderStatusThree(chrg_bchno, org_id)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "记账成功",
			})
		}
	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         res.ResultDesc,
		})
	}

}

func (c *CoordinateController) OpCancelKeepAccounts() {
	order_id, _ := c.GetInt64("order_id")
	admin_user_id, _ := c.GetInt64("admin_user_id")
	org_id, _ := c.GetInt64("org_id")
	org, _ := service.GetOrgById(org_id)

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

	role, _ := service.GetAdminUserInfoByID(org_id, admin_user_id)
	result, request_log := service.OpCancelKeepAccounts(order.SetlId, role.UserName, role.DoctorNumber)
	saveLog(result, request_log, "撤销记账", "撤销记账", org.OrgName)
	var res RefundDetail
	if err := json.Unmarshal([]byte(result), &res); err != nil {
		utils.ErrorLog("解析失败:%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		return
	}
	fmt.Println(result)
	fmt.Println(request_log)
	fmt.Println(res)
	flag := 0
	isSuccess := false
	for _, item := range res.Result {
		if item.Code == "200" {
			flag = flag + 1
		}
	}
	if len(res.Result) == flag {
		isSuccess = true
	}
	var errMsg string
	for _, item := range res.Result {
		errMsg = errMsg + "\n" + item.ResultMsg
	}

	if isSuccess {
		err := service.UpdataOrderStatus(order_id, order.Number, org_id)
		if err == nil {
			c.ServeSuccessJSON(map[string]interface{}{
				"msg": "撤销记账成功",
			})
		} else {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"failed_code": -10,
			"msg":         errMsg,
		})

	}
}

//func saveLog(result string, request string, infno string, desc string) {
//
//	org_id, _ := beego.AppConfig.Int64("org_id")
//	miConfig, _ := service.FindMedicalInsuranceInfo(org_id)
//	dir := miConfig.OrgName + "日志"
//	utils.Mkdir(dir)
//	month := time.Unix(1557042972, 0).Format("1")
//	year := time.Now().Format("2006")
//	month = time.Now().Format("01")
//	day := time.Now().Format("02")
//	hour := time.Now().Format("15")
//	min := time.Now().Format("04")
//	sec := time.Now().Format("05")
//
//	result_time := year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec
//
//	file := strconv.FormatInt(org_id, 10) + "_" + year + month + day + "_log"
//	file_name := file + ".txt"
//	file_path := miConfig.OrgName + "日志" + "/" + file_name
//	exist, _ := utils.PathExists(file_path)
//	if exist { //存在
//		fmt.Println("存在")
//		f, err := os.OpenFile(file_path, os.O_WRONLY, 0644)
//		if err != nil {
//			fmt.Println("read fail")
//		}
//		content := "\r\n" + "\r\n" + "\r\n" + result_time + " " + "【 " + desc + infno + "入参" + " 】:" + "\r\n" + request + "\r\n" + result_time + " " + "【 " + desc + infno + "出参" + " 】:" + "\r\n" + result
//		n, _ := f.Seek(0, 2)
//		_, err = f.WriteAt([]byte(content), n)
//
//	} else { //不存在
//		fmt.Println("文件不存在,创建文件")
//		f, err := os.Create(miConfig.OrgName + "日志" + "/" + file_name)
//		defer f.Close()
//		if err != nil {
//		} else {
//			_, err = f.Write([]byte("记录日志"))
//		}
//	}
//
//}

type Charset string

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

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

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

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

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

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

}