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 CoordinateController struct {
	controllers.BaseAuthAPIController
}

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

func CoordinateRegistRouters() {
	beego.Router("/coordinate/check", &CoordinateController{}, "get:SavePatientMessageInfo")
	beego.Router("/coordinate/register", &CoordinateController{}, "get:Register")
	beego.Router("/coordinate/getWaitPayDetail", &CoordinateController{}, "get:GetWaitPayDetail")
	beego.Router("/coordinate/opKeepAccounts", &CoordinateController{}, "get:OpKeepAccounts")
	beego.Router("/coordinate/opCancelKeepAccounts", &CoordinateController{}, "get:OpCancelKeepAccounts")

}

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

}

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")

	patient, _ := service.GetPatientByID(c.GetAdminUserInfo().CurrentOrgId, patient_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()

	patientPrescription, _ := service.FindPatientPrescriptionInfo(c.GetAdminUserInfo().CurrentOrgId, patient.ID, recordDateTime)
	if patientPrescription.ID == 0 {
		patientPrescription, _ = service.FindLastPatientPrescriptionInfo(c.GetAdminUserInfo().CurrentOrgId, patient.ID, recordDateTime)
	}
	department, _ := service.GetDepartMentDetail(patientPrescription.Departments)
	doctor_info, _ := service.GetAdminUserInfoByID(c.GetAdminUserInfo().CurrentOrgId, patientPrescription.DoctorId)

	admin_user_info, _ := service.GetAdminUserInfoByID(c.GetAdminUserInfo().CurrentOrgId, admin_user_id)

	reg := models.Reg{
		DeptId:      department.Number,
		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,
	}

	result, request_log := service.SaveReg(reg)
	fmt.Println(result)
	fmt.Println(request_log)

	saveLog(result, request_log, "reg", "挂号")
	var res ResultReg
	if err := json.Unmarshal([]byte(result), &res); err != nil {
		utils.ErrorLog("解析失败：%v", err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		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(patient.ID, 10)

	his := models.VMHisPatient{
		Name:                   patient.Name,
		Gender:                 patient.Gender,
		Birthday:               patient.Birthday,
		MedicalTreatmentType:   0,
		IdType:                 1,
		IdCardNo:               patient.IdCardNo,
		BalanceAccountsType:    1,
		SocialType:             0,
		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:              c.GetAdminUserInfo().CurrentOrgId,
		AdminUserId:            admin_user_id,
		IsReturn:               1,
		IdCardType:             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, c.GetAdminUserInfo().CurrentOrgId)
	c.ServeSuccessJSON(map[string]interface{}{
		"his_info": his,
	})
}

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

}

func (c *CoordinateController) OpKeepAccounts() {
	//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")
	//
	//result, request_log := service.OpKeepAccounts()
	//fmt.Println(result)
	//fmt.Println(request_log)
}
func (c *CoordinateController) OpCancelKeepAccounts() {
	result, request_log := service.OpCancelKeepAccounts()
	fmt.Println(result)
	fmt.Println(request_log)
}

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")
)
