package new_mobile_api_controllers

import (
	"Xcx_New/controllers/mobile_api_controllers"
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"Xcx_New/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"path"
	"regexp"
	"runtime"
	"strconv"
	"time"
)

type MobileRegistController struct {
	mobile_api_controllers.MobileBaseAPIController
}

// /mobile/regist [get]

// /mobile/regist/submit [post]
// @param mobile:string
// @param password:string
// @param code:string
func (this *MobileRegistController) RegistSubmit() {
	mobile := this.GetString("mobile")
	pwd := this.GetString("password")
	code := this.GetString("code")

	// 判断手机号是否存在
	if utils.CellPhoneRegexp().MatchString(mobile) == false {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileFormat)
		return
	}
	if len(pwd) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePasswordEmpty)
		return

	}
	if len(code) == 0 {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
		return
	}
	if service.IsMobileRegister(mobile) == true {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMobileRegistered)
		return
	}

	if code == "13535547901" {
		admin, err := service.RegisterSuperAdmin(mobile, pwd)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(err.Code)
			return
		} else {
			this.Ctx.SetCookie("mobile", mobile)
			this.SetSession("mobile_admin_user", admin)
			this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
				"result": true,
				"id":     admin.Id,
			})
			this.ServeJSON()
		}
	} else {

		redisClient := service.RedisClient()
		defer redisClient.Close()
		cache_code, _ := redisClient.Get("code_msg_" + mobile).Result()
		if cache_code != code {
			//this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)
			//this.ServeJSON()
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeVerificationCodeWrong)

			return
		}
		admin, err := service.RegisterSuperAdmin(mobile, pwd)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(err.Code)
			return
		} else {
			this.Ctx.SetCookie("mobile", mobile)
			this.SetSession("mobile_admin_user", admin)
			// 注册成功后验证码就要使其失效
			redisClient.Del("code_msg_" + mobile)

			this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
				"result": true,
				"id":     admin.Id,
			})
			this.ServeJSON()
		}

	}

}

// /mobile/org/create/submit [post]
// @param name:string
// @param province:string 省名
// @param city:string 市名
// @param district:string 区县
// @param address:string
// @param category:int
// @param contact_name:string
// @param org_phone?:string
// @param open_xt?:bool 是否开启血透系统
// @param open_cdm?:bool 是否开启慢病系统
// @param open_scrm?:bool 是否开启SCRM
// @param open_mall?:bool 是否开启Mall
func (this *MobileRegistController) CreateOrg() {
	adminUserObj := this.GetSession("mobile_admin_user")
	if adminUserObj == nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
		this.ServeJSON()
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)

	//if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil {
	//	this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
	//	this.ServeJSON()
	//	return
	//} else if didCreateOrg {
	//	this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRepeatCreateOrg)
	//	this.ServeJSON()
	//	return
	//}

	name := this.GetString("org_name")
	shortName := name
	provinceName := this.GetString("provinces_name")
	cityName := this.GetString("city_name")
	districtName := this.GetString("district_name")
	address := this.GetString("address")
	org_type := this.GetString("org_type")
	contactName := this.GetString("contact_name")

	//openXT, _ := this.GetBool("open_xt")
	//openCDM, _ := this.GetBool("open_cdm")
	//openSCRM, _ := this.GetBool("open_scrm")
	//openMall, _ := this.GetBool("open_mall")

	openXT := true
	openCDM := false
	openSCRM := false
	openMall := false

	if len(name) == 0 || len(shortName) == 0 || len(contactName) == 0 || len(address) == 0 || len(provinceName) <= 0 || len(cityName) <= 0 || len(districtName) <= 0 || len(org_type) <= 0 {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		this.ServeJSON()
		return
	}
	orgPhone := this.GetString("telephone")
	//
	//if len(orgPhone) > 0 {
	//	if utils.PhoneRegexp().MatchString(orgPhone) == false {
	//		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodePhone)
	//		this.ServeJSON()
	//		return
	//	}
	//}

	provinceID := 0
	cityID := 0
	districtID := 0

	province, getProvinceErr := service.GetProvinceWithName(provinceName)
	if getProvinceErr != nil {
		utils.ErrorLog("查询省名失败：%v", getProvinceErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else if province != nil {
		provinceID = int(province.ID)
		city, getCityErr := service.GetCityWithName(province.ID, cityName)
		if getCityErr != nil {
			utils.ErrorLog("查询城市名失败：%v", getCityErr)
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			this.ServeJSON()
			return
		} else if city != nil {
			cityID = int(city.ID)
			district, getDistrictErr := service.GetDistrictWithName(city.ID, districtName)
			if getDistrictErr != nil {
				utils.ErrorLog("查询区县名失败：%v", getDistrictErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else if district != nil {
				districtID = int(district.ID)
			}
		}
	}

	orgType := service.GetOrgTypeByName(org_type)

	org := &models.Org{
		Creator:      adminUser.Id,
		OrgName:      name,
		OrgShortName: shortName,
		Province:     int64(provinceID),
		City:         int64(cityID),
		District:     int64(districtID),
		Address:      address,
		OrgType:      orgType.ID,
		Telephone:    orgPhone,
		ContactName:  contactName,
		Claim:        1,
		Evaluate:     5,
		Status:       1,
		CreateTime:   time.Now().Unix(),
		ModifyTime:   time.Now().Unix(),
	}

	adminUsers, _ := service.GetAdminUserByUserID(adminUser.Id)

	createErr := service.CreateOrg(org, adminUsers.Name, openXT, openCDM, openSCRM, openMall) // 创建机构以及所有类型的 app，如果有新类型的平台，则需要在这个方法里面把创建这一新类型的 app 的代码加上

	if createErr != nil {
		utils.ErrorLog("mobile=%v的超级管理员创建机构失败：%v", adminUser.Mobile, createErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		this.ServeJSON()
	} else {

		//初始化病人和排班相关数据
		InitPatientAndSchedule(org)
		//初始化透析方案
		InitSystemPrescrption(org)
		//初始化角色和权限
		InitRoleAndPurviews(org)
		//初始化设备管理org
		InitEquitMentInformation(org)
		//初始化显示配置和打印模版
		InitShowConfig(org)
		//初始化商品类型
		InitGoodTypesConfig(org)

		//创建完机构后进行登录验证操作
		ip := utils.GetIP(this.Ctx.Request)
		ssoDomain := beego.AppConfig.String("sso_domain")
		api := ssoDomain + "/m/login/pwd"
		values := make(url.Values)
		values.Set("mobile", adminUser.Mobile)
		values.Set("password", adminUser.Password)
		values.Set("app_type", "3")
		values.Set("ip", ip)
		resp, requestErr := http.PostForm(api, values)

		if requestErr != nil {
			utils.ErrorLog("请求SSO登录接口失败: %v", requestErr)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		defer resp.Body.Close()
		body, ioErr := ioutil.ReadAll(resp.Body)
		if ioErr != nil {
			utils.ErrorLog("SSO登录接口返回数据读取失败: %v", ioErr)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}
		var respJSON map[string]interface{}
		utils.InfoLog(string(body))
		if err := json.Unmarshal([]byte(string(body)), &respJSON); err != nil {
			utils.ErrorLog("SSO登录接口返回数据解析JSON失败: %v", err)
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		}

		if respJSON["state"].(float64) != 1 {
			msg := respJSON["msg"].(string)
			utils.ErrorLog("SSO登录接口请求失败: %v", msg)
			if int(respJSON["code"].(float64)) == 609 {
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeAccountOrPasswordWrong)
				return
			}
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			return
		} else {
			utils.SuccessLog("SSO登录成功")
			// 下面这几段 Map=>JSON=>Struct 的流程可能会造成速度很慢
			userJSON := respJSON["data"].(map[string]interface{})["admin"].(map[string]interface{})
			userJSONBytes, _ := json.Marshal(userJSON)
			var adminUser models.AdminUser
			if err := json.Unmarshal(userJSONBytes, &adminUser); err != nil {
				utils.ErrorLog("解析管理员失败：%v", err)
				this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				return
			}

			var org models.Org
			if respJSON["data"].(map[string]interface{})["org"] != nil {
				orgJSON := respJSON["data"].(map[string]interface{})["org"].(map[string]interface{})
				orgJSONBytes, _ := json.Marshal(orgJSON)
				if err := json.Unmarshal(orgJSONBytes, &org); err != nil {
					utils.ErrorLog("解析机构失败：%v", err)
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
			}

			var app models.OrgApp

			if respJSON["data"].(map[string]interface{})["app"] != nil {
				appJSON := respJSON["data"].(map[string]interface{})["app"].(map[string]interface{})
				appJSONBytes, _ := json.Marshal(appJSON)
				if err := json.Unmarshal(appJSONBytes, &app); err != nil {
					utils.ErrorLog("解析应用失败：%v", err)
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
			}

			var appRole models.App_Role

			if respJSON["data"].(map[string]interface{})["app_role"] != nil {
				appRoleJSON := respJSON["data"].(map[string]interface{})["app_role"].(map[string]interface{})
				appRoleJSONBytes, _ := json.Marshal(appRoleJSON)
				if err := json.Unmarshal(appRoleJSONBytes, &appRole); err != nil {
					utils.ErrorLog("解析AppRole失败：%v", err)
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}
			}

			var subscibe models.ServeSubscibe
			if respJSON["data"].(map[string]interface{})["subscibe"] != nil {
				subscibeJSON := respJSON["data"].(map[string]interface{})["subscibe"].(map[string]interface{})
				subscibeJSONBytes, _ := json.Marshal(subscibeJSON)
				if err := json.Unmarshal(subscibeJSONBytes, &subscibe); err != nil {
					utils.ErrorLog("解析Subscibe失败：%v", err)
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
					return
				}

			}

			//service.GetOrgSubscibeState(&subscibe)
			templateInfo, _ := service.GetOrgInfoTemplate(org.Id)

			mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{
				AdminUser:    &adminUser,
				Org:          &org,
				App:          &app,
				AppRole:      &appRole,
				Subscibe:     &subscibe,
				TemplateInfo: &templateInfo,
			}
			//设置seesion
			this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)

			//设置cookie
			mobile := adminUser.Mobile + "-" + strconv.FormatInt(org.Id, 10) + "-" + strconv.FormatInt(appRole.Id, 10)
			token := utils.GenerateLoginToken(mobile)
			expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
			this.Ctx.SetCookie("token_cookie", token, expiration, "/")

			var configList interface{}
			var FiledList []*models.FiledConfig
			var dict_configList interface{}

			if org.Id > 0 {
				configList, _ = service.GetConfigList(org.Id)
				dict_configList, _ = service.GetDictConfigList(org.Id)

				FiledList, _ = service.FindFiledByOrgId(org.Id)
			}
			if len(FiledList) == 0 {
				var err error
				if org.Id > 0 {
					err = service.BatchInsertFiledConfig(org.Id)
					if err == nil {
						FiledList, _ = service.FindFiledByOrgId(org.Id)
					} else {
						utils.ErrorLog("字段批量插入失败：%v", err)
					}
				} else {
					FiledList = make([]*models.FiledConfig, 0)
				}
			}

			if org.Id > 0 {
				major, requestErr := service.GetInspectionMajor(org.Id)
				if len(major) == 0 {
					QualityeList, err := service.FindQualityByOrgId(org.Id)
					if len(QualityeList) == 0 {
						err = service.BatchInsertQualityControl(org.Id)
					} else {
						utils.ErrorLog("字段批量插入失败：%v", err)
					}

					InspectionList, err := service.FindeInspectionByOrgId(org.Id)
					if len(InspectionList) == 0 {
						err = service.BatchInspectionConfiguration(org.Id)
					} else {
						utils.ErrorLog("字段批量插入失败：%v", err)
					}
				} else {
					utils.ErrorLog("字段批量插入失败：%v", requestErr)
				}

			}

			this.ServeSuccessJSON(map[string]interface{}{
				"admin": adminUser,
				"user":  appRole,
				"org":   org,
				"template_info": map[string]interface{}{
					"id":          templateInfo.ID,
					"org_id":      templateInfo.OrgId,
					"template_id": templateInfo.TemplateId,
				},
				"config_list":      configList,
				"dict_config_list": dict_configList,

				"filed_list": FiledList,
			})
		}

	}

}

func InitAdviceTemplate(org *models.Org) {

	//初始化医嘱模版
	adviceInit := &models.AdviceInit{
		UserOrgId:  org.Id,
		CreateTime: time.Now().Unix(),
		UpdateTime: time.Now().Unix(),
		Status:     1,
		IsInit:     1,
	}

	adviceParentTemplate := LoadConfig("./advice_template.json").Parent_template
	for _, item := range adviceParentTemplate {
		parentTemplate := &models.DoctorAdviceParentTemplate{
			OrgId:       org.Id,
			Name:        item.Name,
			Status:      1,
			CreatedTime: time.Now().Unix(),
			UpdatedTime: time.Now().Unix(),
			AdviceType:  item.AdviceType,
		}

		createErr := service.CreateDoctorParentTemplate(parentTemplate)
		fmt.Println(parentTemplate.ID)
		if createErr == nil {
			for _, adviceTemplateItem := range item.DoctorAdviceTemplate {
				adviceTeplate := &models.DoctorAdviceTemplate{
					OrgId:                 org.Id,
					AdviceName:            adviceTemplateItem.AdviceName,
					AdviceDesc:            adviceTemplateItem.AdviceDesc,
					SingleDose:            adviceTemplateItem.SingleDose,
					SingleDoseUnit:        adviceTemplateItem.SingleDoseUnit,
					PrescribingNumber:     adviceTemplateItem.PrescribingNumber,
					PrescribingNumberUnit: adviceTemplateItem.PrescribingNumberUnit,
					DeliveryWay:           adviceTemplateItem.DeliveryWay,
					ExecutionFrequency:    adviceTemplateItem.ExecutionFrequency,
					AdviceDoctor:          adviceTemplateItem.AdviceDoctor,
					Status:                1,
					CreatedTime:           time.Now().Unix(),
					UpdatedTime:           time.Now().Unix(),
					TemplateId:            parentTemplate.ID,
					DrugSpec:              adviceTemplateItem.DrugSpec,
					DrugSpecUnit:          adviceTemplateItem.DrugSpecUnit,
					ParentId:              adviceTemplateItem.ParentId,
					AdviceType:            adviceTemplateItem.AdviceType,
					DayCount:              adviceTemplateItem.DayCount,
					WeekDays:              adviceTemplateItem.WeekDays,
					FrequencyType:         adviceTemplateItem.FrequencyType,
				}
				createErr := service.CreateDoctorTemplate(adviceTeplate)

				if createErr == nil {
					for _, childItem := range adviceTemplateItem.SubDoctorAdviceTemplate {
						adviceTeplate := &models.DoctorAdviceTemplate{
							OrgId:                 org.Id,
							AdviceName:            childItem.AdviceName,
							AdviceDesc:            childItem.AdviceDesc,
							SingleDose:            childItem.SingleDose,
							SingleDoseUnit:        childItem.SingleDoseUnit,
							PrescribingNumber:     childItem.PrescribingNumber,
							PrescribingNumberUnit: childItem.PrescribingNumberUnit,
							DeliveryWay:           childItem.DeliveryWay,
							ExecutionFrequency:    childItem.ExecutionFrequency,
							AdviceDoctor:          childItem.AdviceDoctor,
							Status:                1,
							CreatedTime:           time.Now().Unix(),
							UpdatedTime:           time.Now().Unix(),
							TemplateId:            parentTemplate.ID,
							DrugSpec:              childItem.DrugSpec,
							DrugSpecUnit:          childItem.DrugSpecUnit,
							ParentId:              adviceTeplate.ID,
							AdviceType:            childItem.AdviceType,
							DayCount:              childItem.DayCount,
							WeekDays:              childItem.WeekDays,
							FrequencyType:         childItem.FrequencyType,
						}
						service.CreateDoctorTemplate(adviceTeplate)
					}
				}
			}
		}
	}
	service.CreateAdviceInitConfig(adviceInit)

}

func InitSystemPrescrption(org *models.Org) {
	//初始化透析方案
	prescriptions := LoadPrescriptionConfig("./system_dialysis_prescription.json").Prescription
	for _, item := range prescriptions {
		item.UserOrgId = org.Id
		item.CreatedTime = time.Now().Unix()
		item.UpdatedTime = time.Now().Unix()
		service.CreateVMPrescription(item)
	}

}

func InitPatientAndSchedule(org *models.Org) {
	var ids []int64
	//数据初始化

	//创建两个虚拟病人
	patients := LoadPatientConfig("./patient.json").Patients
	for _, item := range patients {
		item.UserOrgId = org.Id
		item.CreatedTime = time.Now().Unix()
		item.UpdatedTime = time.Now().Unix()
		item.Status = 1

		service.CreateVMOrgPatient(item)
		ids = append(ids, item.ID)
	}

	//创建两个血透的虚拟病人到新表
	fmt.Print("patients", patients)
	for _, it := range patients {
		patientsNew := models.XtPatientsNew{
			UserOrgId:               org.Id,
			CreatedTime:             time.Now().Unix(),
			UpdatedTime:             time.Now().Unix(),
			Status:                  1,
			BloodId:                 it.ID,
			BloodPatients:           1,
			Name:                    it.Name,
			Avatar:                  it.Avatar,
			PatientType:             it.PatientType,
			Source:                  it.Source,
			Lapseto:                 it.Lapseto,
			Gender:                  it.Gender,
			Nation:                  it.Nation,
			NativePlace:             it.NativePlace,
			MaritalStatus:           it.MaritalStatus,
			IdCardNo:                it.IdCardNo,
			Birthday:                it.Birthday,
			ReimbursementWayId:      it.ReimbursementWayId,
			HealthCareNo:            it.HealthCareNo,
			Phone:                   it.Phone,
			HomeAddress:             it.HomeAddress,
			WorkUnit:                it.WorkUnit,
			UnitAddress:             it.UnitAddress,
			Children:                it.Children,
			IsHospitalFirstDialysis: it.IsHospitalFirstDialysis,
			FirstDialysisDate:       it.FirstDialysisDate,
			BindingState:            it.BindingState,
			PatientComplains:        it.PatientComplains,
			PresentHistory:          it.PresentHistory,
			PastHistory:             it.PastHistory,
			Temperature:             it.Temperature,
			Pulse:                   it.Pulse,
			Respiratory:             it.Respiratory,
			Age:                     it.Age,
			IsOpenRemind:            it.IsOpenRemind,
			TellPhone:               it.TellPhone,
			FirstTreatmentDate:      it.FirstTreatmentDate,
			ContactName:             it.ContactName,
			IsInfectious:            it.IsInfectious,
		}

		service.CreateVMOrgNewPatient(&patientsNew)
	}
	//创建1个分组
	vmGroup := &models.VMDeviceGroup{
		OrgId:  org.Id,
		Name:   "护理一组",
		Status: 1,
		Ctime:  time.Now().Unix(),
		Mtime:  time.Now().Unix(),
	}

	service.CreateVMGroup(vmGroup)

	//创建两个虚拟分区
	vmZone1 := &models.VMDeviceZone{
		OrgId:  org.Id,
		Name:   "A区",
		Type:   1,
		Status: 1,
		Ctime:  time.Now().Unix(),
		Mtime:  time.Now().Unix(),
	}
	service.CreateVMZone(vmZone1)

	vmZone2 := &models.VMDeviceZone{
		OrgId:  org.Id,
		Name:   "B区",
		Type:   2,
		Status: 1,
		Ctime:  time.Now().Unix(),
		Mtime:  time.Now().Unix(),
	}
	service.CreateVMZone(vmZone2)

	//创建2个虚拟床位
	vmDeviceNumber1 := &models.VMDeviceNumber{
		OrgId:   org.Id,
		Number:  "1号床",
		GroupId: vmGroup.ID,
		ZoneId:  vmZone1.ID,
		Status:  1,
		Ctime:   time.Now().Unix(),
		Mtime:   time.Now().Unix(),
	}
	service.CreateVMDeviceNumber(vmDeviceNumber1)

	vmDeviceNumber2 := &models.VMDeviceNumber{
		OrgId:   org.Id,
		Number:  "2号床",
		GroupId: vmGroup.ID,
		ZoneId:  vmZone2.ID,
		Status:  1,
		Ctime:   time.Now().Unix(),
		Mtime:   time.Now().Unix(),
	}
	service.CreateVMDeviceNumber(vmDeviceNumber2)

	var dates []int64

	mondayDate := GetDateOfWeek(1)
	tuesdayDate := GetDateOfWeek(2)
	wednesdayDate := GetDateOfWeek(3)
	thursdayDate := GetDateOfWeek(4)
	fridayDate := GetDateOfWeek(5)
	saturdayDate := GetDateOfWeek(6)
	sundayDate := GetDateOfWeek(7)

	dates = append(dates, mondayDate)
	dates = append(dates, tuesdayDate)
	dates = append(dates, wednesdayDate)
	dates = append(dates, thursdayDate)
	dates = append(dates, fridayDate)
	dates = append(dates, saturdayDate)
	dates = append(dates, sundayDate)

	//创建两个虚拟病人本周的排班
	//stime, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
	for week_type, date := range dates {
		for index, id := range ids {
			if index == 0 {
				sch := &models.VMSchedule{
					UserOrgId:    org.Id,
					PartitionId:  vmZone1.ID,
					BedId:        vmDeviceNumber1.ID,
					PatientId:    id,
					ScheduleDate: date,
					ScheduleType: 1,
					ScheduleWeek: int64(week_type + 1),
					ModeId:       1,
					Status:       1,
					CreatedTime:  time.Now().Unix(),
					UpdatedTime:  time.Now().Unix(),
				}
				service.CreateVMSch(sch)
			}

			if index == 1 {

				sch := &models.VMSchedule{
					UserOrgId:    org.Id,
					PartitionId:  vmZone2.ID,
					BedId:        vmDeviceNumber2.ID,
					PatientId:    id,
					ScheduleDate: date,
					ScheduleType: 2,
					ScheduleWeek: int64(week_type + 1),
					ModeId:       1,
					Status:       1,
					CreatedTime:  time.Now().Unix(),
					UpdatedTime:  time.Now().Unix(),
				}
				service.CreateVMSch(sch)
			}
		}

	}

	//创建单周模版
	//1.创建模版模式
	mode := &models.VMPatientScheduleTemplateMode{
		OrgId:        org.Id,
		Mode:         1,
		ExecuteTimes: 0,
		Status:       1,
		Ctime:        time.Now().Unix(),
		Mtime:        time.Now().Unix(),
	}
	service.CreateVMSchMode(mode)
	//2.创建模版id
	templaeIdOne := &models.VMPatientScheduleTemplateId{
		OrgId:  org.Id,
		Status: 1,
		Ctime:  time.Now().Unix(),
		Mtime:  time.Now().Unix(),
	}
	service.CreateVMSchTemplateId(templaeIdOne)
	templaeIdTwo := &models.VMPatientScheduleTemplateId{
		OrgId:  org.Id,
		Status: 1,
		Ctime:  time.Now().Unix(),
		Mtime:  time.Now().Unix(),
	}
	service.CreateVMSchTemplateId(templaeIdTwo)
	//3.创建单周排班模版
	items := LoadSchTemplateConfig("./schedule_template.json").Item
	for _, item := range items {
		if item.TimeType == 1 {
			item.OrgId = org.Id
			item.TemplateId = templaeIdOne.ID
			item.DeviceNumberId = vmDeviceNumber1.ID
			item.PatientId = ids[0]
			item.Status = 1
			item.Ctime = time.Now().Unix()
			item.Mtime = time.Now().Unix()

		} else if item.TimeType == 2 {
			item.OrgId = org.Id
			item.TemplateId = templaeIdOne.ID
			item.DeviceNumberId = vmDeviceNumber2.ID
			item.PatientId = ids[1]
			item.Status = 1
			item.Ctime = time.Now().Unix()
			item.Mtime = time.Now().Unix()

		}

		service.CreateVMSchTemplate(item)
	}

}

func InitRoleAndPurviews(org *models.Org) {
	roles := LoadRoleConfig("./role.json").Roles
	app, _ := service.GetOrgApp(org.Id, 3)
	for _, item := range roles {
		role := &models.Role{
			RoleName:     item.RoleName,
			RoleIntro:    item.RoleIntroduction,
			Creator:      0,
			OrgId:        org.Id,
			AppId:        app.Id,
			IsSuperAdmin: false,
			Status:       1,
			CreateTime:   time.Now().Unix(),
			ModifyTime:   time.Now().Unix(),
			Number:       item.Number,
			IsSystem:     item.IsSystem,
		}
		err := service.CreateOrgRole(role)
		if err == nil {
			purview := &models.RolePurview{
				RoleId:     role.Id,
				OrgId:      org.Id,
				AppId:      role.AppId,
				PurviewIds: item.PurviewIds,
				Status:     1,
				CreateTime: time.Now().Unix(),
				ModifyTime: time.Now().Unix(),
			}
			func_purview := &models.SgjUserRoleFuncPurview{
				RoleId:     role.Id,
				OrgId:      org.Id,
				AppId:      role.AppId,
				PurviewIds: item.FuncIds,
				Status:     1,
				Ctime:      time.Now().Unix(),
				Mtime:      time.Now().Unix(),
			}

			service.CreateRolePurview(purview)
			service.CreateFuncRolePurview(func_purview)
		}
	}
}

func (this *MobileRegistController) ModifyName() {
	name := this.GetString("name")
	adminUserObj := this.GetSession("mobile_admin_user")
	adminUser := adminUserObj.(*models.AdminUser)
	err := service.ModifyAdminUserName(name, adminUser.Id)
	if err != nil {
		utils.ErrorLog("修改管理员名字失败：%v", err)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		this.ServeJSON()
	} else {
		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{})
		this.ServeJSON()
	}
}

func (this *MobileRegistController) Login() {
	mobile := this.Ctx.GetCookie("mobile")
	adminUser, err := service.GetValidAdminUserByMobileReturnErr(mobile)
	if err != nil {
		utils.ErrorLog("获取管理信息失败：%v", err)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		this.ServeJSON()
	} else {

		mobileAdminUserInfo := &mobile_api_controllers.MobileAdminUserInfo{
			AdminUser:    adminUser,
			Org:          nil,
			App:          nil,
			AppRole:      nil,
			Subscibe:     nil,
			TemplateInfo: nil,
		}

		var org models.Org
		var user models.App_Role
		//设置seesion
		this.SetSession("mobile_admin_user_info", mobileAdminUserInfo)
		//设置cookie
		mobile = mobile + "-" + "0" + "-" + "0"
		token := utils.GenerateLoginToken(mobile)
		expiration, _ := beego.AppConfig.Int64("mobile_token_expiration_second")
		this.Ctx.SetCookie("token_cookie", token, expiration, "/")
		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
			"admin": adminUser,
			"user":  user,
			"org":   org,
			"template_info": map[string]interface{}{
				"id":          0,
				"org_id":      0,
				"template_id": 0,
			},
			"config_list":      nil,
			"dict_config_list": nil,
			"filed_list":       nil,
		})
		this.ServeJSON()
	}

}

type RoleConfig struct {
	Roles []*models.VMUserRoleAndPurview "json:roles"
}

type PatientConfig struct {
	Patients []*models.VMOrgPatients "json:patients"
}

type SchTemplateConfig struct {
	Item []*models.VMPatientScheduleTemplateItem "json:item"
}

type PrescriptionConfig struct {
	Prescription []*models.SystemPrescription "json:prescription"
}

func LoadRoleConfig(dataFile string) *RoleConfig {
	var config RoleConfig
	_, filename, _, _ := runtime.Caller(1)
	datapath := path.Join(path.Dir(filename), dataFile)
	config_file, err := os.Open(datapath)
	if err != nil {
		emit("Failed to open config file '%s': %s\n", datapath, err)
		return &config
	}

	fi, _ := config_file.Stat()

	buffer := make([]byte, fi.Size())
	_, err = config_file.Read(buffer)

	buffer, err = StripComments(buffer) //去掉注释
	if err != nil {
		emit("Failed to strip comments from json: %s\n", err)
		return &config
	}

	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
	err = json.Unmarshal(buffer, &config)         //解析json格式数据
	if err != nil {
		emit("Failed unmarshalling json: %s\n", err)
		return &config
	}
	return &config
}

func LoadPatientConfig(dataFile string) *PatientConfig {
	var config PatientConfig
	_, filename, _, _ := runtime.Caller(1)
	datapath := path.Join(path.Dir(filename), dataFile)
	config_file, err := os.Open(datapath)
	if err != nil {
		emit("Failed to open config file '%s': %s\n", datapath, err)
		return &config
	}

	fi, _ := config_file.Stat()

	buffer := make([]byte, fi.Size())
	_, err = config_file.Read(buffer)

	buffer, err = StripComments(buffer) //去掉注释
	if err != nil {
		emit("Failed to strip comments from json: %s\n", err)
		return &config
	}

	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
	err = json.Unmarshal(buffer, &config)         //解析json格式数据
	if err != nil {
		emit("Failed unmarshalling json: %s\n", err)
		return &config
	}
	return &config
}

func LoadSchTemplateConfig(dataFile string) *SchTemplateConfig {
	var config SchTemplateConfig
	_, filename, _, _ := runtime.Caller(1)
	datapath := path.Join(path.Dir(filename), dataFile)
	config_file, err := os.Open(datapath)
	if err != nil {
		emit("Failed to open config file '%s': %s\n", datapath, err)
		return &config
	}

	fi, _ := config_file.Stat()

	buffer := make([]byte, fi.Size())
	_, err = config_file.Read(buffer)

	buffer, err = StripComments(buffer) //去掉注释
	if err != nil {
		emit("Failed to strip comments from json: %s\n", err)
		return &config
	}

	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
	err = json.Unmarshal(buffer, &config)         //解析json格式数据
	if err != nil {
		emit("Failed unmarshalling json: %s\n", err)
		return &config
	}
	return &config
}

func LoadPrescriptionConfig(dataFile string) *PrescriptionConfig {
	var config PrescriptionConfig
	_, filename, _, _ := runtime.Caller(1)
	datapath := path.Join(path.Dir(filename), dataFile)
	config_file, err := os.Open(datapath)
	if err != nil {
		emit("Failed to open config file '%s': %s\n", datapath, err)
		return &config
	}

	fi, _ := config_file.Stat()

	buffer := make([]byte, fi.Size())
	_, err = config_file.Read(buffer)

	buffer, err = StripComments(buffer) //去掉注释
	if err != nil {
		emit("Failed to strip comments from json: %s\n", err)
		return &config
	}

	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
	err = json.Unmarshal(buffer, &config)         //解析json格式数据
	if err != nil {
		emit("Failed unmarshalling json: %s\n", err)
		return &config
	}
	return &config
}

func emit(msgfmt string, args ...interface{}) {
	log.Printf(msgfmt, args...)
}

func StripComments(data []byte) ([]byte, error) {
	data = bytes.Replace(data, []byte("\r"), []byte(""), 0) // Windows
	lines := bytes.Split(data, []byte("\n"))                //split to muli lines
	filtered := make([][]byte, 0)

	for _, line := range lines {
		match, err := regexp.Match(`^\s*#`, line)
		if err != nil {
			return nil, err
		}
		if !match {
			filtered = append(filtered, line)
		}
	}

	return bytes.Join(filtered, []byte("\n")), nil
}

func GetDateOfWeek(week_type int) (weekMonday int64) {
	thisTime := time.Now()
	weekDay := int(thisTime.Weekday())
	if weekDay == 0 {
		weekDay = 7
	}
	weekEnd := 7 - weekDay
	weekStart := weekEnd - 6
	weekTitle := make([]string, 0)
	days := make([]string, 0)
	for index := weekStart; index <= weekEnd; index++ {
		theDay := thisTime.AddDate(0, 0, index)
		indexYear, indexMonthTime, indexDay := theDay.Date()
		indexMonth := int(indexMonthTime)
		indexWeek := strconv.Itoa(indexYear) + "." + strconv.Itoa(indexMonth) + "." + strconv.Itoa(indexDay)
		weekTitle = append(weekTitle, indexWeek)
		days = append(days, theDay.Format("2006-01-02"))
	}
	var targetDayStr string
	switch week_type {
	case 1:
		targetDayStr = days[0]
		break
	case 2:
		targetDayStr = days[1]

		break
	case 3:
		targetDayStr = days[2]

		break
	case 4:
		targetDayStr = days[3]

		break
	case 5:
		targetDayStr = days[4]

		break
	case 6:
		targetDayStr = days[5]

		break
	case 7:
		targetDayStr = days[6]

		break
	}
	targetDay, _ := utils.ParseTimeStringToTime("2006-01-02", targetDayStr)
	return targetDay.Unix()
}

type Config struct {
	Parent_template []*models.VMDoctorAdviceParentTemplate "json:parent_template"
}

func LoadConfig(dataFile string) *Config {
	var config Config
	_, filename, _, _ := runtime.Caller(1)
	datapath := path.Join(path.Dir(filename), dataFile)
	config_file, err := os.Open(datapath)
	if err != nil {
		emit("Failed to open config file '%s': %s\n", datapath, err)
		return &config
	}

	fi, _ := config_file.Stat()

	buffer := make([]byte, fi.Size())
	_, err = config_file.Read(buffer)

	buffer, err = StripComments(buffer) //去掉注释
	if err != nil {
		emit("Failed to strip comments from json: %s\n", err)
		return &config
	}

	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
	err = json.Unmarshal(buffer, &config)         //解析json格式数据
	if err != nil {
		emit("Failed unmarshalling json: %s\n", err)
		return &config
	}
	return &config
}

func InitEquitMentInformation(org *models.Org) {
	//添加设备型号
	mode := models.VMDeviceMode{
		DeviceMode: "5008S",
		Status:     1,
		UserOrgId:  org.Id,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
	}
	service.CreatedDeviceMode(&mode)

	deviceMode := models.VMDeviceMode{
		DeviceMode: "4008S",
		Status:     1,
		UserOrgId:  org.Id,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
	}
	service.CreatedDeviceMode(&deviceMode)

	firstDeviceMode, _ := service.GetFirstDeviceMode(org.Id)
	//获取机构下对应的第一数据
	number, _ := service.GetFirstBedNumber(org.Id)
	//添加设备
	deviceAddmacher := models.VmDeviceAddmacher{
		SerialNumber:  "8VSAHE13",
		DeviceType:    1,
		BedId:         number.ID,
		DeviceName:    "费森尤斯",
		UnitType:      firstDeviceMode.ID,
		MachineStatus: 1,
		Status:        1,
		UserOrgId:     org.Id,
		Ctime:         time.Now().Unix(),
	}
	service.CreateDeviceAddMacher(&deviceAddmacher)
	macher, _ := service.GetLastMacher(org.Id)
	fmt.Print(macher.ID)
	treatmentmode := models.VmDeviceTreatmentmode{
		MachineId:  macher.ID,
		Status:     1,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		UserOrgId:  org.Id,
		TreateMode: 1,
	}
	service.CreatedTreateMode(&treatmentmode)
	treatmentmodeone := models.VmDeviceTreatmentmode{
		MachineId:  macher.ID,
		Status:     1,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		UserOrgId:  org.Id,
		TreateMode: 2,
	}
	service.CreatedTreateMode(&treatmentmodeone)
	treatmentmodetwo := models.VmDeviceTreatmentmode{
		MachineId:  macher.ID,
		Status:     1,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		UserOrgId:  org.Id,
		TreateMode: 3,
	}
	service.CreatedTreateMode(&treatmentmodetwo)

	treatmentmodethree := models.VmDeviceTreatmentmode{
		MachineId:  macher.ID,
		Status:     1,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		UserOrgId:  org.Id,
		TreateMode: 4,
	}
	service.CreatedTreateMode(&treatmentmodethree)
	treatmentmodefour := models.VmDeviceTreatmentmode{
		MachineId:  macher.ID,
		Status:     1,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		UserOrgId:  org.Id,
		TreateMode: 5,
	}
	service.CreatedTreateMode(&treatmentmodefour)
	treatmentmodefive := models.VmDeviceTreatmentmode{
		MachineId:  macher.ID,
		Status:     1,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		UserOrgId:  org.Id,
		TreateMode: 12,
	}
	service.CreatedTreateMode(&treatmentmodefive)
}

func InitShowConfig(org *models.Org) {
	service.BatchInsertFiledSystemConfig(org.Id)
	template := &models.VMGobalTemplate{
		Status:     1,
		Ctime:      time.Now().Unix(),
		Mtime:      time.Now().Unix(),
		OrgId:      org.Id,
		TemplateId: 2,
	}
	service.CreateVMPrintTemplate(template)
}

type GoodTypesConfig struct {
	Types []*models.VMGoodsType "json:types"
}

func LoadGoodTypeConfig(dataFile string) *GoodTypesConfig {
	var config GoodTypesConfig
	_, filename, _, _ := runtime.Caller(1)
	datapath := path.Join(path.Dir(filename), dataFile)
	config_file, err := os.Open(datapath)
	fmt.Println("1111111")
	fmt.Println(err)
	fmt.Println("2222222")

	if err != nil {
		emit("Failed to open config file '%s': %s\n", datapath, err)
		return &config
	}

	fi, _ := config_file.Stat()

	buffer := make([]byte, fi.Size())
	_, err = config_file.Read(buffer)

	buffer, err = StripComments(buffer) //去掉注释
	fmt.Println("333333")
	fmt.Println(err)
	fmt.Println("4444444")
	if err != nil {
		emit("Failed to strip comments from json: %s\n", err)
		return &config
	}

	buffer = []byte(os.ExpandEnv(string(buffer))) //特殊
	err = json.Unmarshal(buffer, &config)         //解析json格式数据
	fmt.Println("55555555")
	fmt.Println(err)
	fmt.Println("66666666")
	if err != nil {
		emit("Failed unmarshalling json: %s\n", err)
		return &config
	}
	return &config
}

func InitGoodTypesConfig(org *models.Org) {
	good_types := LoadGoodTypeConfig("./good_types.json").Types
	fmt.Println(good_types)
	for _, item := range good_types {
		good_type := &models.GoodsType{
			TypeCode: item.TypeCode,
			TypeName: item.TypeName,
			Remark:   "",
			Number:   item.Number,
			Ctime:    time.Now().Unix(),
			Mtime:    time.Now().Unix(),
			OrgId:    org.Id,
			Status:   1,
			Type:     1,
			OutStock: item.OutStock,
		}
		service.AddSigleGoodType(good_type)
	}

}
