package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// EtaVersionUpdateLogController ETA版本更新日志
type EtaVersionUpdateLogController struct {
	BaseAuthController
}

// PageList
// @Title 更新日志列表-分页
// @Description 更新日志列表-分页
// @Param   Keyword		query	string	false	"关键词"
// @Param   SortType	query	string	false	"排序方式, 1-ASC; 2-DESC"
// @Success 200 Ret=200 获取成功
// @router /page_list [get]
func (this *EtaVersionUpdateLogController) PageList() {
	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
	}

	// 分页
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	cond := ``
	pars := make([]interface{}, 0)
	// 关键词
	keyword := this.GetString("Keyword", "")
	keyword = strings.TrimSpace(keyword)
	if keyword != "" {
		kw := fmt.Sprint("%", keyword, "%")
		cond += ` AND content LIKE ?`
		pars = append(pars, kw)
	}

	sortType, _ := this.GetInt("SortType", 0)
	orderMap := map[int]string{0: "", 1: "update_date ASC", 2: "update_date DESC"}
	order := orderMap[sortType]

	// 获取列表
	businessOb := new(models.EtaVersionUpdateLog)
	total, e := businessOb.GetCountByCondition(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取更新日志总数失败, Err: " + e.Error()
		return
	}
	list, e := businessOb.GetPageItemsByCondition(cond, pars, []string{}, order, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取更新日志列表失败, Err: " + e.Error()
		return
	}

	items := make([]*models.EtaVersionUpdateLogItem, 0)
	for _, v := range list {
		b := new(models.EtaVersionUpdateLogItem)
		b.Id = v.Id
		b.Version = v.Version
		b.Content = v.Content
		b.UpdateDate = v.UpdateDate.Format(utils.FormatDate)
		b.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		b.ModifyTime = v.ModifyTime.Format(utils.FormatDateTime)
		items = append(items, b)
	}

	resp := new(models.EtaVersionUpdateLogListResp)
	resp.List = items
	resp.Paging = paging.GetPaging(currentIndex, pageSize, total)
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// Add
// @Title 新增
// @Description 新增
// @Param	request	body models.EtaVersionUpdateLogAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /add [post]
func (this *EtaVersionUpdateLogController) Add() {
	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
	}

	// 参数校验
	var req models.EtaVersionUpdateLogAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.Version = strings.TrimSpace(req.Version)
	if req.Version == "" {
		br.Msg = "版本号不可为空"
		return
	}
	// 版本号格式: X.X.X
	versionArr := strings.Split(req.Version, ".")
	if len(versionArr) != 3 {
		br.Msg = "请输入正确格式的版本号"
		return
	}
	for _, n := range versionArr {
		if _, e := strconv.Atoi(n); e != nil {
			br.Msg = "请输入正确格式的版本号"
			return
		}
	}

	req.Content = strings.TrimSpace(req.Content)
	if req.Content == "" {
		br.Msg = "更新内容不可为空"
		return
	}
	updateDate, e := time.ParseInLocation(utils.FormatDate, req.UpdateDate, time.Local)
	if e != nil {
		br.Msg = "更新日期格式有误"
		br.ErrMsg = "更新日期格式有误, Err: " + e.Error()
		return
	}

	// 版本号重复校验
	{
		item := new(models.EtaVersionUpdateLog)
		cond := ` AND version = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, req.Version)
		exist, e := item.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取更新日志重复版本号失败, Err: " + e.Error()
			return
		}
		if exist != nil {
			br.Msg = "该版本号已有更新日志, 请重新输入"
			return
		}
	}

	// 更新日期重复校验
	{
		item := new(models.EtaVersionUpdateLog)
		cond := ` AND update_date = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, req.UpdateDate)
		exist, e := item.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取更新日志重复日期失败, Err: " + e.Error()
			return
		}
		if exist != nil {
			br.Msg = "该日期已有更新日志, 请重新选择"
			return
		}
	}

	// 新增
	item := new(models.EtaVersionUpdateLog)
	item.Version = req.Version
	item.UpdateDate = updateDate
	item.Content = req.Content
	item.CreateTime = time.Now().Local()
	item.ModifyTime = time.Now().Local()
	if e = item.Create(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增更新日志失败, Err: " + e.Error()
		return
	}

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

// Edit
// @Title 编辑
// @Description 编辑
// @Param	request	body models.EtaVersionUpdateLogEditReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /edit [post]
func (this *EtaVersionUpdateLogController) Edit() {
	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
	}

	// 参数校验
	var req models.EtaVersionUpdateLogEditReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "参数有误"
		return
	}
	req.Version = strings.TrimSpace(req.Version)
	if req.Version == "" {
		br.Msg = "版本号不可为空"
		return
	}
	// 版本号格式: X.X.X
	versionArr := strings.Split(req.Version, ".")
	if len(versionArr) != 3 {
		br.Msg = "请输入正确格式的版本号"
		return
	}
	for _, n := range versionArr {
		if _, e := strconv.Atoi(n); e != nil {
			br.Msg = "请输入正确格式的版本号"
			return
		}
	}
	req.Content = strings.TrimSpace(req.Content)
	if req.Content == "" {
		br.Msg = "更新内容不可为空"
		return
	}
	updateDate, e := time.ParseInLocation(utils.FormatDate, req.UpdateDate, time.Local)
	if e != nil {
		br.Msg = "更新日期格式有误"
		br.ErrMsg = "更新日期格式有误, Err: " + e.Error()
		return
	}

	// 版本号重复校验
	{
		item := new(models.EtaVersionUpdateLog)
		cond := ` AND version = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, req.Version)
		exist, e := item.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取更新日志重复版本号失败, Err: " + e.Error()
			return
		}
		if exist != nil && exist.Id != req.Id {
			br.Msg = "该版本号已有更新日志, 请重新输入"
			return
		}
	}

	// 更新日期重复校验
	{
		item := new(models.EtaVersionUpdateLog)
		cond := ` AND update_date = ?`
		pars := make([]interface{}, 0)
		pars = append(pars, req.UpdateDate)
		exist, e := item.GetItemByCondition(cond, pars)
		if e != nil && e.Error() != utils.ErrNoRow() {
			br.Msg = "操作失败"
			br.ErrMsg = "获取更新日志重复日期失败, Err: " + e.Error()
			return
		}
		if exist != nil && exist.Id != req.Id {
			br.Msg = "该日期已有更新日志, 请重新选择"
			return
		}
	}

	ob := new(models.EtaVersionUpdateLog)
	item, e := ob.GetItemById(req.Id)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "更新日志不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取更新日志信息失败, Err: " + e.Error()
		return
	}
	item.Version = req.Version
	item.Content = req.Content
	item.UpdateDate = updateDate
	item.ModifyTime = time.Now().Local()
	cols := []string{"Version", "Content", "UpdateDate", "ModifyTime"}
	if e := item.Update(cols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "编辑更新日志失败, Err: " + e.Error()
		return
	}

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

// Del
// @Title 删除
// @Description 删除
// @Param	request	body models.EtaVersionUpdateLogDelReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /del [post]
func (this *EtaVersionUpdateLogController) Del() {
	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
	}

	// 参数校验
	var req models.EtaVersionUpdateLogDelReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "参数有误"
		return
	}

	ob := new(models.EtaVersionUpdateLog)
	item, e := ob.GetItemById(req.Id)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "更新日志不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取更新日志信息失败, Err: " + e.Error()
		return
	}
	if e := item.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除更新日志失败, Err: " + e.Error()
		return
	}

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