package english_report

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/services"
	"eta/eta_api/utils"
	"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()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	classifyType, _ := this.GetInt("ClassifyType", 0)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = utils.StartIndex(currentIndex, pageSize)

	page := paging.GetPaging(currentIndex, pageSize, 0)
	resp := new(models.EnglishClassifyListResp)

	list, err := models.GetEnglishClassifyList(startSize, pageSize, keyWord, classifyType)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	total, err := models.GetEnglishClassifyListCount(keyWord, classifyType)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if total == 0 {
		resp.List = make([]*models.EnglishClassifyList, 0)
		resp.Paging = page

		br.Data = resp
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}
	var parentIds []int
	for _, v := range list {
		parentIds = append(parentIds, v.Id)
	}

	childMap := make(map[int][]*models.EnglishClassifyList)
	tmpList, err := models.GetEnglishClassifyChildByParentIds(parentIds, keyWord, classifyType)
	if err != nil {
		br.Msg = "获取二级分类失败"
		br.ErrMsg = "获取二级分类失败，Err:" + err.Error()
		return
	}

	// 二级分类-品种权限
	permissionMap := make(map[int][]int)
	{
		classifyIds := make([]int, 0)
		for _, v := range tmpList {
			classifyIds = append(classifyIds, v.Id)
		}
		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 {
		v.EnPermissions = permissionMap[v.Id]
		childMap[v.ParentId] = append(childMap[v.ParentId], v)
	}
	for _, v := range list {
		if child, ok := childMap[v.Id]; ok {
			v.Child = child
		}
	}
	var sortList models.RSClassifyList
	sortList = list
	sort.Sort(sortList)

	for _, item := range sortList {
		var sortChildList models.RSChildClassifyList
		sortChildList = item.Child
		sort.Sort(sortChildList)
		item.Child = sortChildList
	}
	resp.List = sortList
	resp.Paging = page

	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 [get]
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")
	classifyType, _ := this.GetInt("ClassifyType", 0)
	sort, _ := this.GetInt("Sort")

	item := &models.EnglishClassify{
		ClassifyName: classifyName,
		Sort:         sort,
		ParentId:     parentId,
		CreateTime:   time.Now(),
		ModifyTime:   time.Now(),
		ClassifyType: classifyType,
		IsShow:       1,
	}
	counts, err := models.GetEnglishClassifyCountsByName(classifyName, parentId, classifyType)
	if err != nil {
		br.Msg = "查询失败"
		br.ErrMsg = "查询失败,Err:" + err.Error()
		return
	}
	if counts > 0 {
		br.Msg = "该名称已存在"
		br.ErrMsg = "该名称已存在!"
		return
	}
	_, err = models.AddEnglishClassify(item)
	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       "分类Id"
// @Param   ClassifyName   string  true       "分类名称"
// @Param   ParentId   query   int  true       "父级Id 添加父级时为0"
// @Param   Sort   query   string  false       "排序"
// @Success 200 保存成功
// @router /classify/edit [get]
func (this *EnglishReportController) EditClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	classifyId, _ := this.GetInt("ClassifyId")
	classifyName := this.GetString("ClassifyName")
	parentId, _ := this.GetInt("ParentId")
	sort, _ := this.GetInt("Sort")

	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 && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	parent, err := models.GetEnglishReportClassifyById(parentId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}

	if oldItem.ParentId == 0 && parentId > 0 {
		// 一级分类变更为二级分类，禁止
		br.Msg = "一级分类不允许更改为二级分类"
		return
	}

	//判断是否已存在同个名称的分类
	existItem, e := models.GetEnglishClassifyByClassifyNameParentId(classifyName, parentId, oldItem.ClassifyType)
	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 err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}

	//oldParentId := item.ParentId
	item := &models.EnglishClassify{
		Id:           oldItem.Id,
		ClassifyName: classifyName,
		Sort:         sort,
		ParentId:     parentId,
		ModifyTime:   time.Now(),
		ClassifyType: oldItem.ClassifyType,
		IsShow:       1,
	}
	if oldItem.ClassifyType == 1 {
		err = services.UpdateEnglishVideoClassifyId(oldItem, item, parent, classifyId)
		if err != nil {
			br.Msg = err.Error()
			return
		}
	} else {
		// 更新研报里的分类名称
		err = services.UpdateEnglishReportClassifyId(oldItem, item, parent, classifyId)
		if err != nil {
			br.Msg = err.Error()
			return
		}
	}

	err = models.ModifyEnglishClassify(item)
	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
	}

	if classifyInfo.ClassifyType == 0 {
		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
		}
	} else {
		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
		}
	}

	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()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	classifyType, _ := this.GetInt("ClassifyType", 0)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = utils.StartIndex(currentIndex, pageSize)
	list, err := models.GetEnglishFirstClassifyList(classifyType, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	total, err := models.GetEnglishFirstClassifyListCount(classifyType)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.EnglishClassifyListResp)
	resp.List = list
	resp.Paging = page

	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 = "操作成功"
}
