package data_manage

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/data_manage"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services/data"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// 手工数据管理
type ManualController struct {
	controllers.BaseAuthController
}

// @Title 手工数据权限用户搜索
// @Description 手工数据权限用户搜索
// @Param   KeyWord   query   string  false       "关键词搜索"
// @Success 200 {object} data_manage.ManualSysUser
// @router /manual/sysuser/search [get]
func (this *ManualController) ManualSysUserSearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.Ret = 408
		return
	}
	keyWord := this.GetString("KeyWord")
	list, err := data.GetManualSysUser(keyWord)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 获取手工数据权限用户
// @Description 获取手工数据权限用户
// @Success 200 {object} data_manage.ManualUserList
// @router /manual/sysuser/all [get]
func (this *ManualController) ManualSysUserAll() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.Ret = 408
		return
	}
	fmt.Println("start")
	list, err := data_manage.GetManualUserList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	fmt.Println("end")
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 获取所有手工数据分类
// @Description 获取所有手工数据分类
// @Param   AdminId   query   int  false       "初始化,AdminId 传0，如果对应具体用户，传对应的id"
// @Success 200 {object} data_manage.ManualClassifyList
// @router /manual/classify/all [get]
func (this *ManualController) ClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.Ret = 408
		return
	}
	adminId, _ := this.GetInt("AdminId")
	list, err := data_manage.GetManualClassifyAll(adminId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

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

// @Title 保存手工数据权限-用户对应分类
// @Description 保存手工数据权限-用户对应分类
// @Param	request	body data_manage.ManualSysUserClassifySaveReq true "type json string"
// @Success Ret=200 保存成功
// @router /manual/sysuser/classify/save [post]
func (this *ManualController) ManualSysUserClassifySave() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.Ret = 408
		return
	}

	var req data_manage.ManualSysUserClassifySaveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.AdminId <= 0 {
		br.Msg = "参数错误！"
		return
	}
	sysUserItem, err := system.GetSysUserById(req.AdminId)
	if err != nil {
		br.Msg = "获取用户信息失败！"
		br.ErrMsg = "获取用户信息失败，Err:" + err.Error()
		return
	}

	err = data_manage.DeleteManualUserClassifyCount(req.AdminId)
	if err != nil {
		br.Msg = "保存失败！"
		br.ErrMsg = "删除用户分类信息失败，Err:" + err.Error()
		return
	}
	list := make([]*data_manage.ManualUserClassify, 0)
	for _, v := range req.ClassifyId {
		item := new(data_manage.ManualUserClassify)
		item.AdminId = req.AdminId
		item.ClassifyId = v
		item.CreateTime = time.Now()
		list = append(list, item)
	}
	if len(list) > 0 {
		err = data_manage.AddManualUserClassifyMulti(list)
		if err != nil {
			br.Msg = "保存失败！"
			br.ErrMsg = "保存失败，Err:" + err.Error()
			return
		}
	}
	count, err := data_manage.GetManualUserCount(req.AdminId)
	if err != nil {
		br.Msg = "保存失败！"
		br.ErrMsg = "判断用户是否存在失败，Err:" + err.Error()
		return
	}
	if count <= 0 {
		manualUser := new(data_manage.ManualUser)
		manualUser.AdminId = req.AdminId
		manualUser.CreateTime = time.Now()
		manualUser.SysUserId = sysUser.AdminId
		manualUser.AdminRealName = sysUserItem.RealName
		manualUser.SysUserRealName = sysUser.RealName
		err = data_manage.AddManualUser(manualUser)
		if err != nil {
			br.Msg = "保存失败！"
			br.ErrMsg = "保存用户信息失败，Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}

// AddManualClassify
// @Title 新增手工指标分类
// @Description 新增手工指标分类接口
// @Param	request	body data_manage.AddManualClassifyReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /manual/classify/add [post]
func (this *ChartClassifyController) AddManualClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req data_manage.AddManualClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}
	if req.ParentId < 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	classifyItem, err := data_manage.GetManualClassifyByClassifyName(req.ClassifyName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "判断名称是否已存在失败"
		br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
		return
	}
	if classifyItem != nil {
		if classifyItem.IsShow == 1 {
			br.Msg = "分类名称已存在，请重新输入"
			br.IsSendEmail = false
			return
		} else {
			err = data_manage.ModifyManualClassifyIsShow(1, classifyItem.ClassifyId, req.ParentId)
			if err != nil {
				br.Msg = "保存失败"
				br.ErrMsg = "保存失败，Err:" + err.Error()
				br.IsSendEmail = false
				return
			}
			parentItem, _ := data_manage.GetManualClassifyById(req.ParentId)
			if parentItem != nil && parentItem.IsShow == 0 {
				err = data_manage.ModifyManualClassifyIsShow(1, parentItem.ClassifyId, req.ParentId)
				if err != nil {
					br.Msg = "保存失败"
					br.ErrMsg = "保存失败，Err:" + err.Error()
					br.IsSendEmail = false
					return
				}
			}
			br.Msg = "保存成功"
			br.Success = true
			br.Ret = 200
			return
		}
	}

	classify := new(data_manage.EdbdataClassify)
	classify.IsShow = 1
	classify.ClassifyName = req.ClassifyName
	classify.ParentId = req.ParentId
	classify.CreateTime = time.Now()
	classify.Sort = 0
	_, err = data_manage.AddEdbdataClassify(classify)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		br.IsSendEmail = false
		return
	}
	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
}

// ManualClassifyEdit
// @Title 修改手工指标分类
// @Description 修改手工指标分类接口
// @Param	request	body data_manage.EditManualClassifyReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /manual/classify/edit [post]
func (this *ChartClassifyController) ManualClassifyEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req data_manage.EditManualClassifyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ClassifyName == "" {
		br.Msg = "请输入分类名称"
		br.IsSendEmail = false
		return
	}

	if req.ClassifyId <= 0 {
		br.Msg = "参数错误"
		br.IsSendEmail = false
		return
	}

	item, err := data_manage.GetManualClassifyById(req.ClassifyId)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "获取分类失败，Err:" + err.Error()
		return
	}
	classifyItem, err := data_manage.GetManualClassifyByClassifyName(req.ClassifyName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "修改失败"
		br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
		return
	}

	if classifyItem != nil {
		if item.ClassifyId != classifyItem.ClassifyId {
			br.Msg = "名称已存在,请重新输入"
			return
		}
	}

	err = data_manage.ModifyManualClassifyName(req.ClassifyName, req.ClassifyId, req.ParentId)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "修改成功"
	br.Success = true
}

// ManualClassifyDel
// @Title 删除手工指标分类
// @Description 删除手工指标分类接口
// @Param	request	body data_manage.DelManualClassifyReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /manual/classify/delete [post]
func (this *ChartClassifyController) ManualClassifyDel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req data_manage.DelManualClassifyReq
	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 = "请选择分类"
		br.IsSendEmail = false
		return
	}
	classifyItem, err := data_manage.GetManualClassifyById(req.ClassifyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "查找分类失败"
		br.ErrMsg = "查找分类失败，Err:" + err.Error()
		return
	}
	if classifyItem.IsShow == 0 {
		br.Msg = "该分类已删除"
		br.IsSendEmail = false
		return
	}

	// 获取当前分类下是否存在子分类
	count, err := data_manage.GetChildManualClassifyCount(req.ClassifyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "删除失败"
		br.ErrMsg = "根据分类id获取下面存在的子分类数量失败，Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "该分类下包含子分类，不允许删除!"
		br.IsSendEmail = false
		return
	}

	if classifyItem.ParentId > 0 {
		// 获取当前分类下的指标数
		count, err = data_manage.GetManualEdbInfoCountByClassifyId(req.ClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "删除失败"
			br.ErrMsg = "根据分类id获取下面存在的指标数量失败，Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "该分类下包含指标，不允许删除!"
			br.IsSendEmail = false
			return
		}
	}

	// 修改是否展示
	err = data_manage.ModifyManualClassifyIsShow(0, classifyItem.ClassifyId, classifyItem.ParentId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
}

// @Title 获取用户设置的所有分类
// @Description 获取用户设置的所有分类(手工数据录入页面)
// @Success 200 {object} data_manage.EdbdataClassify
// @router /manual/set_classify/all [get]
func (this *ManualController) ManualSetClassifyAll() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.Ret = 408
		return
	}
	adminId := sysUser.AdminId
	setList, err := data_manage.GetManualUserSetClassify(adminId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	listLen := len(setList)
	classifyArr := make([]string, 0)
	for i := 0; i < listLen; i++ {
		classifyArr = append(classifyArr, strconv.Itoa(setList[i].ClassifyId))
	}
	classifyIdStr := strings.Join(classifyArr, ",")
	condition := ""
	items := make([]*data_manage.EdbdataClassifyList, 0)
	if classifyIdStr != "" {
		condition += ` AND classify_id IN(` + classifyIdStr + `)`
		condition += ` AND parent_id<>0 `
		items, err = data_manage.GetManualClassifyAllByCondition(condition)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,Err:" + err.Error()
			return
		}
	}

	classifyEdbTotalList, _ := data_manage.GetManualClassifyEdbInfoCount()
	edbTotalMap := make(map[int]int)
	for _, v := range classifyEdbTotalList {
		edbTotalMap[v.ClassifyId] = v.Total
	}
	itemsLen := len(items)
	for i := 0; i < itemsLen; i++ {
		items[i].Total = edbTotalMap[items[i].ClassifyId]
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = items
}

// FirstClassifyList
// @Title 获取所有手工数据的一级分类
// @Description 获取所有手工数据的一级分类
// @Success 200 {object} data_manage.ManualClassifyList
// @router /manual/classify/first [get]
func (this *ManualController) FirstClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.Ret = 408
		return
	}
	condition := " AND parent_id =0 "
	list, err := data_manage.GetManualClassifyAllByCondition(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

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

// AllClassifyList
// @Title 获取所有手工数据分类
// @Description 获取所有手工数据分类
// @Success 200 {object} data_manage.ManualClassifyList
// @router /manual/classify/all_list [get]
func (this *ManualController) AllClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.Ret = 408
		return
	}
	list, err := data_manage.GetManualClassifyAllV2()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}

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

//func init() {
//	fmt.Println("start")
//	adminId:=137
//	setList, err := data_manage.GetManualUserSetClassify(adminId)
//	if err != nil {
//		fmt.Println("err:", err)
//		return
//	}
//	listLen := len(setList)
//	classifyArr := make([]string, 0)
//	for i := 0; i < listLen; i++ {
//		classifyArr = append(classifyArr, strconv.Itoa(setList[i].ClassifyId))
//	}
//	classifyIdStr := strings.Join(classifyArr, ",")
//	condition := ""
//	if classifyIdStr != "" {
//		condition += ` AND classify_id IN(` + classifyIdStr + `)`
//	}
//	items, err := data_manage.GetManualClassifyAllByCondition(condition)
//	if err != nil {
//		fmt.Println("err:", err)
//		return
//	}
//	fmt.Println(items)
//	fmt.Println("end")
//}
