package controllers

import (
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/services/maycur"
	"hongze/hz_crm_api/utils"
	"time"
)

// MaycurController 每刻报销
type MaycurController struct {
	BaseAuthController
}

// MaycurOpenController 每刻报销-无鉴权
type MaycurOpenController struct {
	BaseCommonController
}

// SyncCompanyProfile
// @Title 主动触发-同步客户档案及权限
// @Description 同步客户档案及权限
// @Success 200 Ret=200 操作成功
// @router /company_profile/sync [post]
func (this *MaycurController) SyncCompanyProfile() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	// 每刻没提供debug环境，所以测试环境不同步
	if utils.RunMode != "release" {
		br.Msg = "测试环境暂不允许同步"
		return
	}
	// 加锁
	cacheKey := "maycur:company:sync"
	ok := utils.Rc.SetNX(cacheKey, 1, time.Second*600)
	if !ok {
		br.Msg = "请勿频繁同步, 请稍后再试"
		return
	}
	go func() {
		_ = maycur.SyncCompanyProfile()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// DailySyncCompanyProfile
// @Title 每日同步-同步客户档案及权限
// @Description 同步客户档案及权限
// @Success 200 Ret=200 操作成功
// @router /company_profile/daily_sync [post]
func (this *MaycurOpenController) DailySyncCompanyProfile() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	// 每刻没提供debug环境，所以测试环境不同步
	if utils.RunMode != "release" {
		br.Msg = "测试环境暂不允许同步"
		return
	}
	// 简单校验一下
	ip := this.Ctx.Input.IP()
	if ip != "127.0.0.1" {
		br.Msg = "未经授权, 不可操作"
		br.ErrMsg = "未经授权, 不可操作, IP: " + ip
		return
	}
	// 加锁
	cacheKey := "maycur:company:sync"
	ok := utils.Rc.SetNX(cacheKey, 1, time.Second*600)
	if !ok {
		br.Msg = "请勿频繁同步, 请稍后再试"
		return
	}
	go func() {
		_ = maycur.SyncCompanyProfile()
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
