package mobile_api_controllers

import (
	"Xcx_New/enums"
	"Xcx_New/models"
	"Xcx_New/service"
	"encoding/json"
	"fmt"
	"time"

	"github.com/astaxie/beego"
)

type AdminUserApiController struct {
	MobileBaseAPIAuthController
}

func (c *AdminUserApiController) GetAdminUserElectronicSignature() {

	adminUserInfo := c.GetMobileAdminUserInfo()
	//orgId, _ := service.GetCreatByOrgId(adminUserInfo.Org.Id)
	id := adminUserInfo.AdminUser.Id
	es, _ := service.GetAdminUserElectronicSignatureTwo(id)
	if es != nil {
		c.ServeSuccessJSON(map[string]interface{}{
			"state":                1,
			"electronic_signature": es,
		})
	} else {
		c.ServeSuccessJSON(map[string]interface{}{
			"state": 0,
		})
	}
	return
}

func (c *AdminUserApiController) SaveAdminUserElectronicSignature() {

	adminUserInfo := c.GetMobileAdminUserInfo()

	es, _ := service.GetAdminUserElectronicSignature(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id)

	action := "update"
	timeNow := time.Now().Unix()
	if es == nil {
		es = new(models.AdminUserElectronicSignature)
		es.Status = 1
		es.OrgId = adminUserInfo.Org.Id
		es.AppId = adminUserInfo.App.Id
		es.Ctime = timeNow
		es.Creator = adminUserInfo.AdminUser.Id
		action = "create"
	}
	es.Mtime = timeNow

	var esdata models.AdminUserElectronicSignature
	var err error
	if err = json.Unmarshal(c.Ctx.Input.RequestBody, &esdata); err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	es.Hash = esdata.Hash
	es.Url = beego.AppConfig.String("qiniu_domain") + esdata.Hash

	if action == "create" {
		err = service.CreateAdminUserElectronicSignature(es)
	} else {
		err = service.SaveAdminUserElectronicSignature(es)
	}
	if err != nil {
		fmt.Println(err)
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
		return
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"electronic_signature": es,
	})
}

func (c *AdminUserApiController) GetMyInfo() {
	adminUserInfo := c.GetMobileAdminUserInfo()

	roleInfo := adminUserInfo.AppRole

	es, _ := service.GetAdminUserElectronicSignature(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id)

	c.ServeSuccessJSON(map[string]interface{}{
		"electronic_signature": es,
		"roleInfo":             roleInfo,
	})
	return
}
