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"
	"be.ems/src/modules/system/model"
	"be.ems/src/modules/system/service"

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

// 实例化控制层 SysPostController 结构体
var NewSysPost = &SysPostController{
	sysPostService: service.NewSysPost,
}

// 岗位信息
//
// PATH /system/post
type SysPostController struct {
	sysPostService *service.SysPost // 岗位服务
}

// 岗位列表
//
// GET /list
//
//	@Tags			system/post
//	@Accept			json
//	@Produce		json
//	@Param			postName	query		string	false	"postName"
//	@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		Post Information List
//	@Description	Post Information List
//	@Router			/system/post/list [get]
func (s *SysPostController) List(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	query := reqctx.QueryMap(c)
	// 多语言值转key查询
	if v, ok := query["postName"]; ok && v != "" {
		query["postName"] = i18n.TFindKeyPrefix(language, "post", v)
	}

	rows, total := s.sysPostService.FindByPage(query)

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

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

// Info 岗位信息
//
// GET /:postId
func (s *SysPostController) Info(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	postId := parse.Number(c.Param("postId"))
	if postId <= 0 {
		c.JSON(400, resp.CodeMsg(40010, "bind err: postId is empty"))
		return
	}
	data := s.sysPostService.FindById(postId)
	if data.PostId == postId {
		// 处理多语言
		data.PostName = i18n.TKey(language, data.PostName)
		data.Remark = i18n.TKey(language, data.Remark)
		c.JSON(200, resp.OkData(data))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// Add 岗位新增
//
// POST /
func (s *SysPostController) Add(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.SysPost
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.PostId > 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: postId not is empty"))
		return
	}

	// 检查名称唯一
	uniqueuName := s.sysPostService.CheckUniqueByName(body.PostName, 0)
	if !uniqueuName {
		// msg := fmt.Sprintf("岗位新增【%s】失败，岗位名称已存在", body.PostName)
		msg := i18n.TTemplate(language, "post.errNameExists", map[string]any{"name": body.PostName})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	// 检查编码属性值唯一
	uniqueCode := s.sysPostService.CheckUniqueByCode(body.PostCode, 0)
	if !uniqueCode {
		// msg := fmt.Sprintf("岗位新增【%s】失败，岗位编码已存在", body.PostCode)
		msg := i18n.TTemplate(language, "post.errCodeExists", map[string]any{"name": body.PostCode})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	body.CreateBy = reqctx.LoginUserToUserName(c)
	insertId := s.sysPostService.Insert(body)
	if insertId > 0 {
		c.JSON(200, resp.OkData(insertId))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// 岗位修改
//
// PUT /
func (s *SysPostController) Edit(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body model.SysPost
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	if body.PostId <= 0 {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: postId is empty"))
		return
	}

	// 检查是否存在
	postInfo := s.sysPostService.FindById(body.PostId)
	if postInfo.PostId != body.PostId {
		// c.JSON(200, resp.ErrMsg("没有权限访问岗位数据！"))
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "post.noData")))
		return
	}

	// 检查名称唯一
	uniquePostName := s.sysPostService.CheckUniqueByName(body.PostName, body.PostId)
	if !uniquePostName {
		// msg := fmt.Sprintf("岗位修改【%s】失败，岗位名称已存在", body.PostName)
		msg := i18n.TTemplate(language, "post.errNameExists", map[string]any{"name": body.PostName})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	// 检查编码属性值唯一
	uniquePostCode := s.sysPostService.CheckUniqueByCode(body.PostCode, body.PostId)
	if !uniquePostCode {
		// msg := fmt.Sprintf("岗位修改【%s】失败，岗位编码已存在", body.PostCode)
		msg := i18n.TTemplate(language, "post.errCodeExists", map[string]any{"name": body.PostCode})
		c.JSON(200, resp.ErrMsg(msg))
		return
	}

	// 多语言非原始值
	i18nValue := i18n.TKey(language, postInfo.PostName)
	if i18nValue != postInfo.PostName {
		service.NewSysI18n.UpdateKeyValue(language, postInfo.PostName, body.PostName)
		body.PostName = postInfo.PostName
	}
	// 多语言非原始值
	i18nValue2 := i18n.TKey(language, postInfo.Remark)
	if i18nValue2 != postInfo.Remark {
		service.NewSysI18n.UpdateKeyValue(language, postInfo.Remark, body.Remark)
		body.Remark = postInfo.Remark
	}

	postInfo.PostCode = body.PostCode
	postInfo.PostName = body.PostName
	postInfo.PostSort = body.PostSort
	postInfo.StatusFlag = body.StatusFlag
	postInfo.Remark = body.Remark
	postInfo.UpdateBy = reqctx.LoginUserToUserName(c)
	rows := s.sysPostService.Update(postInfo)
	if rows > 0 {
		c.JSON(200, resp.Ok(nil))
		return
	}
	c.JSON(200, resp.Err(nil))
}

// Remove 岗位删除
//
// DELETE /:postId
func (s SysPostController) Remove(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	postId := c.Param("postId")
	if postId == "" {
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_CHEACK, "bind err: postId is empty"))
		return
	}

	// 处理字符转id数组后去重
	uniqueIDs := parse.RemoveDuplicatesToArray(postId, ",")
	// 转换成int64数组类型
	ids := make([]int64, 0)
	for _, v := range uniqueIDs {
		ids = append(ids, parse.Number(v))
	}

	rows, err := s.sysPostService.DeleteByIds(ids)
	if err != nil {
		c.JSON(200, resp.ErrMsg(err.Error()))
		return
	}
	// msg := fmt.Sprintf("删除成功：%d", rows)
	msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
	c.JSON(200, resp.OkMsg(msg))
}

// 导出岗位信息
//
// POST /export
func (s *SysPostController) Export(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	// 查询结果，根据查询条件结果，单页最大值限制
	query := reqctx.QueryMap(c)
	rows, total := s.sysPostService.FindByPage(query)
	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.SysPost) {
		for i := range *arr {
			(*arr)[i].PostName = i18n.TKey(language, (*arr)[i].PostName)
			(*arr)[i].Remark = i18n.TKey(language, (*arr)[i].Remark)
		}
	}
	converI18n(language, &rows)

	// 导出文件名称
	fileName := fmt.Sprintf("post_export_%d_%d.xlsx", len(rows), time.Now().UnixMilli())
	// 第一行表头标题
	headerCells := map[string]string{
		"A1": i18n.TKey(language, "post.export.id"),
		"B1": i18n.TKey(language, "post.export.name"),
		"C1": i18n.TKey(language, "post.export.code"),
		"D1": i18n.TKey(language, "post.export.sort"),
		"E1": i18n.TKey(language, "post.export.status"),
		"F1": i18n.TKey(language, "post.export.time"),
	}
	// 从第二行开始的数据
	dataCells := make([]map[string]any, 0)
	for i, row := range rows {
		idx := strconv.Itoa(i + 2)
		statusValue := i18n.TKey(language, "dictData.disable")
		if row.StatusFlag == "1" {
			statusValue = i18n.TKey(language, "dictData.normal")
		}
		dataCells = append(dataCells, map[string]any{
			"A" + idx: row.PostId,
			"B" + idx: row.PostName,
			"C" + idx: row.PostCode,
			"D" + idx: row.PostSort,
			"E" + idx: statusValue,
			"F" + idx: date.ParseDateToStr(row.CreateTime, date.YYYY_MM_DDTHH_MM_SSZ),
		})
	}

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

	c.FileAttachment(saveFilePath, fileName)
}
