package coordinate

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

type ZBDrug struct {
	Code   string `json:"code"`
	Msg    string `json:"msg"`
	Result []struct {
		Bbx01 int64  `json:"bbx01"`
		Bby01 int64  `json:"bby01"`
		Kf    string `json:"库房id"`
	} `json:"result"`
}

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"`
		Code            string        `json:"code"`
	} `json:"result"`
}

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

type CoordinateController struct {
	controllers.BaseAuthAPIController
}

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

type GroupPrescription struct {
	GroupNo int64
	PId     int64
}

func CoordinateRegistRouters() {
	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 = 10340
	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.FindLastPatientPrescriptionInfoTwoTen(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.GetUnSettleHisPrescriptionFiveTen(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.BaseDrugLib.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

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

		var info3 models.UploadInfo
		info3.Vaa01 = res.Result[0].Vaa01
		info3.Fasong = "1"
		info3.Vaa07 = res.Result[0].Vaa07
		info3.Bck01c = departmwnt.Number
		info3.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 presInfos2 []*models.PresInfo
		var presInfos3 []*models.PresInfo

		var doctoradvices []*models.HisDoctorAdviceInfo
		var projects []*models.HisPrescriptionProject

		var groups []*GroupPrescription
		for _, item := range prescriptions {
			for _, subItem := range item.HisDoctorAdviceInfo {
				doctoradvices = append(doctoradvices, subItem)
			}
		}

		for _, item := range prescriptions {
			for _, subItem := range item.HisPrescriptionProject {
				projects = append(projects, subItem)
			}
		}

		for _, item := range doctoradvices {
			var gp GroupPrescription
			gp.GroupNo = item.Groupno
			gp.PId = item.PrescriptionId
			groups = append(groups, &gp)
		}
		groups = RemoveRepeatedGroupElement(groups)

		type DoctorAdvices struct {
			GroupNo int64
			item    []*models.HisDoctorAdviceInfo
		}
		var doctoradvice []*DoctorAdvices

		for index, group := range groups {
			var da DoctorAdvices
			da.GroupNo = group.GroupNo + int64(index)
			for _, item := range doctoradvices {
				if group.GroupNo == item.Groupno && group.PId == item.PrescriptionId {
					da.item = append(da.item, item)
				}
			}

			doctoradvice = append(doctoradvice, &da)
		}

		fmt.Println("doctoradvice")
		fmt.Println(doctoradvice)

		var presInfo models.PresInfo
		presInfo.Cbmid = "0"
		presInfo.Cbm06 = "0"
		presInfo.Cbm07 = "0"
		var presDetails []*models.PresDetail

		var presInfo2 models.PresInfo
		presInfo2.Cbmid = "0"
		presInfo2.Cbm06 = "9"
		presInfo2.Cbm07 = "0"
		var presDetails2 []*models.PresDetail

		var presInfo3 models.PresInfo
		presInfo3.Cbmid = "0"
		presInfo3.Cbm06 = "5"
		presInfo3.Cbm07 = "0"
		var presDetails3 []*models.PresDetail

		for _, item := range doctoradvice {
			var presDetail models.PresDetail
			presDetail.Vaf59 = strconv.FormatInt(item.GroupNo, 10)
			var infoItems []*models.Item
			for index, subItem := range item.item {
				ef, _ := service.GetExecutionFrequencyByName(subItem.ExecutionFrequency, subItem.UserOrgId)
				result3, request3 := service.GetDrugInfo(subItem.BaseDrugLib.MedicalInsuranceNumber)
				saveLog(result3, request3, "查询药品", "查询药品", org.OrgName)

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

				var infoItem models.Item
				infoItem.Rownr = strconv.FormatInt(int64(index+1), 10)
				infoItem.Vaf11 = "2"
				infoItem.Vaf36 = time.Unix(subItem.CreatedTime, 0).Format("2006-01-02 15:04:05")
				infoItem.Bbx01 = subItem.BaseDrugLib.MedicalInsuranceNumber
				infoItem.Bda01 = "1"
				infoItem.Bby01 = strconv.FormatInt(res.Result[0].Bby01, 10)
				if subItem.BaseDrugLib.MinUnit != subItem.BaseDrugLib.DoseUnit {
					infoItem.Vaf22 = subItem.BaseDrugLib.DrugName + " " + subItem.BaseDrugLib.DoseUnit + "*" + strconv.FormatInt(subItem.BaseDrugLib.MinNumber, 10) + subItem.BaseDrugLib.MinUnit + "/" + subItem.BaseDrugLib.MaxUnit
				}
				infoItem.Vaf14 = subItem.BaseDrugLib.DrugName
				infoItem.Bdi01 = ef.Code
				infoItem.Vaf17 = strconv.FormatInt(subItem.Day, 10)
				infoItem.Vaf18 = fmt.Sprintf("%.2f", subItem.SingleDose)
				infoItem.Vaf15 = subItem.DeliveryWay

				infoItem.Vaf20 = fmt.Sprintf("%.2f", subItem.SingleDose)
				infoItem.Vaf21 = fmt.Sprintf("%.2f", subItem.PrescribingNumber)
				infoItem.Vaf35 = "0"
				infoItem.Vaf32 = "0"
				fmt.Println(res.Result[0].Kf)
				infoItem.Bck01b = res.Result[0].Kf
				infoItem.Bck01d = departmwnt.Number
				infoItem.Vaf58 = "0"
				infoItem.Vaf61 = "1"
				infoItems = append(infoItems, &infoItem)

				var infoItem2 models.Item //用药途径
				project, _ := service.GetWayInfoByName(subItem.DeliveryWay, 10340)
				infoItem2.Rownr = "0"
				infoItem2.Vaf11 = "2"
				infoItem2.Vaf36 = time.Unix(subItem.CreatedTime, 0).Format("2006-01-02 15:04:05")
				infoItem2.Bbx01 = project.MedicalCode
				infoItem2.Bda01 = "Z"
				infoItem2.Bby01 = project.MedicalCode
				infoItem2.Vaf14 = project.ProjectName
				infoItem2.Vaf15 = project.ProjectName
				infoItem2.Bdi01 = "160"
				infoItem2.Vaf17 = strconv.FormatInt(subItem.Day, 10)
				infoItem2.Vaf20 = "1"
				infoItem2.Vaf21 = "1"
				infoItem2.Vaf35 = "0"
				infoItem2.Vaf18 = "0"
				infoItem2.Vaf32 = "1"
				infoItem2.Bck01b = departmwnt.Number
				infoItem2.Bck01d = res.Result[0].Kf
				infoItem2.Vaf58 = "0"
				infoItem2.Vaf61 = "1"
				infoItems = append(infoItems, &infoItem2)

				fmt.Println(infoItems)
			}
			presDetail.Item = infoItems
			presDetails = append(presDetails, &presDetail)
		}

		for index, subItem := range projects {

			if subItem.Type == 2 {
				var presDetail2 models.PresDetail
				presDetail2.Vaf59 = strconv.FormatInt(int64(index+1), 10)
				var infoItems2 []*models.Item
				var infoItem models.Item
				infoItem.Rownr = "1"
				infoItem.Vaf11 = "0"
				infoItem.Vaf36 = time.Unix(subItem.Ctime, 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 = "0"
				infoItem.Vaf14 = subItem.HisProject.ProjectName
				infoItem.Vaf22 = subItem.HisProject.ProjectName
				infoItem.Bdi01 = "160"
				infoItem.Vaf17 = "1"
				infoItem.Vaf20 = "1"
				infoItem.Vaf21 = 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"
				infoItems2 = append(infoItems2, &infoItem)
				presDetail2.Item = infoItems2
				presDetails2 = append(presDetails2, &presDetail2)

			} else {
				var presDetail3 models.PresDetail
				presDetail3.Vaf59 = strconv.FormatInt(int64(index+1), 10)
				var infoItems2 []*models.Item
				var infoItem models.Item
				result3, request3 := service.GetGoodInfo(subItem.GoodInfo.MedicalInsuranceNumber)
				saveLog(result3, request3, "查询耗材", "查询耗材", org.OrgName)
				var res ZBDrug
				if err := json.Unmarshal([]byte(result3), &res); err != nil {
					utils.ErrorLog("解析失败：%v", err)
					c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}

				infoItem.Rownr = "1"
				infoItem.Vaf11 = "0"
				infoItem.Vaf36 = time.Unix(subItem.Ctime, 0).Format("2006-01-02 15:04:05")
				infoItem.Bbx01 = subItem.GoodInfo.MedicalInsuranceNumber
				infoItem.Bda01 = "M"
				infoItem.Bby01 = strconv.FormatInt(res.Result[0].Bby01, 10)
				infoItem.Vaf14 = subItem.GoodInfo.GoodName + " " + subItem.GoodInfo.SpecificationName
				infoItem.Vaf22 = subItem.GoodInfo.GoodName + " " + subItem.GoodInfo.SpecificationName
				infoItem.Bdi01 = "160"
				infoItem.Vaf17 = "1"
				infoItem.Vaf18 = "0"
				infoItem.Vaf20 = subItem.SingleDose
				infoItem.Vaf21 = subItem.Count
				infoItem.Vaf35 = "0"
				infoItem.Vaf32 = "0"
				infoItem.Bck01b = res.Result[0].Kf
				infoItem.Bck01d = departmwnt.Number
				infoItem.Vaf58 = "0"
				infoItem.Vaf61 = "1"
				infoItems2 = append(infoItems2, &infoItem)
				presDetail3.Item = infoItems2
				presDetails3 = append(presDetails3, &presDetail3)

			}
		}

		presInfo.PresDetail = presDetails
		presInfo2.PresDetail = presDetails2
		presInfo3.PresDetail = presDetails3

		presInfos = append(presInfos, &presInfo)
		presInfos2 = append(presInfos2, &presInfo2)
		presInfos3 = append(presInfos3, &presInfo3)

		info.PresInfo = presInfos
		info2.PresInfo = presInfos2
		info3.PresInfo = presInfos3

		var infos []models.UploadInfo

		infos = append(infos, info)
		infos = append(infos, info2)
		infos = append(infos, info3)

		var result2 string
		var request2 string
		if res.Result[0].Type == "1" {
			for _, item := range infos {
				result2, request2 = service.UploadPrescriptionForCoordinate(item)
				saveLog(result2, request2, "上传明细", "上传明细", org.OrgName)

			}

		} else {
			for _, item := range infos {
				result2, request2 = service.UploadPrescriptionForCoordinateHospital(item)
				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" && len(res2.Result) > 0 && res2.Result[0].Code != "500" && len(res2.Result[0].List) > 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:                  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.UpdateHisPatientStatusTwo(&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.ErrorCodeCreateOrderExceptionT)
				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.UpdataHisPateintTwoTen(&his)
			err = service.UpDatePrescriptionNumber(org_id, ids, order.Number)
			err = service.UpDateHisPrescriptionInfoNumberTen(org_id, patient_id, order.Number, recordDateTime, his.ID)
			err = service.UpdataOrderStatusThreeTen(strconv.FormatInt(int64(chrgBchno), 10), org_id)

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

		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"failed_code": -10,
				"msg":         res2.Msg + "----" + res2.Result[0].ResultMsg,
			})

		}

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

	}

}

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("记录日志"))
		}
	}

}

func RemoveRepeatedGroupElement(arr []*GroupPrescription) (newArr []*GroupPrescription) {
	newArr = make([]*GroupPrescription, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i].GroupNo == arr[j].GroupNo && arr[i].PId == arr[j].PId {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}
