package fe_calendar

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/request"
	"hongze/hongze_yb/models/tables/fe_calendar_matter"
	"hongze/hongze_yb/models/tables/rddp/chart_permission"
	"hongze/hongze_yb/services/company"
	userService "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"time"
)

// PermissionList 品种列表
func PermissionList(c *gin.Context) {
	userInfo := userService.GetInfoByClaims(c)

	// 获取用户有权限的品种
	validPermissionIds, e := company.GetValidPermissionIdListByCompany2ProductId(userInfo.CompanyID, int64(utils.FiccProductId))
	if e != nil {
		response.FailMsg("获取失败", "获取有权限品种列表失败, Err: "+e.Error(), c)
		return
	}

	// 获取品种下面挂有日历的品种列表

	matterOb := new(fe_calendar_matter.FeCalendarMatter)
	matterPermissionIds, e := matterOb.GetAllPermissionIds()
	if e != nil {
		response.FailMsg("获取失败", "获取有日历品种列表失败, Err: "+e.Error(), c)
		return
	}

	// 遍历品种树
	permissions, e := chart_permission.GetChartPermissionsByProductId()
	if e != nil {
		response.FailMsg("获取失败", "获取品种列表失败, Err: "+e.Error(), c)
		return
	}
	parents := make([]*chart_permission.SimpleChartPermission, 0)
	parentPermissions := make(map[int][]*chart_permission.SimpleChartPermission, 0)
	showPermissionIds := make(map[int]struct{})
	for _, v := range permissions {
		if v.ParentId > 0 && utils.InArrayByInt(validPermissionIds, int(v.ChartPermissionID)) && utils.InArrayByInt(matterPermissionIds, int(v.ChartPermissionID)) {
			if parentPermissions[v.ParentId] == nil {
				parentPermissions[v.ParentId] = make([]*chart_permission.SimpleChartPermission, 0)
			}
			parentPermissions[v.ParentId] = append(parentPermissions[v.ParentId], chart_permission.FormatChartPermission2Simple(v))
			showPermissionIds[int(v.ChartPermissionID)] = struct{}{}
			showPermissionIds[v.ParentId] = struct{}{}
			continue
		}
		parents = append(parents, chart_permission.FormatChartPermission2Simple(v))
	}
	var resp chart_permission.FaCalendarPermissionResp
	list := make([]*chart_permission.SimpleChartPermission, 0)
	for _, v := range parents {
		if parentPermissions[v.ChartPermissionId] == nil {
			continue
		}
		v.Children = parentPermissions[v.ChartPermissionId]
		list = append(list, v)
	}
	lastEditPermissionId := 0
	lastEditPermissionName := ""
	// 查询最近被编辑过的品种ID
	matter, e := matterOb.GetLaststModifyMatter()
	if e != nil && e.Error() != utils.NotEmpty() {
		response.FailMsg("获取失败", "获取品种列表失败, Err: "+e.Error(), c)
		return
	}
	if e == nil && matter != nil && matter.FeCalendarMatterId > 0 {
		if _, ok := showPermissionIds[matter.ChartPermissionId]; ok {
			lastEditPermissionId = matter.ChartPermissionId
			lastEditPermissionName = matter.ChartPermissionName
		}
	}

	resp.CheckedPermissionId = lastEditPermissionId
	resp.CheckedPermissionName = lastEditPermissionName
	resp.List = list
	response.OkData("获取成功", resp, c)
}

// LastestPermissionMonth 获取品种有数据最近的月份
func LastestPermissionMonth(c *gin.Context) {
	var req request.FeCalendarLastestPermissionMonthReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.ChartPermissionId <= 0 {
		response.Fail("请选择品种", c)
		return
	}
	var month string
	matterOb := new(fe_calendar_matter.FeCalendarMatter)

	// 当月事项
	currentMonth := time.Now().Format("2006-01")
	cond := ` chart_permission_id = ? AND matter_month = ?`
	pars := make([]interface{}, 0)
	pars = append(pars, req.ChartPermissionId, currentMonth)
	item, e := matterOb.GetItemByCondition(cond, pars)
	if e != nil && e != utils.ErrNoRow {
		response.FailMsg("获取失败", "获取当月事项失败, Err: "+e.Error(), c)
		return
	}
	if item != nil && item.FeCalendarMatterId > 0 {
		month = currentMonth
	}

	// 无当月事项则查询最近的
	if month == "" {
		lastest, e := matterOb.GetLastestMonthItemByPermissionId(req.ChartPermissionId)
		if e != nil && e != utils.ErrNoRow {
			response.FailMsg("获取失败", "获取事项失败, Err: "+e.Error(), c)
			return
		}
		if lastest != nil && lastest.FeCalendarMatterId > 0 {
			month = lastest.MatterMonth
		}
	}
	response.OkData("获取成功", month, c)
}

// MatterList 事项列表
func MatterList(c *gin.Context) {
	var req request.FeCalendarMatterListReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.ChartPermissionId <= 0 {
		response.Fail("请选择品种", c)
		return
	}
	//userInfo := userService.GetInfoByClaims(c)

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

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

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

	response.OkData("获取成功", resp, c)
}

// MatterDetail 事项详情
func MatterDetail(c *gin.Context) {
	var req request.FeCalendarMatterDetailReq
	if err := c.Bind(&req); err != nil {
		response.Fail("参数有误", c)
		return
	}
	if req.ChartPermissionId <= 0 {
		response.Fail("请选择品种", c)
		return
	}
	if req.MatterDate == "" {
		response.Fail("请选择日期", c)
		return
	}
	_, e := time.Parse(utils.FormatDate, req.MatterDate)
	if e != nil {
		response.Fail("日期格式有误", c)
		return
	}
	//userInfo := userService.GetInfoByClaims(c)

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

	response.OkData("获取成功", resp, c)
}
