package controller

import (
	"fmt"
	"strconv"
	"time"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	authService "be.ems/src/modules/auth/service"
	"be.ems/src/modules/system/model"
	"be.ems/src/modules/system/service"

	"github.com/gin-gonic/gin"
)

// 实例化控制层 SysLogLoginController 结构体
var NewSysLogLogin = &SysLogLoginController{
	sysLogLoginService: service.NewSysLogLogin,
	accountService:     authService.NewAccount,
}

// 系统登录日志信息
//
// PATH /system/log/login
type SysLogLoginController struct {
	sysLogLoginService *service.SysLogLogin // 系统登录日志服务
	accountService     *authService.Account // 账号身份操作服务
}

// 系统登录日志列表
//
// GET /list
//
//	@Tags			system/log/login
//	@Accept			json
//	@Produce		json
//	@Param			userName	query		string	false	"userName"
//	@Param			pageNum		query		number	true	"pageNum"	default(1)
//	@Param			pageSize	query		number	true	"pageSize"	default(10)
//	@Success		200			{object}	object	"Response Results"
//	@Security		TokenAuth
//	@Summary		System Login Log List
//	@Description	System Login Log List
//	@Router			/system/log/login/list [get]
func (s *SysLogLoginController) List(c *gin.Context) {
	query := reqctx.QueryMap(c)
	// 分页检查
	pageNum := parse.Number(query["pageNum"])
	pageSize := parse.Number(query["pageSize"])
	if pageNum == 0 || pageSize == 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: pageNum or pageSize not is empty"))
		return
	}
	dataScopeSQL := reqctx.LoginUserToDataScopeSQL(c, "sys_user", "sys_user")
	rows, total := s.sysLogLoginService.FindByPage(query, dataScopeSQL)

	// 闭包函数处理多语言
	language := reqctx.AcceptLanguage(c)
	converI18n := func(language string, arr *[]model.SysLogLogin) {
		for i := range *arr {
			(*arr)[i].LoginLocation = i18n.TKey(language, (*arr)[i].LoginLocation)
			(*arr)[i].OS = i18n.TKey(language, (*arr)[i].OS)
			(*arr)[i].Browser = i18n.TKey(language, (*arr)[i].Browser)
			(*arr)[i].Msg = i18n.TKey(language, (*arr)[i].Msg)
		}
	}
	converI18n(language, &rows)

	c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}

// Clean 系统登录日志清空
//
// DELETE /clean
func (s SysLogLoginController) Clean(c *gin.Context) {
	rows := s.sysLogLoginService.Clean()
	c.JSON(200, resp.OkData(rows))
}

// Unlock 系统登录日志账户解锁
//
// PUT /unlock/:userName
func (s SysLogLoginController) Unlock(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	userName := c.Param("userName")
	if userName == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: userName is empty"))
		return
	}
	ok := s.accountService.CleanLoginRecordCache(userName)
	if ok {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.errUnlock")))
}

// Export 导出系统登录日志信息
//
// GET /export
func (s SysLogLoginController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	query := reqctx.QueryMap(c)
	// 分页检查
	pageNum := parse.Number(query["pageNum"])
	pageSize := parse.Number(query["pageSize"])
	if pageNum == 0 || pageSize == 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: pageNum or pageSize not is empty"))
		return
	}
	dataScopeSQL := reqctx.LoginUserToDataScopeSQL(c, "sys_user", "sys_user")
	rows, total := s.sysLogLoginService.FindByPage(query, dataScopeSQL)
	if total == 0 {
		// c.JSON(200, resp.CodeMsg(40016, "export data record as empty"))
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}

	// 闭包函数处理多语言
	converI18n := func(language string, arr *[]model.SysLogLogin) {
		for i := range *arr {
			(*arr)[i].LoginLocation = i18n.TKey(language, (*arr)[i].LoginLocation)
			(*arr)[i].OS = i18n.TKey(language, (*arr)[i].OS)
			(*arr)[i].Browser = i18n.TKey(language, (*arr)[i].Browser)
			(*arr)[i].Msg = i18n.TKey(language, (*arr)[i].Msg)
		}
	}
	converI18n(language, &rows)

	// 导出文件名称
	fileName := fmt.Sprintf("sys_log_login_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": i18n.TKey(language, "log.login.export.id"),
		"B1": i18n.TKey(language, "log.login.export.userName"),
		"C1": i18n.TKey(language, "log.login.export.ip"),
		"D1": i18n.TKey(language, "log.login.export.location"),
		"E1": i18n.TKey(language, "log.login.export.os"),
		"F1": i18n.TKey(language, "log.login.export.browser"),
		"G1": i18n.TKey(language, "log.login.export.status"),
		"H1": i18n.TKey(language, "log.login.export.time"),
		"I1": i18n.TKey(language, "log.login.export.msg"),
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 状态
		statusValue := i18n.TKey(language, "dictData.fail")
		if row.StatusFlag == "1" {
			statusValue = i18n.TKey(language, "dictData.success")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.ID,
			"B" + idx: row.UserName,
			"C" + idx: row.LoginIp,
			"D" + idx: row.LoginLocation,
			"E" + idx: row.OS,
			"F" + idx: row.Browser,
			"G" + idx: statusValue,
			"H" + idx: date.ParseDateToStr(row.LoginTime, date.YYYY_MM_DDTHH_MM_SSZ),
			"I" + idx: row.Msg,
		})
	}

	// 导出数据表格
	saveFilePath, err := file.WriteSheet(headerCells, dataCells, fileName, "")
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}

	c.FileAttachment(saveFilePath, fileName)
}
