package english_report

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

// EnPermissionController 英文权限
type EnPermissionController struct {
	controllers.BaseAuthController
}

// Add
// @Title 新增品种权限
// @Description 新增品种权限
// @Param	request	body models.EnPermissionAddReq true "type json string"
// @Success 200 Ret=200 操作成功
// @router /add [post]
func (this *EnPermissionController) 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.EnPermissionAddReq
	if e := json.Unmarshal(this.Ctx.Input.RequestBody, &req); e != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + e.Error()
		return
	}
	req.EnPermissionName = strings.TrimSpace(req.EnPermissionName)
	if req.EnPermissionName == "" {
		br.Msg = "请输入品种名称"
		return
	}

	// 重名校验
	existOB := new(models.EnPermission)
	existCond := fmt.Sprintf(` AND %s = ? AND %s = ?`, models.EnPermissionColumns.EnPermissionName, models.EnPermissionColumns.ParentId)
	existPars := make([]interface{}, 0)
	existPars = append(existPars, req.EnPermissionName, req.ParentId)
	exist, e := existOB.GetItemByCondition(existCond, existPars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "操作失败"
		br.ErrMsg = "获取重名品种权限失败, Err: " + e.Error()
		return
	}
	if exist != nil && exist.EnPermissionId > 0 {
		br.Msg = "品种名称已存在"
		return
	}

	// 新增
	item := new(models.EnPermission)
	item.EnPermissionName = req.EnPermissionName
	item.ParentId = req.ParentId
	item.Sort = req.Sort
	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 = "操作成功"
	br.Data = item.EnPermissionId
}

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

	// 重名校验
	ob := new(models.EnPermission)
	existCond := fmt.Sprintf(` AND %s = ? AND %s = ? AND %s <> ?`, models.EnPermissionColumns.EnPermissionName, models.EnPermissionColumns.ParentId, models.EnPermissionColumns.EnPermissionId)
	existPars := make([]interface{}, 0)
	existPars = append(existPars, req.EnPermissionName, req.ParentId, req.EnPermissionId)
	exist, e := ob.GetItemByCondition(existCond, existPars)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "操作失败"
		br.ErrMsg = "获取重名品种权限失败, Err: " + e.Error()
		return
	}
	if exist != nil && exist.EnPermissionId > 0 {
		br.Msg = "品种名称已存在"
		return
	}

	item, e := ob.GetItemById(req.EnPermissionId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "品种不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取品种权限失败, Err: " + e.Error()
		return
	}
	originPid := item.ParentId
	item.EnPermissionName = req.EnPermissionName
	item.ParentId = req.ParentId
	item.Sort = req.Sort
	item.ModifyTime = time.Now().Local()
	if e = item.Update([]string{"EnPermissionName", "ParentId", "Sort", "ModifyTime"}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新品种权限失败, Err: " + e.Error()
		return
	}

	// 若二级分类转为一级分类, 则清空对应客户、分类权限
	if originPid > 0 && req.ParentId == 0 {
		if e = models.ClearEnPermissionsByPermissionId(item.EnPermissionId); e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "清空英文分类权限失败, Err: " + e.Error()
			return
		}
	}

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

// ParentList
// @Title 父级品种列表
// @Description 父级品种列表
// @Success 200 Ret=200 操作成功
// @router /parent/list [get]
func (this *EnPermissionController) ParentList() {
	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
	}

	cond := fmt.Sprintf(` AND %s = ?`, models.EnPermissionColumns.ParentId)
	pars := make([]interface{}, 0)
	pars = append(pars, 0)
	ob := new(models.EnPermission)
	list, e := ob.GetItemsByCondition(cond, pars, []string{}, "sort ASC, create_time ASC")
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取父级品种列表失败, Err: " + e.Error()
		return
	}

	resp := make([]*models.EnPermissionItem, 0)
	for _, v := range list {
		t := new(models.EnPermissionItem)
		t.EnPermissionId = v.EnPermissionId
		t.EnPermissionName = v.EnPermissionName
		t.CnPermissionName = v.CnPermissionName
		t.ParentId = v.ParentId
		t.Sort = v.Sort
		t.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		t.Child = make([]*models.EnPermissionItem, 0)
		resp = append(resp, t)
	}

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

// List
// @Title 品种列表
// @Description 品种列表
// @Param   Keyword  query  string  false  "关键词"
// @Param   ReportId  query  int  false  "报告ID-用于邮件推送时过滤掉无权限的品种"
// @Param   VideoId  query  int  false  "路演视频ID-用于邮件推送时过滤掉无权限的品种"
// @Success 200 Ret=200 操作成功
// @router /list [get]
func (this *EnPermissionController) 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
	}
	keyword := this.GetString("Keyword", "")
	keyword = strings.TrimSpace(keyword)

	// 禁用指定报告、指定路演无权限的品种
	reportId, _ := this.GetInt("ReportId", 0)
	videoId, _ := this.GetInt("VideoId", 0)
	limitIds := make([]int, 0)
	if reportId > 0 {
		ps, e := models.GetEnPermissionIdsByEnglishReportId(reportId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取报告权限品种失败, Err: " + e.Error()
			return
		}
		limitIds = ps
	}
	if videoId > 0 {
		ps, e := models.GetEnPermissionIdsByEnglishVideoId(videoId)
		if e != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取视频权限品种失败, Err: " + e.Error()
			return
		}
		limitIds = ps
	}

	cond := ``
	pars := make([]interface{}, 0)
	if keyword != "" {
		k := fmt.Sprint("%", keyword, "%")
		cond += fmt.Sprintf(` AND %s LIKE ?`, models.EnPermissionColumns.EnPermissionName)
		pars = append(pars, k)
	}
	list, e := models.GetEnPermissionUnionList(cond, pars)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取品种Union列表失败, Err: " + e.Error()
		return
	}

	// 品种树
	resp := make([]*models.EnPermissionItem, 0)
	childMap := make(map[int][]*models.EnPermissionItem)
	for _, v := range list {
		t := new(models.EnPermissionItem)
		t.EnPermissionId = v.EnPermissionId
		t.EnPermissionName = v.EnPermissionName
		t.CnPermissionName = v.CnPermissionName
		t.ParentId = v.ParentId
		t.Sort = v.Sort
		t.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		t.Child = make([]*models.EnPermissionItem, 0)
		if v.ParentId == 0 {
			resp = append(resp, t)
			continue
		}
		if v.ParentId > 0 {
			if childMap[v.ParentId] == nil {
				childMap[v.ParentId] = make([]*models.EnPermissionItem, 0)
			}
			// 无权限则隐藏
			if (reportId > 0 || videoId > 0) && !utils.InArrayByInt(limitIds, t.EnPermissionId) {
				continue
			}
			childMap[v.ParentId] = append(childMap[v.ParentId], t)
		}
	}
	for _, r := range resp {
		r.Child = childMap[r.EnPermissionId]
	}

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

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

	ob := new(models.EnPermission)
	item, e := ob.GetItemById(req.EnPermissionId)
	if e != nil {
		if e.Error() == utils.ErrNoRow() {
			br.Msg = "品种不存在, 请刷新页面"
			return
		}
		br.Msg = "操作失败"
		br.ErrMsg = "获取品种权限失败, Err: " + e.Error()
		return
	}

	// 校验是否有子品种
	childCond := fmt.Sprintf(` AND %s = ?`, models.EnPermissionColumns.ParentId)
	childPars := make([]interface{}, 0)
	childPars = append(childPars, req.EnPermissionId)
	num, e := ob.GetCountByCondition(childCond, childPars)
	if e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取品种子权限数量失败, Err: " + e.Error()
		return
	}
	if num > 0 {
		br.Msg = "请先删除该品种下关联品种"
		return
	}

	// 校验是否关联客户
	{
		cond := fmt.Sprintf(` AND %s = ?`, models.EnCompanyPermissionColumns.EnPermissionId)
		pars := make([]interface{}, 0)
		pars = append(pars, item.EnPermissionId)
		ob := new(models.EnCompanyPermission)
		num, e := ob.GetCountByCondition(cond, pars)
		if e != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "获取品种关联客户数量失败, Err: " + e.Error()
			return
		}
		if num > 0 {
			br.Msg = "该品种有关联客户, 不允许删除"
			return
		}
	}

	// 删除品种
	if e = item.Del(); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "删除品种失败, Err: " + e.Error()
		return
	}

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