package controllers

import (
	"SSO/enums"
	"SSO/models"
	"SSO/service"
	"SSO/utils"
	"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
// @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 org_phone?:string
// @param business_week?:string
// @param business_time?:string
// @param business_state?:int
// @param org_pics?:string (url1@@url2@@url3)
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 := 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")
	if len(name) == 0 || len(shortName) == 0 || len(address) == 0 || province <= 0 || city <= 0 || district <= 0 || category <= 0 {
		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.PhoneRegexp().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,
		BusinessWeek:    businessWeek,
		BusinessTime:    businessTime,
		Gallery:         orgPics,
		Claim:           1,
		Evaluate:        5,
		Status:          2,
		CreateTime:      time.Now().Unix(),
		ModifyTime:      time.Now().Unix(),
	}
	createErr := service.CreateOrg(&org, adminUser.Mobile) // 创建机构以及所有类型的 app，如果有新类型的平台，则需要在这个方法里面把创建这一新类型的 app 的代码加上
	if createErr != nil {
		utils.ErrorLog("mobile=%v的超级管理员创建机构失败：%v", adminUser.Mobile, createErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDBCreate)
		this.ServeJSON()
	} else {
		redirectURL := beego.AppConfig.String("submodule_domain_dialysis_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 {
			apps, 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)
					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)
					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)
					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)
					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         //"/static/images/userData.png"
			this.Data["user_name"] = org.OrgShortName //adminUser.Mobile

			if adminUser.IsSuperAdmin {
				this.Data["scrm_role_exist"] = true
				this.Data["xt_role_exist"] = true
				this.Data["cdm_role_exist"] = true
				this.Data["mall_role_exist"] = true
			} else {
				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 {
						this.Data["scrm_role_exist"] = true
					}
					if app.AppType == 3 {
						this.Data["xt_role_exist"] = true
					}
					if app.AppType == 4 {
						this.Data["cdm_role_exist"] = true
					}
					if app.AppType == 5 {
						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")
		}
	}
}

// /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); 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")
}
