package controller

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/utils/date"
	"be.ems/src/framework/utils/file"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/framework/vo/result"
	commonService "be.ems/src/modules/common/service"
	"be.ems/src/modules/system/model"
	"be.ems/src/modules/system/service"

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

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

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

// 系统登录日志列表
//
// GET /list
func (s *SysLogLoginController) List(c *gin.Context) {
	querys := ctx.QueryMap(c)
	data := s.sysLogLoginService.SelectSysLogLoginPage(querys)

	rows := data["rows"].([]model.SysLogLogin)
	// 闭包函数处理多语言
	language := ctx.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, result.Ok(data))
}

// 系统登录日志删除
//
// DELETE /:infoIds
func (s *SysLogLoginController) Remove(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	infoIds := c.Param("infoIds")
	if infoIds == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 处理字符转id数组后去重
	ids := strings.Split(infoIds, ",")
	uniqueIDs := parse.RemoveDuplicates(ids)
	if len(uniqueIDs) <= 0 {
		c.JSON(200, result.Err(nil))
		return
	}
	rows := s.sysLogLoginService.DeleteSysLogLoginByIds(uniqueIDs)
	if rows > 0 {
		msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
		c.JSON(200, result.OkMsg(msg))
		return
	}
	c.JSON(200, result.Err(nil))
}

// 系统登录日志清空
//
// DELETE /clean
func (s *SysLogLoginController) Clean(c *gin.Context) {
	err := s.sysLogLoginService.CleanSysLogLogin()
	if err != nil {
		c.JSON(200, result.ErrMsg(err.Error()))
		return
	}
	c.JSON(200, result.Ok(nil))
}

// 系统登录日志账户解锁
//
// PUT /unlock/:userName
func (s *SysLogLoginController) Unlock(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	userName := c.Param("userName")
	if userName == "" {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}
	ok := s.accountService.ClearLoginRecordCache(userName)
	if ok {
		c.JSON(200, result.Ok(nil))
		return
	}
	c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.errUnlock")))
}

// 导出系统登录日志信息
//
// POST /export
func (s *SysLogLoginController) Export(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	querys := ctx.BodyJSONMap(c)
	data := s.sysLogLoginService.SelectSysLogLoginPage(querys)
	if data["total"].(int64) == 0 {
		// 导出数据记录为空
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.exportEmpty")))
		return
	}
	rows := data["rows"].([]model.SysLogLogin)

	// 闭包函数处理多语言
	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.status"),
		"D1": i18n.TKey(language, "log.login.export.ip"),
		"E1": i18n.TKey(language, "log.login.export.location"),
		"F1": i18n.TKey(language, "log.login.export.browser"),
		"G1": i18n.TKey(language, "log.login.export.os"),
		"H1": i18n.TKey(language, "log.login.export.msg"),
		"I1": i18n.TKey(language, "log.login.export.time"),
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		// 状态
		statusValue := i18n.TKey(language, "dictData.fail")
		if row.Status == "1" {
			statusValue = i18n.TKey(language, "dictData.success")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.LoginID,
			"B" + idx: row.UserName,
			"C" + idx: statusValue,
			"D" + idx: row.IPAddr,
			"E" + idx: row.LoginLocation,
			"F" + idx: row.Browser,
			"G" + idx: row.OS,
			"H" + idx: row.Msg,
			"I" + idx: date.ParseDateToStr(row.LoginTime, date.YYYY_MM_DD_HH_MM_SS),
		})
	}

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

	c.FileAttachment(saveFilePath, fileName)
}
