package service

import (
	"Xcx_New/models"
	"fmt"
	"github.com/jinzhu/gorm"
	"strconv"
	"time"
)

func GetOrgTypes() (ots []*models.OrgType, err error) {
	err = readUserDb.Model(&models.OrgType{}).Where("status=1").Order("sort_no").Find(&ots).Error
	return
}

func UpdateOrgInfo(org *models.Org) (err error) {
	err = writeUserDb.Model(&models.Org{}).Where("id=?", org.Id).Update(org).Error
	return
}

func GetIllnessList() (ills []*models.Illness, err error) {
	err = readUserDb.Where("status=1").Find(&ills).Error
	return
}

func CreateOrgGalleryItem(item *models.OrgGallery) (err error) {
	err = writeUserDb.Create(item).Error
	return
}

func DeleteOrgGalleryItem(id int64) (err error) {
	err = writeUserDb.Model(&models.OrgGallery{}).Where("id=?", id).Update(map[string]interface{}{"Status": 0, "Mtime": time.Now().Unix()}).Error
	return
}

func CreateOrg(org *models.Org, name string, openXT bool, openCDM bool, openSCRM bool, openMall bool) 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
	}

	// app 的创建顺序也决定了登录后前往 app 的优先级
	if err := createOrgApp(tx_admin, &role, name, 3, openXT); 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 := writeSgjPatientDb.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 createOrgApp(tx *gorm.DB, superAdminRole *models.Role, userName string, appType int, open bool) error {

	//创建应用
	now := time.Now().Unix()
	var app_id int64
	apps, _ := FindSystemOrgApp()
	for _, item := range apps {
		app := &VMOrgApp{
			AppType:    item.AppType,
			Creator:    int(superAdminRole.Creator),
			OrgId:      int(superAdminRole.OrgId),
			OpenStatus: item.OpenStatus,
			Status:     1,
			CreateTime: now,
			ModifyTime: now,
			Name:       item.Name,
			Url:        item.Url,
			Number:     item.Number,
			Pid:        0,
		}
		writeUserDb.Create(&app)
		if app.AppType == 3 {
			app_id = app.ID

		}
		fmt.Println(item.VMOrgApp)

		for _, subItem := range item.VMOrgApp {
			app := &VMOrgApp{
				AppType:    subItem.AppType,
				Creator:    int(superAdminRole.Creator),
				OrgId:      int(superAdminRole.OrgId),
				OpenStatus: subItem.OpenStatus,
				Status:     1,
				CreateTime: now,
				ModifyTime: now,
				Name:       subItem.Name,
				Url:        subItem.Url,
				Number:     subItem.Number,
				Pid:        app.ID,
			}
			writeUserDb.Create(&app)
		}
	}

	//string := strconv.FormatInt(int64,10        /)
	app_role := models.App_Role{
		AdminUserId: superAdminRole.Creator,
		OrgId:       superAdminRole.OrgId,
		AppId:       app_id,
		RoleId:      superAdminRole.Id,
		RoleIds:     strconv.FormatInt(superAdminRole.Id, 10),
		Avatar:      "",
		UserName:    userName,
		Intro:       "",
		UserType:    1,
		UserTitle:   0,
		Status:      1,
		CreateTime:  now,
		ModifyTime:  now,
	}
	if createApp_RoleErr := tx.Create(&app_role).Error; createApp_RoleErr != nil {
		return createApp_RoleErr
	}
	return nil
}

func GetOrgTypeByName(org_type_name string) (org_type models.OrgType) {
	readUserDb.Model(&models.OrgType{}).Where("status = 1 AND name = ?", org_type_name).First(&org_type)
	return
}

type VMOrgApp struct {
	ID         int64       `gorm:"PRIMARY_KEY;AUTO_INCREMENT" json:"id"` // ID
	AppType    int         `gorm:"column:app_type" json:"app_type"`
	Creator    int         `json:"creator"` // 创建者，即管理员用户的 id
	OrgId      int         `gorm:"column:org_id" json:"org_id"`
	OpenStatus int         `gorm:"column:open_status" json:"open_status"`
	Status     int8        `json:"status"`                    // 状态 0.无效 1.有效 2.禁用
	CreateTime int64       `gorm:"column:ctime" json:"ctime"` // 创建时间
	ModifyTime int64       `gorm:"column:mtime" json:"mtime"` // 修改时间
	Name       string      `gorm:"column:name" json:"name" form:"name"`
	Url        string      `gorm:"column:url" json:"url" form:"url"`
	Pid        int64       `gorm:"column:pid" json:"pid" form:"pid"`
	Number     int64       `gorm:"column:number" json:"order" form:"number"`
	VMOrgApp   []*VMOrgApp `gorm:"ForeignKey:Pid;AssociationForeignKey:Id" `
}

func (VMOrgApp) TableName() string {
	return "sgj_user_org_app"
}

func FindSystemOrgApp() (app []*VMOrgApp, err error) {
	err = readUserDb.Model(&VMOrgApp{}).Preload("VMOrgApp", "org_id = 0 AND status =1 AND pid > 0").Where("status = 1 AND org_id = 0 AND pid = 0").Find(&app).Error
	return
}

func GetAllOrgByAdminUserId() {

}
