package controllers

import (
	"SSO/enums"
	"SSO/models"
	"SSO/service"
	"SSO/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path"
	"regexp"
	"runtime"
	"strconv"
	"time"

	"github.com/astaxie/beego"
)

type OrgController struct {
	BaseController
}

// /org/create [get]
func (this *OrgController) Create() {
	adminUserObj := this.GetSession("admin_user")
	if adminUserObj == nil {
		this.Redirect302(beego.URLFor("LoginController.PwdLogin"))
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)
	if !adminUser.IsSuperAdmin {
		utils.ErrorLog("用户%v不是超级管理员，没有权限创建机构，应跳转到错误页", adminUser.Mobile)
		this.Redirect302(beego.URLFor("OrgController.CreateAppHint"))
		return
	}
	if didCreateOrg, checkCreateOrgErr := service.DidAdminUserCreateOrg(adminUser.Id); checkCreateOrgErr != nil {
		utils.ErrorLog("检查id = %v的用户是否创建了机构时出错：%v", adminUser.Id, checkCreateOrgErr)
		// this.Redirect302(beego.URLFor("LoginController.PwdLogin"))
		this.Abort("404")
		return
	} else {
		if didCreateOrg {
			// if didCreateApp, checkCreateAppErr := service.DidAdminUserOrgCreateApp(adminUser.Id); checkCreateAppErr != nil {
			// 	utils.ErrorLog("检查id = %v的用户是否创建了应用时出错：%v", adminUser.Id, checkCreateAppErr)
			// 	this.Redirect302(beego.URLFor("LoginController.Login"))
			// 	return
			// } else {
			// 	if didCreateApp {
			// 		// 前往该去的地方 LoginController.getRedirectURL()
			// 	}
			// }
			utils.ErrorLog("id = %v 的用户已创建机构，接下来应当前往应用页或者前往错误页", adminUser.Id)
			this.Redirect302(beego.URLFor("LoginController.CreateApp"))
			return
		}
	}

	cats, getCatErr := service.GetOrgCategoriesByPid(0)
	if getCatErr != nil {
		utils.ErrorLog("获取机构类型失败：%v", getCatErr)
		this.Abort("404")
		return
	}
	this.Data["categories"] = cats
	this.Data["avatar"] = "/static/images/userData.png"
	this.Data["user_name"] = adminUser.Mobile
	this.Data["province"] = service.GetAllProvince()
	this.Data["illness"], _ = service.GetIllness()

	this.SetTpl("new_main/create_org.html")
}

// /org/create/submit [post]
// @param name:string
// @param short_name:string 已和 name 同步，不需要传了
// @param intro?:string
// @param logo?:string
// @param province:int
// @param city:int
// @param district:int
// @param address:string
// @param ill?:string ("病种1,病种2")
// @param category:int
// @param contact_name:string
// @param org_phone?:string
// @param business_week?:string
// @param business_time?:string
// @param business_state?:int
// @param org_pics?:string (url1@@url2@@url3)
// @param open_xt?:bool 是否开启血透系统
// @param open_cdm?:bool 是否开启慢病系统
// @param open_scrm?:bool 是否开启SCRM
// @param open_mall?:bool 是否开启Mall
func (this *OrgController) CreateSubmit() {
	adminUserObj := this.GetSession("admin_user")
	if adminUserObj == nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
		this.ServeJSON()
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)
	if !adminUser.IsSuperAdmin {
		utils.ErrorLog("用户%v不是超级管理员，没有权限创建机构", adminUser.Mobile)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
		this.ServeJSON()
		return
	}
	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("name")
	shortName := name // this.GetString("short_name")
	intro := this.GetString("intro")
	logo := this.GetString("logo")
	province, _ := this.GetInt("province", 0)
	city, _ := this.GetInt("city", 0)
	district, _ := this.GetInt("district", 0)
	address := this.GetString("address")
	ill := this.GetString("ill")
	category, _ := this.GetInt64("category")
	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")
	user_name := this.GetString("user_name")
	if len(name) == 0 || len(shortName) == 0 || len(contactName) == 0 || len(address) == 0 || province <= 0 || city <= 0 || district <= 0 || category <= 0 || (!openXT && !openCDM && !openSCRM && !openMall) {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		this.ServeJSON()
		return
	}
	orgPhone := this.GetString("org_phone")
	businessWeek := this.GetString("business_week")
	businessTime := this.GetString("business_time")
	businessState, _ := this.GetInt64("business_state")
	orgPics := this.GetString("org_pics")

	if len(orgPhone) > 0 {
		if utils.CellPhoneRegexp().MatchString(orgPhone) == false {
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			this.ServeJSON()
			return
		}
	}

	if businessState != 0 && businessState != 1 {
		businessState = 0
	}

	org := models.Org{
		Creator:         adminUser.Id,
		OrgName:         name,
		OrgShortName:    shortName,
		OrgIntroduction: intro,
		OrgLogo:         logo,
		Province:        province,
		City:            city,
		District:        district,
		Address:         address,
		Illness:         ill,
		OrgType:         category,
		OperatingState:  businessState,
		Telephone:       orgPhone,
		ContactName:     contactName,
		BusinessWeek:    businessWeek,
		BusinessTime:    businessTime,
		Gallery:         orgPics,
		Claim:           1,
		Evaluate:        5,
		Status:          1,
		CreateTime:      time.Now().Unix(),
		ModifyTime:      time.Now().Unix(),
	}

	fmt.Print("user_name ------------------------------------------------------------------", user_name)

	createErr := service.CreateOrg(&org, user_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)
		//初始化医嘱模版
		//InitAdviceTemplate(org)
		//初始化角色和权限
		InitRoleAndPurviews(&org)
		//初始化设备管理org
		InitEquitMentInformation(&org)
		//初始化显示配置和打印模版
		InitShowConfig(&org)

		redirectURL := beego.AppConfig.String("submodule_domain_dialysis_manage")
		//} else if openCDM {
		//	redirectURL = beego.AppConfig.String("submodule_domain_cdm_manage")
		//} else if openSCRM {
		//	redirectURL = beego.AppConfig.String("submodule_domain_patient_manage")
		//} else if openMall {
		//	redirectURL = beego.AppConfig.String("submodule_domain_mall_manage")
		//}

		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
			"url": redirectURL,
		})
		this.ServeJSON()
	}
}

// /org/app/create [get] 19.06.04 之前的管理应用逻辑，已弃用
func (this *OrgController) CreateApp() {
	// this.Abort("404")
	// return

	adminUserObj := this.GetSession("admin_user")
	if adminUserObj == nil {
		this.Redirect302(beego.URLFor("LoginController.PwdLogin"))
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)
	if !adminUser.IsSuperAdmin {
		utils.ErrorLog("用户%v不是超级管理员，没有权限创建应用，应跳转到错误页", adminUser.Mobile)
		this.Redirect302(beego.URLFor("OrgController.CreateAppHint"))
		return
	}
	org, getOrgErr := service.GetOrgWithAdminUserID(adminUser.Id)
	if getOrgErr != nil {
		utils.ErrorLog("获取id = %v的用户创建的机构时出错：%v", adminUser.Id, getOrgErr)
		// this.Redirect302(beego.URLFor("LoginController.PwdLogin"))
		this.Abort("404")
		return
	} else {
		if org == nil {
			this.Redirect302(beego.URLFor("OrgController.Create"))
			return
		} else {
			_, getAppsErr := service.GetOrgApps(adminUser.Id, org.Id)
			if getAppsErr != nil {
				utils.ErrorLog("获取id = %v的用户创建的机构下已创建的应用时出错：%v", adminUser.Id, getOrgErr)
				// this.Redirect302(beego.URLFor("LoginController.PwdLogin"))
				this.Abort("404")
				return
			} else {

				this.Data["avatar"] = org.OrgLogo         //"/static/images/userData.png"
				this.Data["user_name"] = org.OrgShortName //adminUser.Mobile
				// 已创建的应用的信息
				//did_patient_manage_create := false
				//did_dialysis_manage_create := false
				//did_cdm_manage_create := false
				//did_mall_manage_create := false
				//for _, app := range apps {
				//	if app.AppType == 1 {
				//		did_patient_manage_create = true
				//	} else if app.AppType == 3 {
				//		did_dialysis_manage_create = true
				//	} else if app.AppType == 4 {
				//		did_cdm_manage_create = true
				//	} else if app.AppType == 5 {
				//		did_mall_manage_create = true
				//	}
				//}

				//// 自动创建所有应用
				//if did_patient_manage_create == false {
				//	err := service.CreateOrgApp(adminUser.Id, org.Id, 1, true)
				//	if err != nil {
				//		utils.ErrorLog("自动创建酷医聚客应用失败:%v", err)
				//		this.Abort("404")
				//		return
				//	}
				//}
				//if did_dialysis_manage_create == false {
				//	err := service.CreateOrgApp(adminUser.Id, org.Id, 3, true)
				//	if err != nil {
				//		utils.ErrorLog("自动创建透析管理应用失败:%v", err)
				//		this.Abort("404")
				//		return
				//	}
				//}
				//if did_cdm_manage_create == false {
				//	err := service.CreateOrgApp(adminUser.Id, org.Id, 4, true)
				//	if err != nil {
				//		utils.ErrorLog("自动创建慢病管理应用失败:%v", err)
				//		this.Abort("404")
				//		return
				//	}
				//}
				//if did_mall_manage_create == false {
				//	err := service.CreateOrgApp(adminUser.Id, org.Id, 5, true)
				//	if err != nil {
				//		utils.ErrorLog("自动创建微商城应用失败:%v", err)
				//		this.Abort("404")
				//		return
				//	}
				//}

				this.Data["submodule_domain_patient_manage"] = beego.AppConfig.String("submodule_domain_patient_manage")
				this.Data["submodule_domain_dialysis_manage"] = beego.AppConfig.String("submodule_domain_dialysis_manage")
				this.Data["submodule_domain_cdm_manage"] = beego.AppConfig.String("submodule_domain_cdm_manage")
				this.Data["submodule_domain_mall_manage"] = beego.AppConfig.String("submodule_domain_mall_manage")
				this.SetTpl("new_main/manage_app.html")
			}
		}
	}
}

// /org/admin/apps [get]
// @param org:int
//func (this *OrgController) ViewApps() {
//	adminUserObj := this.GetSession("admin_user")
//	if adminUserObj == nil {
//		this.Redirect302(beego.URLFor("LoginController.PwdLogin"))
//		return
//	}
//	adminUser := adminUserObj.(*models.AdminUser)
//	orgID, _ := this.GetInt("org")
//	if orgID <= 0 {
//		this.Abort("404")
//		return
//	}
//	org, getOrgErr := service.GetOrgById(orgID)
//	if getOrgErr != nil {
//		utils.ErrorLog("获取id = %v的用户创建的机构时出错：%v", adminUser.Id, getOrgErr)
//		this.Abort("404")
//		return
//	} else {
//		if org == nil {
//			if adminUser.IsSuperAdmin == true {
//				this.Redirect302(beego.URLFor("OrgController.Create"))
//			} else {
//				this.Abort("404")
//			}
//			return
//		} else {
//			this.Data["avatar"] = org.OrgLogo
//			this.Data["user_name"] = org.OrgShortName
//			this.Data["is_super_admin"] = adminUser.IsSuperAdmin
//			this.Data["org_id"] = org.Id
//
//			apps, getAppsErr := service.GetAdminUserAllOrgApp(adminUser.Id, org.Id)
//			if getAppsErr != nil {
//				utils.ErrorLog("获取 id = %v，org_id = %v 的用户有权限的应用时出错：%v", adminUser.Id, org.Id, getOrgErr)
//				this.Abort("404")
//				return
//			}
//			this.Data["scrm_role_exist"] = false
//			this.Data["xt_role_exist"] = false
//			this.Data["cdm_role_exist"] = false
//			this.Data["mall_role_exist"] = false
//			for _, app := range apps {
//				if app.AppType == 1 && app.OpenStatus == 1 {
//					this.Data["scrm_role_exist"] = true
//				}
//				if app.AppType == 3 && app.OpenStatus == 1 {
//					this.Data["xt_role_exist"] = true
//				}
//				if app.AppType == 4 && app.OpenStatus == 1 {
//					this.Data["cdm_role_exist"] = true
//				}
//				if app.AppType == 5 && app.OpenStatus == 1 {
//					this.Data["mall_role_exist"] = true
//				}
//			}
//
//			this.Data["submodule_domain_patient_manage"] = beego.AppConfig.String("submodule_domain_patient_manage")
//			this.Data["submodule_domain_dialysis_manage"] = beego.AppConfig.String("submodule_domain_dialysis_manage")
//			this.Data["submodule_domain_cdm_manage"] = beego.AppConfig.String("submodule_domain_cdm_manage")
//			this.Data["submodule_domain_mall_manage"] = beego.AppConfig.String("submodule_domain_mall_manage")
//			this.SetTpl("new_main/manage_app.html")
//		}
//	}
//}

// /app/open [post]
// @param type:int
func (this *OrgController) OpenAppSubmit() {
	adminUserObj := this.GetSession("admin_user")
	if adminUserObj == nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
		this.ServeJSON()
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)
	if !adminUser.IsSuperAdmin {
		utils.ErrorLog("用户%v不是超级管理员，没有权限启用应用", adminUser.Mobile)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
		this.ServeJSON()
		return
	}

	appType, _ := this.GetInt("type")
	if url := service.GetAppURLWithAppType(appType); len(url) == 0 {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		this.ServeJSON()
		return
	}

	org, getOrgErr := service.GetOrgWithAdminUserID(adminUser.Id)
	if getOrgErr != nil {
		utils.ErrorLog("获取id = %v的用户创建的机构时出错：%v", adminUser.Id, getOrgErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else {
		if org == nil {
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeMissingOrg)
			this.ServeJSON()
			return
		} else {
			app, getAppErr := service.GetOrgAppWithType(adminUser.Id, org.Id, appType)
			if getAppErr != nil {
				utils.ErrorLog("获取 id=%v 的用户的类型为%v的应用时失败：%v", adminUser.Id, appType)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			}
			if app == nil {
				createAppErr := service.CreateOrgApp(adminUser.Id, org.Id, appType, true)
				if createAppErr != nil {
					utils.ErrorLog("id=%v的超级管理员创建类型为%v的应用时失败：%v", adminUser.Id, appType, createAppErr)
					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
					this.ServeJSON()
				} else {
					this.Data["json"] = enums.MakeSuccessResponseJSON(nil)
					this.ServeJSON()
				}
			} else {
				if app.OpenStatus != 1 {
					app.OpenStatus = 1
					app.ModifyTime = time.Now().Unix()
					updateErr := service.SaveOrgApp(app)
					if updateErr != nil {
						utils.ErrorLog("id=%v的超级管理员开启类型为%v的应用时失败：%v", adminUser.Id, appType, updateErr)
						this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
						this.ServeJSON()
						return
					}
				}
				this.Data["json"] = enums.MakeSuccessResponseJSON(nil)
				this.ServeJSON()
			}
		}
	}
}

// /org/app/create/submit [post] 已废弃
// @param app_type:int
func (this *OrgController) CreateAppSubmit() {
	adminUserObj := this.GetSession("admin_user")
	if adminUserObj == nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeLoginTimeout)
		this.ServeJSON()
		return
	}
	adminUser := adminUserObj.(*models.AdminUser)
	if !adminUser.IsSuperAdmin {
		utils.ErrorLog("用户%v不是超级管理员，没有权限创建机构", adminUser.Mobile)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodePermissionDenied)
		this.ServeJSON()
		return
	}
	appType, _ := this.GetInt("app_type", 0)
	// if appType != 1 && appType != 3 && appType != 5 {
	// 	this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	// 	this.ServeJSON()
	// 	return
	// }
	if url := service.GetAppURLWithAppType(appType); len(url) == 0 {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		this.ServeJSON()
		return
	}
	org, getOrgErr := service.GetOrgWithAdminUserID(adminUser.Id)
	if getOrgErr != nil {
		utils.ErrorLog("获取id = %v的用户创建的机构时出错：%v", adminUser.Id, getOrgErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else {
		if org == nil {
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeMissingOrg)
			this.ServeJSON()
			return
		} else {
			if didCreate, checkErr := service.DidOrgDidCreateAppWithType(org.Id, appType); checkErr != nil {
				utils.ErrorLog("检查id = %v的用户是否创建了类型为%v的应用时出错：%v", adminUser.Id, appType, checkErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else {
				if didCreate {
					this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeRepeatCreateApp)
					this.ServeJSON()
					return
				}
			}

			// 创建应用
			if createErr := service.CreateOrgApp(adminUser.Id, org.Id, appType, false); createErr != nil {
				utils.ErrorLog("id=%v的超级管理员创建类型为%v的应用时失败：%v", adminUser.Id, appType, createErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
				this.ServeJSON()
			} else {
				this.Data["json"] = enums.MakeSuccessResponseJSON(nil)
				this.ServeJSON()
			}
		}
	}
}

type OrgCategoryController struct {
	BaseController
}

// /get_org_cat [get]
// @param pid?:int
func (this *OrgCategoryController) GetOrgCategories() {
	pid, _ := this.GetInt64("pid")
	if pid < 0 {
		pid = 0
	}
	cats, getCatErr := service.GetOrgCategoriesByPid(pid)
	if getCatErr != nil {
		utils.ErrorLog("获取机构类型失败：%v", getCatErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else {
		this.Data["json"] = enums.MakeSuccessResponseJSON(map[string]interface{}{
			"list": cats,
		})
		this.ServeJSON()
		return
	}
}

// /create_app_hint [get]
func (this *OrgController) CreateAppHint() {
	this.SetTpl("error/create_app_hint.html")
}

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

	service.CreateVMGroup(vmGroup)

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

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

	//创建2个虚拟床位
	vmDeviceNumber1 := &models.VMDeviceNumber{
		OrgId:   int64(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:   int64(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:    int64(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:    int64(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:        int64(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:  int64(org.Id),
		Status: 1,
		Ctime:  time.Now().Unix(),
		Mtime:  time.Now().Unix(),
	}
	service.CreateVMSchTemplateId(templaeIdOne)
	templaeIdTwo := &models.VMPatientScheduleTemplateId{
		OrgId:  int64(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 = int64(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 = int64(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:     int64(role.Id),
				OrgId:      int64(org.Id),
				AppId:      int64(role.AppId),
				PurviewIds: item.FuncIds,
				Status:     1,
				Ctime:      time.Now().Unix(),
				Mtime:      time.Now().Unix(),
			}

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

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()
}

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

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

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

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

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