package controllers

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/utils"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strings"
	"time"
)

type OutLinkController struct {
	BaseAuthController
}

// Save
// @Title 保存外部链接
// @Description 保存外部链接
// @Param	request	body models.OutLinkSaveReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /save [post]
func (ol *OutLinkController) Save() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		ol.Data["json"] = br
		ol.ServeJSON()
	}()
	var req models.OutLinkSaveReq
	if e := json.Unmarshal(ol.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.Title = strings.TrimSpace(req.Title)
	if req.Title == "" {
		br.Msg = "请输入菜单名称"
		return
	}
	req.Url = strings.TrimSpace(req.Url)
	if req.Url == "" {
		br.Msg = "请输入页面链接地址"
		return
	}

	outLink := new(models.OutLink)
	if req.Id > 0 {
		// 编辑
		err := outLink.GetItemById(req.Id)
		if err != nil {
			br.Msg = "该记录不存在"
			br.ErrMsg = "该记录不存在，Err:" + err.Error()
			return
		}
		if outLink.Title == req.Title && outLink.Url == req.Url {
			br.Ret = 200
			br.Success = true
			br.Msg = "操作成功"
			return
		}
		outLink.Title = req.Title
		outLink.Url = req.Url
		outLink.ModifyTime = time.Now()
		err = outLink.Update([]string{"Title", "Url", "ModifyTime"})
		if err != nil {
			br.Msg = "更新失败"
			br.ErrMsg = "更新失败，Err:" + err.Error()
			return
		}
	} else {
		outLink.Title = req.Title
		outLink.Url = req.Url
		outLink.CreateTime = time.Now()
		outLink.SysAdminId = ol.SysUser.AdminId
		outLink.SysAdminName = ol.SysUser.AdminName
		outLink.ModifyTime = time.Now()
		err := outLink.Create()
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败，Err:" + err.Error()
			return
		}
	}

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

// Del
// @Title 删除外部链接
// @Description 删除外部链接
// @Param	request	body models.OutLinkReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /del [post]
func (ol *OutLinkController) Del() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		ol.Data["json"] = br
		ol.ServeJSON()
	}()
	var req models.OutLinkReq
	if e := json.Unmarshal(ol.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.Id == 0 {
		br.Msg = "请选择要删除的外部链接"
		return
	}

	outLink := new(models.OutLink)
	// 查询
	err := outLink.GetItemById(req.Id)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该记录已被删除, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}

	err = outLink.Del()
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}

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

// List
// @Title 外部链接列表
// @Description 外部链接列表
// @Param   PageSize  query  int  true  "每页记录数"
// @Param   CurrentIndex  query  int  true  "请求页码"
// @Success 200 Ret=200 操作成功
// @router /list [get]
func (ol *OutLinkController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		ol.Data["json"] = br
		ol.ServeJSON()
	}()
	var startSize int
	pageSize, _ := ol.GetInt("PageSize")
	currentIndex, _ := ol.GetInt("CurrentIndex")
	sortParam := ol.GetString("SortParam")
	sortType := ol.GetString("SortType")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	var orderRule string
	if sortParam == "create_time" {
		orderRule = " create_time "
	}
	if orderRule != "" {
		if strings.ToLower(sortType) == "asc" || strings.ToLower(sortType) == "desc" {
			orderRule += sortType
		}
	}

	startSize = paging.StartIndex(currentIndex, pageSize)

	item := new(models.OutLink)
	cond := ``
	pars := make([]interface{}, 0)

	total, list, e := item.GetPageItemsByCondition(startSize, pageSize, cond, pars, []string{}, orderRule)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取外部链接列表失败, Err: " + e.Error()
		return
	}

	respList := make([]*models.OutLinkItem, 0)
	for i := range list {
		v := new(models.OutLinkItem)
		v.Id = list[i].Id
		v.Title = list[i].Title
		v.Url = list[i].Url
		v.CreateTime = list[i].CreateTime.Format(utils.FormatDateTime)
		v.ModifyTime = list[i].ModifyTime.Format(utils.FormatDateTime)
		respList = append(respList, v)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &models.OutLinkListResp{
		Paging: page,
		List:   respList,
	}
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	return
}

// AllList
// @Title 外部链接展示列表
// @Description 外部链接展示列表
// @Success 200 Ret=200 操作成功
// @router /all [get]
func (ol *OutLinkController) AllList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		ol.Data["json"] = br
		ol.ServeJSON()
	}()

	item := new(models.OutLink)
	cond := ``
	pars := make([]interface{}, 0)
	list, e := item.GetItemsByCondition(cond, pars, "")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取外部链接列表失败, Err: " + e.Error()
		return
	}
	respList := make([]*models.OutLinkItem, 0)
	for i := range list {
		v := new(models.OutLinkItem)
		v.Id = list[i].Id
		v.Title = list[i].Title
		v.Url = list[i].Url
		v.CreateTime = list[i].CreateTime.Format(utils.FormatDateTime)
		v.ModifyTime = list[i].ModifyTime.Format(utils.FormatDateTime)
		respList = append(respList, v)
	}
	resp := &models.OutLinkListResp{
		List: respList,
	}
	
	if ol.SysUser.AdminName != "" {
		desEncrypt := utils.DesBase64Encrypt([]byte(ol.SysUser.AdminName), utils.DesKeySalt)
		resp.UserCode = string(desEncrypt)
	}

	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	return
}
