package fe_calendar

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/fe_calendar"
	"eta/eta_api/utils"
	"fmt"
	"strings"
	"time"
)

// FeCalendarMatterController 外汇日历-事项
type FeCalendarMatterController struct {
	controllers.BaseAuthController
}

// List
// @Title 事项列表
// @Description 事项列表
// @Param   ChartPermissionId	query	int		true	"品种ID"
// @Param   StartDate			query	string	true	"开始日期"
// @Param   EndDate				query   string	true	"结束日期"
// @Success 200 {object} fe_calendar.FeCalendarMatterListItem
// @router /matter/list [get]
func (this *FeCalendarMatterController) List() {
	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
	}
	params := new(fe_calendar.FeCalendarMatterListReq)
	if e := this.ParseForm(params); e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "入参解析失败, Err: " + e.Error()
		return
	}
	if params.ChartPermissionId <= 0 {
		br.Msg = "请选择品种"
		return
	}

	cond := ``
	pars := make([]interface{}, 0)
	if params.ChartPermissionId > 0 {
		cond += fmt.Sprintf(` AND %s = ?`, fe_calendar.FeCalendarMatterCols.ChartPermissionId)
		pars = append(pars, params.ChartPermissionId)
	}
	if params.StartDate != "" && params.EndDate != "" {
		_, e := time.Parse(utils.FormatDate, params.StartDate)
		if e != nil {
			br.Msg = "开始日期格式有误"
			return
		}
		_, e = time.Parse(utils.FormatDate, params.EndDate)
		if e != nil {
			br.Msg = "结束日期格式有误"
			return
		}
		cond += fmt.Sprintf(` AND %s >= ? AND %s <= ?`, fe_calendar.FeCalendarMatterCols.MatterDate, fe_calendar.FeCalendarMatterCols.MatterDate)
		pars = append(pars, params.StartDate, params.EndDate)
	}

	matterOb := new(fe_calendar.FeCalendarMatter)
	order := fmt.Sprintf(`%s ASC, %s ASC`, fe_calendar.FeCalendarMatterCols.MatterDate, fe_calendar.FeCalendarMatterCols.Sort)
	matters, e := matterOb.GetItemsByCondition(cond, pars, []string{}, order)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取事项列表失败, Err: " + e.Error()
		return
	}

	dateMatter := make(map[string][]*fe_calendar.FeCalendarMatterItem)
	for _, v := range matters {
		d := v.MatterDate.Format(utils.FormatDate)
		if dateMatter[d] == nil {
			dateMatter[d] = make([]*fe_calendar.FeCalendarMatterItem, 0)
		}
		dateMatter[d] = append(dateMatter[d], fe_calendar.FormatFeCalendarMatter2Item(v))
	}
	dateExist := make(map[string]bool)
	resp := make([]*fe_calendar.FeCalendarMatterListItem, 0)
	for _, v := range matters {
		d := v.MatterDate.Format(utils.FormatDate)
		if dateExist[d] {
			continue
		}
		dateExist[d] = true
		resp = append(resp, &fe_calendar.FeCalendarMatterListItem{
			Date:    d,
			Matters: dateMatter[d],
		})
	}

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

// Detail
// @Title 事项详情
// @Description 事项详情
// @Param   ChartPermissionId  query  int  true  "品种ID"
// @Param   MatterDate  query  string  true  "事项日期"
// @Success 200 {object} fe_calendar.FeCalendarMatterItem
// @router /matter/detail [get]
func (this *FeCalendarMatterController) Detail() {
	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
	}
	permissionId, _ := this.GetInt("ChartPermissionId")
	if permissionId <= 0 {
		br.Msg = "请选择品种"
		return
	}
	matterDate := this.GetString("MatterDate")
	if matterDate == "" {
		br.Msg = "请选择日期"
		return
	}
	_, e := time.Parse(utils.FormatDate, matterDate)
	if e != nil {
		br.Msg = "日期格式有误"
		return
	}

	matterOb := new(fe_calendar.FeCalendarMatter)
	cond := fmt.Sprintf(` AND %s = ? AND %s = ?`, fe_calendar.FeCalendarMatterCols.ChartPermissionId, fe_calendar.FeCalendarMatterCols.MatterDate)
	pars := make([]interface{}, 0)
	pars = append(pars, permissionId, matterDate)
	order := fmt.Sprintf(`%s ASC`, fe_calendar.FeCalendarMatterCols.Sort)
	matters, e := matterOb.GetItemsByCondition(cond, pars, []string{}, order)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取事项列表失败, Err: " + e.Error()
		return
	}
	resp := make([]*fe_calendar.FeCalendarMatterItem, 0)
	for _, v := range matters {
		resp = append(resp, fe_calendar.FormatFeCalendarMatter2Item(v))
	}

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

// Save
// @Title 保存事项
// @Description 保存事项
// @Param	request	body fe_calendar.FeCalendarMatterSaveReq true "type json string"
// @Success 200 string "操作成功"
// @router /matter/save [post]
func (this *FeCalendarMatterController) Save() {
	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 fe_calendar.FeCalendarMatterSaveReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数有误"
		br.ErrMsg = "参数解析失败, Err: " + e.Error()
		return
	}
	// 参数校验
	if req.ChartPermissionId <= 0 {
		br.Msg = "请选择品种"
		return
	}
	if req.MatterDate == "" {
		br.Msg = "请选择日期"
		return
	}
	var matterMonth string
	matterDate, e := time.ParseInLocation(utils.FormatDate, req.MatterDate, time.Local)
	if e != nil {
		br.Msg = "日期格式有误"
		return
	}
	matterMonth = matterDate.Format("2006-01")
	if len(req.Matters) > 0 {
		for _, v := range req.Matters {
			if v.MatterType != fe_calendar.MatterTypeFree && v.MatterType != fe_calendar.MatterTypeEdb && v.MatterType != fe_calendar.MatterTypePredict {
				br.Msg = "事项类型有误"
				br.ErrMsg = fmt.Sprintf("事项类型有误, MatterType: %d", v.MatterType)
				return
			}
			v.Title = strings.TrimSpace(v.Title)
			if v.Title == "" {
				br.Msg = "请输入指标/事项名称"
				return
			}
			if len([]rune(v.Title)) > 15 {
				br.Msg = "名称超出15个字，请重新编辑"
				return
			}
			if v.MatterType == fe_calendar.MatterTypeEdb || v.MatterType == fe_calendar.MatterTypePredict {
				if v.EdbInfoId <= 0 || v.EdbUniqueCode == "" || v.EdbCode == "" {
					br.Msg = "指标信息有误"
					br.ErrMsg = fmt.Sprintf("指标信息有误, EdbInfoId: %d, EdbUniqueCode: %s, EdbCode: %s", v.EdbInfoId, v.EdbUniqueCode, v.EdbCode)
					return
				}
			}
		}
	}

	// 品种信息
	permissionItem, e := models.GetChartPermissionById(req.ChartPermissionId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取品种失败, Err: " + e.Error()
		return
	}

	// 获取已有事项
	matterOb := new(fe_calendar.FeCalendarMatter)
	cond := fmt.Sprintf(` AND %s = ? AND %s = ?`, fe_calendar.FeCalendarMatterCols.ChartPermissionId, fe_calendar.FeCalendarMatterCols.MatterDate)
	pars := make([]interface{}, 0)
	pars = append(pars, req.ChartPermissionId, req.MatterDate)
	order := fmt.Sprintf(`%s ASC`, fe_calendar.FeCalendarMatterCols.Sort)
	matters, e := matterOb.GetItemsByCondition(cond, pars, []string{}, order)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取已有事项列表失败, Err: " + e.Error()
		return
	}

	addMatters := make([]*fe_calendar.FeCalendarMatter, 0)
	editMatters := make([]*fe_calendar.FeCalendarMatter, 0)
	removeMatters := make([]*fe_calendar.FeCalendarMatter, 0)
	updateCols := []string{fe_calendar.FeCalendarMatterCols.Title, fe_calendar.FeCalendarMatterCols.FontColor, fe_calendar.FeCalendarMatterCols.FillingColor, fe_calendar.FeCalendarMatterCols.FontBold, fe_calendar.FeCalendarMatterCols.Sort, fe_calendar.FeCalendarMatterCols.ChartPermissionName, fe_calendar.FeCalendarMatterCols.ModifyTime}

	editIds := make([]int, 0)
	editMatterMap := make(map[int]*fe_calendar.FeCalendarMatterSaveItem)
	for _, v := range req.Matters {
		// 更新的事项map
		if v.FeCalendarMatterId > 0 {
			editIds = append(editIds, v.FeCalendarMatterId)
			editMatterMap[v.FeCalendarMatterId] = v
			continue
		}
		// 新增事项
		addMatters = append(addMatters, &fe_calendar.FeCalendarMatter{
			ChartPermissionId:   req.ChartPermissionId,
			ChartPermissionName: permissionItem.PermissionName,
			MatterMonth:         matterMonth,
			MatterDate:          matterDate,
			Title:               strings.TrimSpace(v.Title),
			MatterType:          v.MatterType,
			EdbInfoId:           v.EdbInfoId,
			EdbUniqueCode:       v.EdbUniqueCode,
			EdbCode:             v.EdbCode,
			FontColor:           v.FontColor,
			FillingColor:        v.FillingColor,
			FontBold:            v.FontBold,
			Sort:                v.Sort,
			SysUserId:           sysUser.AdminId,
			SysUserName:         sysUser.RealName,
			CreateTime:          time.Now().Local(),
			ModifyTime:          time.Now().Local(),
		})
	}
	for _, v := range matters {
		// 移除的事项
		if !utils.InArrayByInt(editIds, v.FeCalendarMatterId) {
			removeMatters = append(removeMatters, v)
			continue
		}
		// 编辑的事项
		ed := editMatterMap[v.FeCalendarMatterId]
		if ed != nil {
			v.Title = strings.TrimSpace(ed.Title)
			v.FontColor = ed.FontColor
			v.FillingColor = ed.FillingColor
			v.FontBold = ed.FontBold
			v.Sort = ed.Sort
			v.ChartPermissionName = permissionItem.PermissionName
			v.ModifyTime = time.Now().Local()
			editMatters = append(editMatters, v)
		}
	}

	// 保存/删除
	if e = matterOb.Save(addMatters, editMatters, removeMatters, updateCols); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "保存事项失败, Err: " + e.Error()
		return
	}

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

// PermissionList
// @Title 品种列表
// @Description 品种列表
// @Success 200 {object} models.SimpleChartPermission
// @router /permission/list [get]
func (this *FeCalendarMatterController) PermissionList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()

	permissions, e := models.GetChartPermissionsByProductId()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取品种列表失败, Err: " + e.Error()
		return
	}
	resp := make([]*models.SimpleChartPermission, 0)
	parentPermissions := make(map[int][]*models.SimpleChartPermission, 0)
	for _, v := range permissions {
		if v.ParentId > 0 {
			if parentPermissions[v.ParentId] == nil {
				parentPermissions[v.ParentId] = make([]*models.SimpleChartPermission, 0)
			}
			parentPermissions[v.ParentId] = append(parentPermissions[v.ParentId], models.FormatChartPermission2Simple(v))
			continue
		}
		resp = append(resp, models.FormatChartPermission2Simple(v))
	}
	for _, v := range resp {
		v.Children = parentPermissions[v.ChartPermissionId]
	}

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