package english_report

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/report_approve"
	"eta/eta_mobile/services"
	"eta/eta_mobile/utils"
	"fmt"
	"sort"
	"time"
)

// EnglishClassifyController 英文分类
type EnglishClassifyController struct {
	controllers.BaseAuthController
}

// ListClassify
// @Title 获取分类列表
// @Description 获取分类列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "检索关键词"
// @Param   CompanyType   query   string  false       "产品类型，枚举值：'ficc','权益';不传默认返回全部"
// @Success 200 {object} models.EnglishClassifyListResp
// @router /classify/list [get]
func (this *EnglishReportController) ListClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	keyWord := this.GetString("KeyWord")
	reqEnabled, _ := this.GetInt("Enabled", -1)
	enabled := -1
	if reqEnabled == 1 {
		enabled = reqEnabled
	}
	resp := new(models.EnglishClassifyListResp)

	// 处理一级分类分页的情况
	rootList, err := models.GetEnglishClassifyRootId(keyWord, enabled)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if len(rootList) == 0 {
		resp.List = make([]*models.EnglishClassifyList, 0)

		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}
	var ids []int
	var rootIds []int
	rootMap := make(map[int]struct{}, 0)
	for _, v := range rootList {
		rootIds = append(rootIds, v.Id)
		rootMap[v.Id] = struct{}{}
	}

	//获取相关的分类ID
	idList, err := models.GetEnglishClassifyListByRootId(rootIds, keyWord, enabled)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	secondListMap := make(map[int][]*models.EnglishClassifyList)
	thirdListMap := make(map[int][]*models.EnglishClassifyList)
	var thirdIds []int
	var sortChildList models.RSChildClassifyList
	// 三级分类-品种权限
	permissionMap := make(map[int][]int)

	if len(idList) > 0 {
		childIdMap := make(map[int]struct{}, 0)
		for _, v := range idList {
			if _, ok := childIdMap[v.ParentId]; !ok {
				ids = append(ids, v.ParentId)
				childIdMap[v.ParentId] = struct{}{}
			}
			if _, ok := childIdMap[v.Id]; !ok {
				ids = append(ids, v.Id)
				childIdMap[v.Id] = struct{}{}
			}
		}
		tmpList, err := models.GetEnglishClassifyChildByIds(ids)
		if err != nil {
			br.Msg = "获取二级分类失败"
			br.ErrMsg = "获取二级分类失败，Err:" + err.Error()
			return
		}
		for _, v := range tmpList {
			if _, ok := rootMap[v.ParentId]; !ok {
				thirdIds = append(thirdIds, v.Id)
			}
		}
		{
			classifyIds := thirdIds
			if len(classifyIds) > 0 {
				cond := fmt.Sprintf(` AND %s IN (%s)`, models.EnClassifyPermissionColumns.EnClassifyId, utils.GetOrmInReplace(len(classifyIds)))
				pars := make([]interface{}, 0)
				pars = append(pars, classifyIds)
				ob := new(models.EnClassifyPermission)
				items, e := ob.GetItemsByCondition(cond, pars, []string{}, "")
				if e != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取客户权限列表失败, Err: " + e.Error()
					return
				}
				for _, v := range items {
					if permissionMap[v.EnClassifyId] == nil {
						permissionMap[v.EnClassifyId] = make([]int, 0)
					}
					permissionMap[v.EnClassifyId] = append(permissionMap[v.EnClassifyId], v.EnPermissionId)
				}
			}
		}
		// 处理三级分类
		for _, v := range tmpList {
			if _, ok := rootMap[v.ParentId]; !ok {
				if p, ok1 := permissionMap[v.Id]; ok1 {
					v.EnPermissions = p
				}
				thirdListMap[v.ParentId] = append(thirdListMap[v.ParentId], v)
			}
		}

		//处理二级分类
		for _, v := range tmpList {
			if _, ok := rootMap[v.ParentId]; ok {
				if child, ok1 := thirdListMap[v.Id]; ok1 {
					sortChildList = child
					sort.Sort(sortChildList)
					v.Child = sortChildList
				}
				secondListMap[v.ParentId] = append(secondListMap[v.ParentId], v)
			}
		}
	}

	//处理一级分类
	var sortList models.RSClassifyList
	for _, v := range rootList {
		if child, ok := secondListMap[v.Id]; ok {
			sortChildList = child
			sort.Sort(sortChildList)
			v.Child = sortChildList
		}
		sortList = append(sortList, v)
	}

	sort.Sort(sortList)

	resp.List = sortList

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

// @Title 新增分类
// @Description 新增分类接口
// @Param   ClassifyName   int  true       "分类名称"
// @Param   ParentId   query   int  true       "父级Id 添加父级时为0"
// @Param   Sort   query   string  false       "排序"
// @Success 200 新增成功
// @router /classify/add [post]
func (this *EnglishReportController) AddClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	//classifyName := this.GetString("ClassifyName")
	//parentId, _ := this.GetInt("ParentId")
	var req models.EnClassifyAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	classifyName := req.ClassifyName
	parentId := req.ParentId
	ob := new(models.EnglishClassify)
	// 查新父级分类是否存在
	rootId := 0
	if parentId > 0 {
		parentClassify, err := models.GetEnglishReportClassifyById(parentId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "上级分类不存在"
				return
			}
			br.Msg = "查询上级分类信息失败"
			br.ErrMsg = "查询上级分类信息失败,Err:" + err.Error()
			return
		}
		if parentClassify.RootId == 0 {
			rootId = parentClassify.Id
		} else {
			rootId = parentClassify.RootId
		}
	}
	maxSort, e := ob.GetMaxSort()
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "查询品种排序失败, Err: " + e.Error()
		return
	}

	nowTime := time.Now().Local()
	item := &models.EnglishClassify{
		ClassifyName: classifyName,
		Sort:         maxSort + 1,
		ParentId:     parentId,
		RootId:       rootId,
		CreateTime:   nowTime,
		ModifyTime:   nowTime,
		IsShow:       1,
		Enabled:      1,
	}
	counts, err := models.GetEnglishClassifyCountsByName(classifyName, parentId)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败,Err:" + err.Error()
		return
	}
	if counts > 0 {
		br.Msg = "该名称已存在"
		br.ErrMsg = "该名称已存在!"
		return
	}
	var newId int64
	newId, err = models.AddEnglishClassify(item)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	item.Id = int(newId)
	if parentId == 0 { //一级目录的rootId等于自己本身
		item.RootId = int(newId)
		err = item.UpdateEnglishClassify([]string{"RootId"})
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
	}

	if item.ParentId != item.RootId && item.ParentId > 0 { //三级分类才能绑定品种权限
		permissions := make([]*models.EnClassifyPermission, 0)
		for _, p := range req.EnPermissions {
			v := new(models.EnClassifyPermission)
			v.EnPermissionId = p
			v.EnClassifyId = item.Id
			v.CreateTime = nowTime
			permissions = append(permissions, v)
		}
		if e = models.CreateEnClassifyPermissions(permissions); e != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "更新分类品种权限失败, Err: " + e.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// EditClassify
// @Title 编辑分类
// @Description 编辑分类接口
// @Param   ClassifyId   int  true       "分类Id"
// @Param   ClassifyName   string  true       "分类名称"
// @Param   ParentId   query   int  true       "父级Id 添加父级时为0"
// @Param   Sort   query   string  false       "排序"
// @Success 200 保存成功
// @router /classify/edit [post]
func (this *EnglishReportController) EditClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req models.EnClassifyEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	classifyId := req.ClassifyId
	classifyName := req.ClassifyName
	parentId := req.ParentId
	//ob := new(models.EnglishClassify)

	if parentId == classifyId {
		br.Msg = "上级分类不能选择自己"
		return
	}
	if classifyId <= 0 {
		br.Msg = "参数错误"
		return
	}
	if classifyName == "" {
		br.Msg = "分类名称不可为空"
		return
	}

	oldItem, err := models.GetEnglishReportClassifyById(classifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "当前分类不存在"
			return
		}
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if oldItem.ParentId == 0 && parentId > 0 {
		// 一级分类变更为二级分类，禁止
		br.Msg = "一级分类不允许更改为二级分类或三级分类"
		return
	}

	var parent *models.EnglishClassify
	rootId := 0
	if parentId > 0 {
		parent, err = models.GetEnglishReportClassifyById(parentId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "上级分类不存在"
				return
			}
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取信息失败,Err:" + err.Error()
			return
		}
		//二级分类不允许改成三级分类
		if oldItem.ParentId > 0 && oldItem.ParentId == oldItem.RootId {
			if parent.ParentId > 0 {
				//即将改为为三级分类
				br.Msg = "二级分类不允许更改为三级分类"
				return
			}
		}

		if parent.RootId == 0 {
			rootId = parent.Id
		} else {
			rootId = parent.RootId
		}
	}

	//判断是否已存在同个名称的分类
	existItem, e := models.GetEnglishClassifyByClassifyNameParentId(classifyName, parentId)
	if e != nil {
		if e.Error() != utils.ErrNoRow() {
			br.Msg = "查询已存在的分类出错"
			br.ErrMsg = "查询已存在的分类出错, Err:" + e.Error()
			return
		}
	}
	if e == nil && existItem.Id != oldItem.Id {
		br.Msg = "分类名称:" + classifyName + "已存在"
		return
	}

	if parentId == 0 { //一级分类的顶级分类为自己的ID
		rootId = oldItem.Id
	}

	/*maxSort, e := ob.GetMaxSortByParentId(parentId)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "查询品种排序失败, Err: " + e.Error()
		return
	}*/

	nowTime := time.Now().Local()

	item := &models.EnglishClassify{
		Id:           oldItem.Id,
		ClassifyName: classifyName,
		//	Sort:         maxSort + 1,
		ParentId:   parentId,
		RootId:     rootId,
		ModifyTime: nowTime,
		IsShow:     1,
	}
	{
		// 更新研报里的分类名称
		err = services.UpdateEnglishReportClassifyId(oldItem, item, classifyId)
		if err != nil {
			br.Msg = err.Error()
			return
		}

		//更新相关联的路演视频里的分类名称
		err = services.UpdateEnglishVideoClassifyId(oldItem, item, classifyId)
		if err != nil {
			br.Msg = err.Error()
			return
		}
	}
	err = models.ModifyEnglishClassify(item)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	// 更新权限
	if item.ParentId != item.RootId && item.ParentId > 0 { //三级分类才能编辑品种
		permissions := make([]*models.EnClassifyPermission, 0)
		for _, p := range req.EnPermissions {
			v := new(models.EnClassifyPermission)
			v.EnPermissionId = p
			v.EnClassifyId = req.ClassifyId
			v.CreateTime = nowTime
			permissions = append(permissions, v)
		}
		if e = models.ClearAndCreateEnClassifyPermissions(req.ClassifyId, permissions); e != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "更新分类品种权限失败, Err: " + e.Error()
			return
		}
	}

	err = models.UpdateEnglishReportClassifyByFirstSecondClassifyId(classifyId, parentId)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	err = models.UpdateEnglishVideoClassifyByFirstSecondClassifyId(classifyId, parentId)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// @Title 删除分类列表
// @Description 删除分类列表
// @Param   ClassifyId   int  true       "分类名称"
// @Param   ParentId   query   int  true   "父级Id"
// @Success 200 保存成功
// @router /classify/delete [get]
func (this *EnglishReportController) DelClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	classifyId, _ := this.GetInt("ClassifyId")
	//parentId, _ := this.GetInt("ParentId")

	classifyInfo, err := models.GetEnglishReportClassifyById(classifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "当前分类不存在"
			br.ErrMsg = "当前分类不存在"
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}

	count, err := models.GetEnglishClassifyChildCounts(classifyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	if count > 0 {
		br.Msg = "请先删除该分类下关联分类"
		br.Ret = 403
		return
	}
	reportCount, e := models.GetEnglishReportCounts(classifyId, classifyInfo.ParentId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取失败，Err:" + e.Error()
		return
	}

	if reportCount > 0 {
		br.Msg = "该分类有关联报告，不允许删除"
		br.Ret = 403
		return
	}
	videoCount, e := models.GetEnglishVideoCounts(classifyId, classifyInfo.ParentId)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取失败，Err:" + e.Error()
		return
	}

	if videoCount > 0 {
		br.Msg = "该分类有关联的路演视频，不允许删除"
		br.Ret = 403
		return
	}

	// 查询该分类是否关联了审批流
	flowOb := new(report_approve.ReportApproveFlow)
	flowCond := fmt.Sprintf(` AND %s = ? AND (%s = ? Or %s = ?)`, report_approve.ReportApproveFlowCols.ReportType, report_approve.ReportApproveFlowCols.ClassifyFirstId, report_approve.ReportApproveFlowCols.ClassifySecondId)
	flowPars := make([]interface{}, 0)
	flowPars = append(flowPars, report_approve.FlowReportTypeEnglish, classifyId, classifyId)
	flowCount, e := flowOb.GetCountByCondition(flowCond, flowPars)
	if e != nil {
		br.Msg = "检测失败"
		br.ErrMsg = "获取关联审批流失败, Err: " + e.Error()
		return
	}
	if flowCount > 0 {
		br.Msg = "该分类关联审批流，不允许删除"
		br.Ret = 403
		return
	}

	if err = models.DeleteEnglishClassify(classifyId); err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除报告失败, Err: " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// @Title 获取一级分类列表
// @Description 获取一级分类列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   CompanyType   query   string  false       "产品类型，枚举值：'ficc','权益';不传默认返回全部"
// @Success 200 {object} models.EnglishClassifyListResp
// @router /classify/first/list [get]
func (this *EnglishReportController) FistListClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	rootList, err := models.GetEnglishFirstClassifyList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	total, err := models.GetEnglishFirstClassifyListCount()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(models.EnglishClassifyListResp)

	if total == 0 {
		resp.List = make([]*models.EnglishClassifyList, 0)

		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}
	rootMap := make(map[int]struct{}, 0)
	var rootIds []int
	for _, v := range rootList {
		rootMap[v.Id] = struct{}{}
		rootIds = append(rootIds, v.Id)
	}
	tmpList, err := models.GetEnglishSecondClassifyList(rootIds)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	secondListMap := make(map[int][]*models.EnglishClassifyList)
	//处理二级分类
	for _, v := range tmpList {
		if _, ok := rootMap[v.ParentId]; ok {
			secondListMap[v.ParentId] = append(secondListMap[v.ParentId], v)
		}
	}

	//处理一级分类
	var sortList models.RSClassifyList
	var sortChildList models.RSChildClassifyList
	for _, v := range rootList {
		if child, ok := secondListMap[v.Id]; ok {
			sortChildList = child
			sort.Sort(sortChildList)
			v.Child = sortChildList
		}
		sortList = append(sortList, v)
	}

	sort.Sort(sortList)

	resp.List = sortList

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

// PermissionEdit
// @Title 编辑品种权限
// @Description 编辑品种权限
// @Param	request	body models.EnPermissionAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /permission/edit [post]
func (this *EnglishClassifyController) PermissionEdit() {
	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.EnClassifyPermissionEditReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	if req.ClassifyId <= 0 {
		br.Msg = "参数有误"
		return
	}

	// 更新品种权限
	nowTime := time.Now().Local()
	permissions := make([]*models.EnClassifyPermission, 0)
	for _, p := range req.EnPermissions {
		v := new(models.EnClassifyPermission)
		v.EnPermissionId = p
		v.EnClassifyId = req.ClassifyId
		v.CreateTime = nowTime
		permissions = append(permissions, v)
	}
	if e := models.ClearAndCreateEnClassifyPermissions(req.ClassifyId, permissions); e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "更新分类品种权限失败, Err: " + e.Error()
		return
	}

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

// MoveClassify
// @Title 移动分类接口
// @Description 移动分类
// @Param	request	body models.EnglishClassifyMoveReq true "type json string"
// @Success 200 新增成功
// @router /classify/move [post]
func (this *EnglishReportController) MoveClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.EnglishClassifyMoveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ClassifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}
	e, msg := services.MoveEnglishReportClassify(req)
	if e != nil {
		br.Msg = msg
		br.ErrMsg = "移动分类失败, Err: " + e.Error()
		return
	}

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

// SetEnabled
// @Title 启用/禁用分类接口
// @Description 启用/禁用分类
// @Param	request	body models.ClassifyMoveReq true "type json string"
// @Success 200 新增成功
// @router /classify/enabled/set [post]
func (this *EnglishReportController) SetEnabled() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.EnglishClassifySetEnabledReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ClassifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}
	if req.Enabled != 0 && req.Enabled != 1 {
		br.Msg = "请选择正确的启用禁用状态"
		return
	}
	item, err := models.GetEnglishReportClassifyById(req.ClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			return
		}
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if item == nil {
		br.Msg = "分类不存在"
		return
	}
	ob := new(models.EnglishClassify)
	//设置分类启用、禁用状态
	err = ob.SetEnabled(req.ClassifyId, req.Enabled)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}

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