package service

import (
	"SSO/models"
	"time"

	"github.com/jinzhu/gorm"
)

func CreateOrg(org *models.Org, mobile string) error {
	now := time.Now()
	tx_admin := writeUserDb.Begin()
	if err := tx_admin.Create(org).Error; err != nil {
		tx_admin.Rollback()
		return err
	}
	role := models.Role{
		RoleName:     "超级管理员",
		RoleIntro:    "",
		Creator:      org.Creator,
		OrgId:        org.Id,
		AppId:        0,
		IsSuperAdmin: true,
		Status:       1,
		CreateTime:   now.Unix(),
		ModifyTime:   now.Unix(),
	}
	if err := tx_admin.Create(&role).Error; err != nil {
		tx_admin.Rollback()
		return err
	}

	if err := createOrgApp(tx_admin, &role, mobile, 1); err != nil {
		tx_admin.Rollback()
		return err
	}
	if err := createOrgApp(tx_admin, &role, mobile, 3); err != nil {
		tx_admin.Rollback()
		return err
	}
	if err := createOrgApp(tx_admin, &role, mobile, 4); err != nil {
		tx_admin.Rollback()
		return err
	}
	if err := createOrgApp(tx_admin, &role, mobile, 5); err != nil {
		tx_admin.Rollback()
		return err
	}

	nextMonthDate := now.AddDate(0, 0, 30)
	subscibe := models.ServeSubscibe{
		OrgId:       int64(org.Id),
		PeriodStart: now.Unix(),
		PeriodEnd:   nextMonthDate.Unix(),
		Status:      1,
		CreatedTime: now.Unix(),
		UpdatedTime: now.Unix(),
		State:       9,
	}
	if err := tx_admin.Create(&subscibe).Error; err != nil {
		tx_admin.Rollback()
		return err
	}

	tx_patient := writeDb.Begin()
	if err := tx_patient.Exec("INSERT INTO sgj_patient_articles_menu (name, status, type, user_org_id, ctime, mtime) VALUES(?, ?, ?, ?, ?, ?);", "科普教育", 1, 1, org.Id, now.Unix(), now.Unix()).Error; err != nil {
		tx_patient.Rollback()
		tx_admin.Rollback()
		return err
	}
	if err := tx_patient.Exec("INSERT INTO sgj_patient_good_category (user_org_id, category_name, status, created_time, updated_time) VALUES(?, ?, ?, ?, ?);", org.Id, "普通商品", 1, now.Unix(), now.Unix()).Error; err != nil {
		tx_patient.Rollback()
		tx_admin.Rollback()
		return err
	}

	if err := tx_admin.Exec("INSERT INTO sgj_user_membership_card (user_org_id, card_name, card_level, upgrade_integral, card_right, use_notice, background_type, background, service_phone, status, created_time, updated_time) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", org.Id, "普通会员", 0, 0, "", "", 1, "#CACA41", "", 1, now.Unix(), now.Unix()).Error; err != nil {
		tx_admin.Rollback()
		tx_patient.Rollback()
		return err
	}

	tx_admin.Commit()
	tx_patient.Commit()
	return nil
}

func GetOrgWithAdminUserID(adminUserID int) (*models.Org, error) {
	var org models.Org
	err := readUserDb.Where("creator = ? AND status <> 0", adminUserID).First(&org).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	if err != nil {
		return nil, err
	} else {
		return &org, nil
	}
}

func GetOrgApps(adminUserID int, orgID int) ([]*models.OrgApp, error) {
	var apps []*models.OrgApp
	err := readUserDb.Model(&models.OrgApp{}).Where("creator = ? AND org_id = ? AND status = 1", adminUserID, orgID).Find(&apps).Error
	if err == gorm.ErrRecordNotFound {
		err = nil
	}
	if err != nil {
		return nil, err
	} else {
		return apps, nil
	}
}

func DidOrgDidCreateAppWithType(orgID int, appType int) (bool, error) {
	var count int
	err := readUserDb.Model(&models.OrgApp{}).Where("org_id = ? AND app_type = ? AND status = 1", orgID, appType).Count(&count).Error
	if err != nil {
		return false, err
	} else {
		return count == 1, nil
	}
}

func CreateOrgApp(adminUserID int, orgID int, appType int) error {
	var user models.AdminUser
	err := readUserDb.Where("id = ? AND status = 1", adminUserID).Find(&user).Error
	if err != nil {
		return err
	}

	now := time.Now().Unix()
	tx := writeUserDb.Begin()
	app := models.OrgApp{
		Creator:    adminUserID,
		OrgId:      orgID,
		AppType:    appType,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
	}
	if createAppErr := tx.Create(&app).Error; createAppErr != nil {
		tx.Rollback()
		return createAppErr
	}
	var role models.Role
	getRoleErr := readUserDb.Where("creator = ? AND org_id = ? AND is_super_admin = 1", adminUserID, orgID).First(&role).Error
	if getRoleErr != nil {
		tx.Rollback()
		return getRoleErr
	}
	app_role := models.App_Role{
		AdminUserId: adminUserID,
		OrgId:       orgID,
		AppId:       app.Id,
		RoleId:      role.Id,
		Avatar:      "",
		UserName:    user.Mobile,
		Intro:       "",
		UserType:    1,
		UserTitle:   1,
		Status:      1,
		CreateTime:  now,
		ModifyTime:  now,
	}
	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
		tx.Rollback()
		return createApp_RoleErr
	}
	return tx.Commit().Error
}

//  如果出错，没有 rollback，需自行 rollback
func createOrgApp(tx *gorm.DB, superAdminRole *models.Role, userName string, appType int) error {
	now := time.Now().Unix()
	app := models.OrgApp{
		Creator:    superAdminRole.Creator,
		OrgId:      superAdminRole.OrgId,
		AppType:    appType,
		Status:     1,
		CreateTime: now,
		ModifyTime: now,
	}
	if createAppErr := tx.Create(&app).Error; createAppErr != nil {
		return createAppErr
	}
	app_role := models.App_Role{
		AdminUserId: superAdminRole.Creator,
		OrgId:       superAdminRole.OrgId,
		AppId:       app.Id,
		RoleId:      superAdminRole.Id,
		Avatar:      "",
		UserName:    userName,
		Intro:       "",
		UserType:    1,
		UserTitle:   1,
		Status:      1,
		CreateTime:  now,
		ModifyTime:  now,
	}
	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
		return createApp_RoleErr
	}
	return nil
}

func GetIllness() ([]*models.Illness, error) {
	var illness []*models.Illness
	err := readUserDb.Model(&models.Illness{}).Where("status = 1").Find(&illness).Error
	if err != nil {
		return nil, err
	} else {
		return illness, nil
	}
}

func GetOrgCategoriesByPid(pid int64) ([]*models.OrgType, error) {
	var cats []*models.OrgType
	err := readUserDb.Model(&models.OrgType{}).Where("pid = ? AND status = 1", pid).Order("sort_no asc").Find(&cats).Error
	if err != nil {
		return nil, err
	} else {
		return cats, nil
	}
}

func GetOrgServeSubscibe(orgID int) (*models.ServeSubscibe, error) {
	var model models.ServeSubscibe
	err := readUserDb.Model(&models.ServeSubscibe{}).Where("org_id = ? AND status = 1", orgID).First(&model).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &model, nil
}

func CreateOrgServeSubscibe(subscibe *models.ServeSubscibe) error {
	err := writeUserDb.Create(subscibe).Error
	return err
}
