package material

import (
	"archive/zip"
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/material"
	materialService "eta/eta_mobile/services/material"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/http"
	"github.com/rdlucklib/rdluck_tools/paging"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

// MaterialController 逻辑导图
type MaterialController struct {
	controllers.BaseAuthController
}

// AddMaterialClassify
// @Title 新增素材库分类
// @Description 新增材库分类接口
// @Param	request	body data_manage.AddChartClassifyReq true "type json string"
// @Success 200 Ret=200 保存成功
// @router /classify/add [post]
func (this *MaterialController) AddMaterialClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req material.AddMaterialClassifyReq
	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
	}

	level := 1
	levelPath := ""
	if req.ParentId > 0 {
		//查找父级分类
		parentClassify, e := material.GetMaterialClassifyById(req.ParentId)
		if e != nil {
			br.Msg = "获取父级分类失败"
			br.ErrMsg = "获取父级分类失败，Err:" + e.Error()
			return
		}
		level = parentClassify.Level + 1
		levelPath = parentClassify.LevelPath
	}
	var count int
	switch this.Lang {
	case utils.LANG_EN:
		count, err = material.GetMaterialClassifyNameEnCount(req.ClassifyName, req.ParentId)
	default:
		count, err = material.GetMaterialClassifyNameCount(req.ClassifyName, req.ParentId)
	}

	if err != nil {
		br.Msg = "判断名称是否已存在失败"
		br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "分类名称已存在，请重新输入"
		br.IsSendEmail = false
		return
	}

	//获取该层级下最大的排序数
	classify := new(material.MaterialClassify)
	maxSort, _ := material.GetMaterialClassifyMaxSort(req.ParentId)
	classify.ParentId = req.ParentId
	classify.ClassifyName = req.ClassifyName
	classify.ClassifyNameEn = req.ClassifyName
	classify.CreateTime = time.Now()
	classify.ModifyTime = time.Now()
	classify.SysUserId = this.SysUser.AdminId
	classify.SysUserRealName = this.SysUser.RealName
	classify.Level = level
	classify.Sort = maxSort + 1
	classifyId, e := material.AddMaterialClassify(classify)
	if e != nil {
		br.Msg = "保存分类失败"
		br.ErrMsg = "保存分类失败,Err:" + e.Error()
		return
	}
	if req.ParentId > 0 {
		levelPath = fmt.Sprintf("%s,%d", levelPath, classifyId)
	} else {
		levelPath = fmt.Sprintf("%d", classifyId)
	}
	classify.ClassifyId = int(classifyId)
	classify.LevelPath = levelPath
	e = classify.Update([]string{"LevelPath"})
	if e != nil {
		br.Msg = "保存分类失败"
		br.ErrMsg = "保存分类失败,Err:" + e.Error()
		return
	}

	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
}

// EditMaterialClassify
// @Title 修改素材库分类
// @Description 修改素材库分类接口
// @Param	request	body data_manage.EditChartClassifyReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /classify/edit [post]
func (this *MaterialController) EditMaterialClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req material.EditMaterialClassifyReq
	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 := material.GetMaterialClassifyById(req.ClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			return
		}
		br.Msg = "保存失败"
		br.Msg = "获取分类信息失败,Err:" + err.Error()
		return
	}
	var count int
	updateStr := make([]string, 0)
	switch this.Lang {
	case utils.LANG_EN:
		count, err = material.GetMaterialClassifyNameEnNotSelfCount(req.ClassifyId, req.ClassifyName, item.ParentId)
		item.ClassifyNameEn = req.ClassifyName
		updateStr = append(updateStr, "ClassifyNameEn")
	default:
		count, err = material.GetMaterialClassifyNameNotSelfCount(req.ClassifyId, req.ClassifyName, item.ParentId)
		item.ClassifyName = req.ClassifyName
		updateStr = append(updateStr, "ClassifyName")
	}

	if err != nil {
		br.Msg = "判断名称是否已存在失败"
		br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
		return
	}
	if count > 0 {
		br.Msg = "分类名称已存在，请重新输入"
		br.IsSendEmail = false
		return
	}

	item.ModifyTime = time.Now()
	updateStr = append(updateStr, "ModifyTime")
	err = item.Update(updateStr)
	if err != nil {
		br.Msg = "保存分类失败"
		br.ErrMsg = "保存分类失败,Err:" + err.Error()
		return
	}
	//todo 测试更新子集的levelPath
	/*levelPath := ""
	oldLevelPath := item.LevelPath
	if item.ParentId > 0 {
		//查找父级分类
		parentClassify, e := material.GetMaterialClassifyById(item.ParentId)
		if e != nil {
			br.Msg = "获取父级分类失败"
			br.ErrMsg = "获取父级分类失败，Err:" + e.Error()
			return
		}
		levelPath = fmt.Sprintf("%s,%d", parentClassify.LevelPath, item.ClassifyId)
		tmpList, e := material.GetMaterialClassifyByLevelPath(oldLevelPath)
		if e != nil {
			br.Msg = "保存分类失败"
			br.ErrMsg = "保存分类失败,Err:" + e.Error()
			return
		}
		// 把原先的父级levePath，替换成最新的父级序列
		for _, tmp := range tmpList {
			tmp.LevelPath = strings.Replace(tmp.LevelPath, oldLevelPath, levelPath, -1)
			tmp.ModifyTime = time.Now()
			e = tmp.Update([]string{"LevelPath", "ModifyTime"})
			if e != nil {
				br.Msg = "保存分类失败"
				br.ErrMsg = "保存分类失败,Err:" + e.Error()
				return
			}
		}
	} else {
		// 只有更改了父级才需要更新levelPath
	}*/

	br.Ret = 200
	br.Msg = "保存成功"
	br.Success = true
	br.IsAddLog = true
}

// DeleteMaterialClassifyCheck
// @Title 删除素材库检测接口
// @Description 删除素材库检测接口
// @Param	request	body data_manage.ChartClassifyDeleteCheckResp true "type json string"
// @Success 200 Ret=200 检测成功
// @router /classify/del/check [post]
func (this *MaterialController) DeleteMaterialClassifyCheck() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req material.MaterialClassifyDeleteCheckReq
	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
	}
	var deleteStatus int
	var tipsMsg string
	//删除分类
	// 查询当前的分类
	classifyInfo, err := material.GetMaterialClassifyById(req.ClassifyId)
	if err != nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	classifyIds := strings.Split(classifyInfo.LevelPath, ",")
	if len(classifyIds) > 0 {
		//判断素材库分类下，是否含有素材库
		count, e := material.GetMaterialInfoCountByClassifyIds(classifyIds)
		if e != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "分类下是否含有指标失败，Err:" + e.Error()
			return
		}

		if count > 0 {
			deleteStatus = 1
			tipsMsg = "该分类下关联素材库不可删除"
		} else {
			if len(classifyIds) > 1 {
				deleteStatus = 2
				tipsMsg = "确认删除当前目录及包含的子目录吗"
			}
		}
	}

	if deleteStatus == 0 {
		tipsMsg = "可删除，进行删除操作"
	}

	resp := new(material.MaterialClassifyDeleteCheckResp)
	resp.DeleteStatus = deleteStatus
	resp.TipsMsg = tipsMsg
	br.Ret = 200
	br.Msg = "检测成功"
	br.Success = true
	br.Data = resp
}

// DeleteMaterialClassify
// @Title 删除素材库分类/素材库
// @Description 删除素材库分类/素材库接口
// @Param	request	body data_manage.DeleteChartClassifyReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /classify/del [post]
func (this *MaterialController) DeleteMaterialClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.DeleteMaterialClassifyReq
	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
	}

	// 查询当前的分类
	classifyInfo, err := material.GetMaterialClassifyById(req.ClassifyId)
	if err != nil {
		br.Msg = "分类不存在"
		br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
		return
	}
	classifyIds := strings.Split(classifyInfo.LevelPath, ",")
	if len(classifyIds) > 0 {
		//判断素材库分类下，是否含有素材库
		count, e := material.GetMaterialInfoCountByClassifyIds(classifyIds)
		if e != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "分类下是否含有指标失败，Err:" + e.Error()
			return
		}

		if count > 0 {
			br.Msg = "该目录下存在关联指标，不可删除"
			br.IsSendEmail = false
			return
		}

		err = material.DeleteMaterialClassify(classifyIds)
		if err != nil {
			br.Msg = "删除失败"
			br.ErrMsg = "删除失败,Err:" + err.Error()
			return
		}
	}

	//删除素材库
	/*if req.MaterialId > 0 {
		materialInfo, err := material.GetMaterialById(req.MaterialId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				br.Msg = "素材库已删除，请刷新页面"
				br.ErrMsg = "指标不存在,Err:" + err.Error()
				return
			} else {
				br.Msg = "删除失败"
				br.ErrMsg = "删除失败，获取指标信息失败，Err:" + err.Error()
				return
			}
		}
		if materialInfo == nil {
			br.Msg = "素材库已删除，请刷新页面"
			return
		}
		err = materialService.DeleteMaterial(req.MaterialId)
		if err != nil {
			br.Msg = err.Error()
			return
		}
	}*/
	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
	br.IsAddLog = true
}

// ClassifyMove
// @Title 素材库分类移动接口
// @Description 素材库分类移动接口
// @Success 200 {object} data_manage.MoveChartClassifyReq
// @router /classify/move [post]
func (this *MaterialController) ClassifyMove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.MoveMaterialClassifyReq
	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.ErrMsg = "分类id小于等于0"
		return
	}
	//判断分类是否存在
	materialClassifyInfo, err := material.GetMaterialClassifyById(req.ClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在，请刷新页面"
			br.ErrMsg = "分类不存在,Err:" + err.Error()
			return
		}
		br.Msg = "移动失败"
		br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
		return
	}
	if materialClassifyInfo.ParentId != req.ParentClassifyId {
		count, err := material.GetMaterialClassifyNameNotSelfCount(materialClassifyInfo.ClassifyId, materialClassifyInfo.ClassifyName, materialClassifyInfo.ParentId)
		if err != nil {
			br.Msg = "判断名称是否已存在失败"
			br.ErrMsg = "判断名称是否已存在失败，Err:" + err.Error()
			return
		}
		if count > 0 {
			br.Msg = "移动失败，分类名称已存在"
			br.IsSendEmail = false
			return
		}
	}
	err, errMsg := materialService.MoveMaterialClassify(materialClassifyInfo, &req)
	if err != nil {
		br.Msg = errMsg
		if errMsg == "" {
			br.Msg = "移动失败"
		}
		br.ErrMsg = err.Error()
	}

	// todo权限校验
	//移动的是分类
	//判断上级id是否一致，如果不一致的话，那么需要移动该分类层级
	/*updateCol := make([]string, 0)
	if MaterialClassifyInfo.ParentId != req.ParentClassifyId && req.ParentClassifyId != 0 {
		parentChartClassifyInfo, err := material.GetMaterialClassifyById(req.ParentClassifyId)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "获取上级分类信息失败,Err:" + err.Error()
			return
		}
		MaterialClassifyInfo.ParentId = parentChartClassifyInfo.ClassifyId
		MaterialClassifyInfo.Level = parentChartClassifyInfo.Level + 1
		MaterialClassifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "ParentId", "Level", "ModifyTime")
	} else if MaterialClassifyInfo.ParentId != req.ParentClassifyId && req.ParentClassifyId == 0 {
		//改为一级分类
		MaterialClassifyInfo.ParentId = req.ParentClassifyId
		MaterialClassifyInfo.Level = 1
		MaterialClassifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "ParentId", "Level", "ModifyTime")
	}

	//如果有传入 上一个兄弟节点分类id
	if req.PrevId > 0 {
		if req.PrevType == 1 {
			//上一个节点是分类
			//上一个兄弟节点
			prevClassify, err := material.GetMaterialClassifyById(req.PrevId)
			if err != nil {
				br.Msg = "移动失败"
				br.ErrMsg = "获取上一个兄弟节点分类信息失败,Err:" + err.Error()
				return
			}

			//如果是移动在两个兄弟节点之间
			if req.NextId > 0 {
				if req.NextType == 1 {
					//上一个节点是分类 下一个节点是分类的情况
					//下一个兄弟节点
					nextClassify, err := material.GetMaterialClassifyById(req.NextId)
					if err != nil {
						br.Msg = "移动失败"
						br.ErrMsg = "获取下一个兄弟节点分类信息失败,Err:" + err.Error()
						return
					}
					//如果上一个兄弟与下一个兄弟的排序权重是一致的，那么需要将下一个兄弟（以及下个兄弟的同样排序权重）的排序权重+2，自己变成上一个兄弟的排序权重+1
					if prevClassify.Sort == nextClassify.Sort || prevClassify.Sort == MaterialClassifyInfo.Sort {
						//变更兄弟节点的排序
						updateSortStr := `sort + 2`
						_ = material.UpdateMaterialClassifySortByParentId(prevClassify.ParentId, prevClassify.ClassifyId, prevClassify.Sort, updateSortStr)
						_ = material.UpdateMaterialSortByClassifyId(prevClassify.ClassifyId, prevClassify.Sort, 0, updateSortStr)
					} else {
						//如果下一个兄弟的排序权重正好是上个兄弟节点的下一层，那么需要再加一层了
						if nextClassify.Sort-prevClassify.Sort == 1 {
							//变更兄弟节点的排序
							updateSortStr := `sort + 1`
							_ = material.UpdateMaterialClassifySortByParentId(prevClassify.ParentId, 0, prevClassify.Sort, updateSortStr)
							_ = material.UpdateMaterialSortByClassifyId(prevClassify.ClassifyId, prevClassify.Sort, 0, updateSortStr)
						}
					}
				} else {
					//上一个节点是分类 下一个节点是素材库的情况
					//下一个兄弟节点
					nextChartInfo, err := material.GetMaterialById(req.NextId)
					if err != nil {
						br.Msg = "移动失败"
						br.ErrMsg = "获取下一个兄弟节点分类信息失败,Err:" + err.Error()
						return
					}
					//如果上一个兄弟(分类)与下一个兄弟(素材库)的排序权重是一致的，那么需要将下一个兄弟(素材库)（以及下个兄弟(素材库)的同样排序权重）的排序权重+2，自己变成上一个兄弟(分类)的排序权重+1
					if prevClassify.Sort == nextChartInfo.Sort || prevClassify.Sort == MaterialClassifyInfo.Sort {
						//变更兄弟节点的排序
						updateSortStr := `sort + 2`
						_ = material.UpdateMaterialClassifySortByParentId(prevClassify.ParentId, prevClassify.ClassifyId, prevClassify.Sort, updateSortStr)
						_ = material.UpdateMaterialSortByClassifyId(prevClassify.ClassifyId, prevClassify.Sort, 0, updateSortStr)
					} else {
						//如果下一个兄弟(素材库)的排序权重正好是上个兄弟节点(分类)的下一层，那么需要再加一层了
						if nextChartInfo.Sort-prevClassify.Sort == 1 {
							//变更兄弟节点的排序
							updateSortStr := `sort + 1`
							_ = material.UpdateMaterialClassifySortByParentId(prevClassify.ParentId, 0, prevClassify.ClassifyId, updateSortStr)
							_ = material.UpdateMaterialSortByClassifyId(prevClassify.ClassifyId, prevClassify.Sort, 0, updateSortStr)
						}
					}
				}

			}

			MaterialClassifyInfo.Sort = prevClassify.Sort + 1
			MaterialClassifyInfo.ModifyTime = time.Now()
			updateCol = append(updateCol, "Sort", "ModifyTime")

		} else {
			//上一个节点是素材库
			prevMaterial, err := material.GetMaterialById(req.PrevId)
			if err != nil {
				br.Msg = "移动失败"
				br.ErrMsg = "获取上一个兄弟节点分类信息失败,Err:" + err.Error()
				return
			}

			//如果是移动在两个兄弟节点之间
			if req.NextId > 0 {
				if req.NextType == 1 {
					//上一个节点是素材库 下一个节点是分类的情况
					//下一个兄弟节点
					nextClassify, err := material.GetMaterialClassifyById(req.NextId)
					if err != nil {
						br.Msg = "移动失败"
						br.ErrMsg = "获取下一个兄弟节点分类信息失败,Err:" + err.Error()
						return
					}
					//如果上一个兄弟(素材库)与下一个兄弟(分类)的排序权重是一致的，那么需要将下一个兄弟(分类)（以及下个兄弟(分类)的同样排序权重）的排序权重+2，自己变成上一个兄弟(素材库)的排序权重+1
					if prevMaterial.Sort == nextClassify.Sort || prevMaterial.Sort == MaterialClassifyInfo.Sort {
						//变更兄弟节点的排序
						updateSortStr := `sort + 2`
						_ = material.UpdateMaterialClassifySortByParentId(prevMaterial.ClassifyId, 0, prevMaterial.Sort, updateSortStr)
						_ = material.UpdateMaterialSortByClassifyId(prevMaterial.ClassifyId, prevMaterial.Sort, prevMaterial.MaterialId, updateSortStr)
					} else {
						//如果下一个兄弟(分类)的排序权重正好是上个兄弟(素材库)节点的下一层，那么需要再加一层了
						if nextClassify.Sort-prevMaterial.Sort == 1 {
							//变更兄弟节点的排序
							updateSortStr := `sort + 1`
							_ = material.UpdateMaterialClassifySortByParentId(prevMaterial.ClassifyId, 0, prevMaterial.Sort, updateSortStr)
							_ = material.UpdateMaterialSortByClassifyId(prevMaterial.ClassifyId, prevMaterial.Sort, prevMaterial.MaterialId, updateSortStr)
						}
					}
				} else {
					//上一个节点是素材库 下一个节点是素材库的情况
					//下一个兄弟节点
					nextChartInfo, err := material.GetMaterialById(req.NextId)
					if err != nil {
						br.Msg = "移动失败"
						br.ErrMsg = "获取下一个兄弟节点分类信息失败,Err:" + err.Error()
						return
					}
					//如果上一个兄弟(素材库)与下一个兄弟(分类)的排序权重是一致的，那么需要将下一个兄弟(分类)（以及下个兄弟(分类)的同样排序权重）的排序权重+2，自己变成上一个兄弟(素材库)的排序权重+1
					if prevMaterial.Sort == nextChartInfo.Sort || prevMaterial.Sort == MaterialClassifyInfo.Sort {
						//变更兄弟节点的排序
						updateSortStr := `sort + 2`
						_ = material.UpdateMaterialClassifySortByParentId(prevMaterial.ClassifyId, 0, prevMaterial.Sort, updateSortStr)
						_ = material.UpdateMaterialSortByClassifyId(prevMaterial.ClassifyId, prevMaterial.Sort, prevMaterial.MaterialId, updateSortStr)
					} else {
						//如果下一个兄弟(分类)的排序权重正好是上个兄弟(素材库)节点的下一层，那么需要再加一层了
						if nextChartInfo.Sort-prevMaterial.Sort == 1 {
							//变更兄弟节点的排序
							updateSortStr := `sort + 1`
							_ = material.UpdateMaterialClassifySortByParentId(prevMaterial.ClassifyId, 0, prevMaterial.Sort, updateSortStr)
							_ = material.UpdateMaterialSortByClassifyId(prevMaterial.ClassifyId, prevMaterial.Sort, prevMaterial.MaterialId, updateSortStr)
						}
					}
				}

			}
			MaterialClassifyInfo.Sort = prevMaterial.Sort + 1
			MaterialClassifyInfo.ModifyTime = time.Now()
			updateCol = append(updateCol, "Sort", "ModifyTime")

		}

	} else {
		firstClassify, err := material.GetFirstMaterialClassifyByParentId(MaterialClassifyInfo.ParentId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "移动失败"
			br.ErrMsg = "获取获取当前父级分类下的排序第一条的分类信息失败,Err:" + err.Error()
			return
		}

		//如果该分类下存在其他分类，且第一个其他分类的排序等于0，那么需要调整排序
		if firstClassify != nil && firstClassify.Sort == 0 {
			updateSortStr := ` sort + 1 `
			_ = material.UpdateMaterialClassifySortByParentId(firstClassify.ParentId, firstClassify.ClassifyId-1, 0, updateSortStr)
		}

		MaterialClassifyInfo.Sort = 0 //那就是排在第一位
		MaterialClassifyInfo.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")
	}

	//更新
	if len(updateCol) > 0 {
		err = MaterialClassifyInfo.Update(updateCol)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "修改失败,Err:" + err.Error()
			return
		}
		// todo 记录整个层级的分类ID
	}*/

	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
}

// List
// @Title 素材列表接口
// @Description 素材列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ClassifyId   query   int  true       "分类id"
// @Param   Keyword   query   string  true       "搜索关键词"
// @Param   IsShowMe   query   bool  true       "是否只看我的，true、false"
// @Success 200 {object} data_manage.ChartListResp
// @router /list [get]
func (this *MaterialController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	classifyId, _ := this.GetInt("ClassifyId")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyword := this.GetString("Keyword")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	classifyIds := make([]string, 0)
	childClassifyMap := make(map[int]*material.MaterialClassify)
	if classifyId > 0 {
		classifyIds = append(classifyIds, strconv.Itoa(classifyId))
		// 查询当前的分类
		classifyInfo, err := material.GetMaterialClassifyById(classifyId)
		if err != nil {
			br.Msg = "分类不存在"
			br.ErrMsg = "获取分类信息失败，Err:" + err.Error()
			return
		}
		// 获取所有子分类
		childList, e := material.GetMaterialClassifyByLevelPath(classifyInfo.LevelPath)
		if e != nil {
			err = fmt.Errorf("保存分类失败,Err:" + e.Error())
			return
		}
		// 把原先的父级levePath，替换成最新的父级序列
		classifyIdMap := make(map[string]struct{})
		for _, tmp := range childList {
			childClassifyMap[tmp.ClassifyId] = tmp
			//获取字符串前缀的位置
			after, _ := strings.CutPrefix(tmp.LevelPath, classifyInfo.LevelPath)
			fmt.Println("after", after)
			// 拼接字符串
			if after != "" {
				ids := strings.Split(after, ",")
				for _, v := range ids {
					if _, ok := classifyIdMap[v]; !ok {
						classifyIds = append(classifyIds, v)
						classifyIdMap[v] = struct{}{}
					}
				}
			}
		}
	}

	if len(classifyIds) > 0 {
		condition += " AND classify_id IN(" + utils.GetOrmInReplace(len(classifyIds)) + ") "
		pars = append(pars, classifyIds)
	}

	if keyword != "" {
		switch this.Lang {
		case utils.LANG_EN:
			condition += ` AND  ( material_name_en LIKE '%` + keyword + `%' )`
		default:
			condition += ` AND  ( material_name LIKE '%` + keyword + `%' )`
		}
	}

	//只看我的
	isShowMe, _ := this.GetBool("IsShowMe")
	if isShowMe {
		condition += ` AND sys_user_id = ? `
		pars = append(pars, sysUser.AdminId)
	}

	//获取图表信息
	list, err := material.GetMaterialListPageByCondition(condition, pars, startSize, pageSize)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Success = true
		br.Msg = "获取素材库信息失败"
		br.ErrMsg = "获取素材库信息失败,Err:" + err.Error()
		return
	}

	resp := new(material.MaterialListResp)
	if list == nil || len(list) <= 0 || (err != nil && err.Error() == utils.ErrNoRow()) {
		items := make([]*material.MaterialListItems, 0)
		resp.Paging = page
		resp.List = items
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}

	dataCount, err := material.GetMaterialListCountByCondition(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取指标数据总数失败,Err:" + err.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, dataCount)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// SaveAsMaterial
// @Title 将图表等封面上传至素材库
// @Description 将图表等封面上传至素材库
// @Param	request	body material.AddAndEditSandbox true "type json string"
// @Success 200 {object} material.Material
// @router /saveAs [post]
func (this *MaterialController) SaveAsMaterial() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.SaveAsMaterialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.MaterialName = strings.Trim(req.MaterialName, " ")
	if req.MaterialName == "" {
		br.Msg = "缺少素材库名称"
		return
	}
	var exist *material.Material
	switch this.Lang {
	case utils.LANG_EN:
		exist, err = material.GetMaterialByNameEn(req.MaterialName)
	default:
		// 判断名称是否重复
		exist, err = material.GetMaterialByName(req.MaterialName)
	}
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	if err == nil && exist.MaterialId > 0 {
		br.Msg = "图片名称已存在"
		return
	}
	err, errMsg := materialService.AddToMaterial(req, sysUser.AdminId, sysUser.RealName)
	if err != nil {
		br.Msg = "保存失败！"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}

	msg := "保存成功"
	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// MyChartSaveAsMaterial
// @Title 将我的图表等封面上传至素材库
// @Description 将图表等封面上传至素材库
// @Param	request	body material.AddAndEditSandbox true "type json string"
// @Success 200 {object} material.Material
// @router /my_chart/saveAs [post]
func (this *MaterialController) MyChartSaveAsMaterial() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.MyChartSaveAsMaterialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	materialNames := make([]string, 0)
	namesMap := make(map[string]struct{})
	for _, v := range req.MaterialList {
		if v.ClassifyId <= 0 {
			br.Msg = "请选择分类"
			return
		}
		v.MaterialName = strings.Trim(v.MaterialName, " ")
		if v.MaterialName == "" {
			br.Msg = "请填写图片名称"
			return
		}
		if v.ChartInfoId <= 0 {
			br.Msg = "请选择图表"
			return
		}
		if v.MyChartId <= 0 {
			br.Msg = "请选择我的图表"
			return
		}
		if _, ok := namesMap[v.MaterialName]; ok {
			br.Msg = "图片名称不能重复"
			return
		}
		namesMap[v.MaterialName] = struct{}{}
		materialNames = append(materialNames, v.MaterialName)
	}
	if len(materialNames) == 0 {
		br.Msg = "请填写图片名称"
		return
	}
	existList := make([]*material.Material, 0)
	switch this.Lang {
	case utils.LANG_EN:
		existList, err = material.GetMaterialByNameEns(materialNames)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		if len(existList) > 0 {
			msg := "图片名称:"
			for _, v := range existList {
				msg += v.MaterialNameEn + " "
			}
			br.Msg = fmt.Sprintf("%s 已存在", msg)
			return
		}
	default:
		// 判断文件名是否已存在
		existList, err = material.GetMaterialByNames(materialNames)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		if len(existList) > 0 {
			msg := "图片名称:"
			for _, v := range existList {
				msg += v.MaterialName + " "
			}
			br.Msg = fmt.Sprintf("%s 已存在", msg)
			return
		}
	}
	if len(req.MaterialList) > 30 {
		br.Msg = "最多支持选择30个图表"
		return
	}

	err, errMsg := materialService.MyChartAddToMaterial(req, sysUser.AdminId, sysUser.RealName)
	if err != nil {
		br.Msg = "保存失败！"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}

	msg := "保存成功"
	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// Delete
// @Title 删除素材库
// @Description 删除素材库接口
// @Param	request	body material.DeleteSandbox true "type json string"
// @Success 200 标记成功
// @router /del [post]
func (this *MaterialController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.DeleteMaterial
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.MaterialId <= 0 {
		br.Msg = "缺少素材库编号"
		return
	}

	//删除素材库
	err = material.DeleteByMaterialIds([]int{req.MaterialId})
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败，Err:" + err.Error()
		return
	}

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

// BatchDelete
// @Title 批量删除素材库
// @Description 删除素材库接口
// @Param	request	body material.DeleteSandbox true "type json string"
// @Success 200 标记成功
// @router /batch/del [post]
func (this *MaterialController) BatchDelete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.BatchDeleteMaterialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	deleteMaterialIds := make([]int, 0)
	if req.IsSelectAll {
		classifyId := req.ClassifyId
		keyword := req.Keyword
		isShowMe := req.IsShowMe
		//获取图表信息
		list, e, msg := materialService.GetBatchSelectedMaterialList(classifyId, keyword, isShowMe, sysUser, this.Lang)
		if e != nil {
			br.Msg = "获取素材库信息失败"
			if msg != "" {
				br.Msg = msg
			}
			br.ErrMsg = "获取素材库信息失败,Err:" + e.Error()
			return
		}
		notSelectIds := make(map[int]struct{})
		if len(req.MaterialIds) >= 0 {
			for _, v := range req.MaterialIds {
				notSelectIds[v] = struct{}{}
			}
		}
		for _, v := range list {
			if _, ok := notSelectIds[v.MaterialId]; !ok {
				deleteMaterialIds = append(deleteMaterialIds, v.MaterialId)
			}
		}
	} else {
		deleteMaterialIds = req.MaterialIds
	}

	if len(deleteMaterialIds) <= 0 {
		br.Msg = "请选择删除的素材"
		return
	}

	//删除素材库
	err = material.DeleteByMaterialIds(deleteMaterialIds)
	if err != nil {
		br.Msg = err.Error()
		return
	}

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

// MaterialClassifyList
// @Title 获取所有素材库分类接口-不包含素材库
// @Description 获取所有素材库分类接口-不包含素材库
// @Param   IsShowMe   query   bool  true       "是否只看我的，true、false"
// @Success 200 {object} data_manage.ChartClassifyListResp
// @router /classify/list [get]
func (this *MaterialController) MaterialClassifyList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	resp := new(material.MaterialClassifyListResp)

	rootList, err := material.GetMaterialClassifyByParentId(0)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	classifyAll, err := material.GetMaterialClassifyAll()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	nodeAll := make([]*material.MaterialClassifyItems, 0)
	for k := range rootList {
		rootNode := rootList[k]
		materialService.MaterialClassifyItemsMakeTree(this.SysUser, classifyAll, rootNode)
		nodeAll = append(nodeAll, rootNode)
	}

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

// BatchAdd
// @Title 批量新增素材
// @Description 新增/编辑保存素材库接口
// @Param	request	body material.AddAndEditSandbox true "type json string"
// @Success 200 {object} material.Material
// @router /batch/add [post]
func (this *MaterialController) BatchAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.BatchAddMaterialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	classifyId := req.ClassifyId
	if classifyId <= 0 {
		br.Msg = "请选择分类"
		return
	}
	materialNames := make([]string, 0)
	namesMap := make(map[string]struct{})
	for _, v := range req.MaterialList {
		if v.MaterialName == "" {
			br.Msg = "请填写图片名称"
			return
		}
		if v.ImgUrl == "" {
			br.Msg = "请上传图片"
			return
		}
		if _, ok := namesMap[v.MaterialName]; ok {
			br.Msg = "图片名称不能重复"
			return
		}
		namesMap[v.MaterialName] = struct{}{}
		materialNames = append(materialNames, v.MaterialName)
	}
	if len(materialNames) == 0 {
		br.Msg = "请填写图片名称"
		return
	}
	existList := make([]*material.Material, 0)
	switch this.Lang {
	case utils.LANG_EN:
		existList, err = material.GetMaterialByNameEns(materialNames)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		if len(existList) > 0 {
			msg := "图片名称:"
			for _, v := range existList {
				msg += v.MaterialNameEn + " "
			}
			br.Msg = fmt.Sprintf("%s 已存在", msg)
			return
		}
	default:
		// 判断文件名是否已存在
		existList, err = material.GetMaterialByNames(materialNames)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		if len(existList) > 0 {
			msg := "图片名称:"
			for _, v := range existList {
				msg += v.MaterialName + " "
			}
			br.Msg = fmt.Sprintf("%s 已存在", msg)
			return
		}
	}
	err = materialService.BatchAddMaterial(req.MaterialList, classifyId, sysUser.AdminId, sysUser.AdminName)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "文件上传失败，Err:" + err.Error()
		return
	}
	msg := "添加成功"
	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// BatchChangeClassify
// @Title 批量更换分类
// @Description 批量更换分类
// @Param	request	body material.DeleteSandbox true "type json string"
// @Success 200 标记成功
// @router /batch/changeClassify [post]
func (this *MaterialController) BatchChangeClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.BatchChangeClassifyMaterialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.NewClassifyId <= 0 {
		br.Msg = "请选择新的分类"
		return
	}
	updateMaterialIds := make([]int, 0)
	if req.IsSelectAll {
		classifyId := req.ClassifyId
		keyword := req.Keyword
		isShowMe := req.IsShowMe
		//获取图表信息
		list, e, msg := materialService.GetBatchSelectedMaterialList(classifyId, keyword, isShowMe, sysUser, this.Lang)
		if e != nil {
			br.Msg = "获取素材库信息失败"
			if msg != "" {
				br.Msg = msg
			}
			br.ErrMsg = "获取素材库信息失败,Err:" + e.Error()
			return
		}
		notSelectIds := make(map[int]struct{})
		if len(req.MaterialIds) >= 0 {
			for _, v := range req.MaterialIds {
				notSelectIds[v] = struct{}{}
			}
		}
		for _, v := range list {
			if _, ok := notSelectIds[v.MaterialId]; !ok {
				updateMaterialIds = append(updateMaterialIds, v.MaterialId)
			}
		}
	} else {
		updateMaterialIds = req.MaterialIds
	}

	if len(updateMaterialIds) <= 0 {
		br.Msg = "请选择变更的素材"
		return
	}

	// 判断新分类是否存在
	_, err = material.GetMaterialClassifyById(req.NewClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
	}
	//更换分类素材库
	err = material.UpdateClassifyByMaterialIds(updateMaterialIds, req.NewClassifyId, time.Now())
	if err != nil {
		br.Msg = err.Error()
		return
	}

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

// ChangeClassify
// @Title 更换分类
// @Description 批量更换分类
// @Param	request	body material.DeleteSandbox true "type json string"
// @Success 200 标记成功
// @router /changeClassify [post]
func (this *MaterialController) ChangeClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.ChangeClassifyMaterialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.MaterialId <= 0 {
		br.Msg = "缺少素材库编号"
		return
	}
	if req.NewClassifyId <= 0 {
		br.Msg = "请选择新的分类"
		return
	}

	// 判断素材是否存在
	info, err := material.GetMaterialById(req.MaterialId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "素材不存在"
			return
		}
		br.Msg = "获取素材库信息失败"
		br.ErrMsg = "获取素材库信息失败,Err:" + err.Error()
		return
	}

	if req.NewClassifyId == info.ClassifyId {
		br.Msg = "请选择不同的分类"
		return
	}

	// 判断新分类是否存在
	_, err = material.GetMaterialClassifyById(req.NewClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "分类不存在"
			return
		}
		br.Msg = "获取分类信息失败"
		br.ErrMsg = "获取分类信息失败,Err:" + err.Error()
	}
	info.ClassifyId = req.NewClassifyId
	info.ModifyTime = time.Now()

	//更换分类素材库
	err = info.Update([]string{"ClassifyId", "ModifyTime"})
	if err != nil {
		br.Msg = err.Error()
		return
	}

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

// Rename
// @Title 素材重命名
// @Description 素材重命名
// @Param	request	body material.DeleteSandbox true "type json string"
// @Success 200 标记成功
// @router /rename [post]
func (this *MaterialController) Rename() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.RenameMaterialReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.MaterialId <= 0 {
		br.Msg = "缺少素材库编号"
		return
	}
	req.MaterialName = strings.Trim(req.MaterialName, " ")
	if req.MaterialName == "" {
		br.Msg = "缺少素材库名称"
		return
	}
	// 判断素材是否存在
	info, err := material.GetMaterialById(req.MaterialId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "素材不存在"
			return
		}
		br.Msg = "获取素材库信息失败"
		br.ErrMsg = "获取素材库信息失败,Err:" + err.Error()
		return
	}
	var exist *material.Material
	updateStr := make([]string, 0)
	switch this.Lang {
	case utils.LANG_EN:
		// 判断名称是否重复
		if info.MaterialNameEn == req.MaterialName {
			br.Msg = "名称未修改"
			return
		}
		exist, err = material.GetMaterialByNameEn(req.MaterialName)
		info.MaterialNameEn = req.MaterialName
		updateStr = append(updateStr, "MaterialNameEn")
	default:
		// 判断名称是否重复
		if info.MaterialName == req.MaterialName {
			br.Msg = "名称未修改"
			return
		}
		exist, err = material.GetMaterialByName(req.MaterialName)
		info.MaterialName = req.MaterialName
		updateStr = append(updateStr, "MaterialName")
	}
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	if err == nil && exist.MaterialId > 0 {
		br.Msg = "图片名称已存在"
		return
	}
	info.ModifyTime = time.Now()
	updateStr = append(updateStr, "ModifyTime")
	//更换分类素材库
	err = info.Update(updateStr)
	if err != nil {
		br.Msg = err.Error()
		return
	}

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

// BatchDownload
// @Title 批量下载素材
// @Description 批量下载素材
// @Param	request	body material.DeleteSandbox true "type json string"
// @Success 200 标记成功
// @router /batch/download [get]
func (this *MaterialController) BatchDownload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		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 material.BatchDeleteMaterialReq
	materialIdStr := this.GetString("MaterialIds")
	isSelectAll, _ := this.GetBool("IsSelectAll")
	classifyId, _ := this.GetInt("ClassifyId")
	keyword := this.GetString("Keyword")
	isShowMe, _ := this.GetBool("IsShowMe")

	downMaterialList := make([]*material.MaterialListItems, 0)
	materialIds := strings.Split(materialIdStr, ",")
	var err error
	if isSelectAll {
		//获取图表信息
		list, e, msg := materialService.GetBatchSelectedMaterialList(classifyId, keyword, isShowMe, sysUser, this.Lang)
		if e != nil {
			br.Msg = "获取素材库信息失败"
			if msg != "" {
				br.Msg = msg
			}
			br.ErrMsg = "获取素材库信息失败,Err:" + e.Error()
			return
		}
		notSelectIds := make(map[int]struct{})
		if len(materialIds) >= 0 {
			//转成数组
			for _, v := range materialIds {
				id, _ := strconv.Atoi(v)
				notSelectIds[id] = struct{}{}
			}
		}
		for _, v := range list {
			if _, ok := notSelectIds[v.MaterialId]; !ok {
				downMaterialList = append(downMaterialList, v)
			}
		}
	} else {
		if len(materialIds) > 0 {
			// 批量查询指标数据
			materialIdsInt := make([]int, 0)
			for _, v := range materialIds {
				id, _ := strconv.Atoi(v)
				materialIdsInt = append(materialIdsInt, id)
			}
			downMaterialList, err = material.GetMaterialByIds(materialIdsInt)
			if err != nil {
				br.Msg = "获取素材库信息失败"
				br.ErrMsg = "获取素材库信息失败,Err:" + err.Error()
				return
			}
		}
	}

	if len(downMaterialList) <= 0 {
		br.Msg = "请选择要下载的素材"
		return
	}
	// 创建zip
	zipName := time.Now().Format(utils.FormatDateTimeUnSpace) + utils.GetRandString(5) + ".zip"
	savePath := zipName
	zipFile, err := os.Create(zipName)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "生成压缩文件失败, Err: " + err.Error()
		return
	}
	zipWriter := zip.NewWriter(zipFile)
	// 生成zip过程中报错关闭
	defer func() {
		if err != nil {
			_ = zipWriter.Close()
			_ = zipFile.Close()
		}
		_ = os.Remove(savePath)
	}()

	// 获取资源, 写入zip
	zipFileName := ""
	for i := range downMaterialList {
		if downMaterialList[i].MaterialName == "" || downMaterialList[i].ImgUrl == "" {
			continue
		}
		fmt.Printf("开始压缩第%d个文件\n", i+1)
		dotIndex := strings.LastIndex(downMaterialList[i].ImgUrl, ".")

		// 如果找不到点，或者点是文件名的第一个字符（不合法情况），则返回空字符串
		if dotIndex == -1 || dotIndex == 0 {
			continue
		}

		fileExt := downMaterialList[i].ImgUrl[dotIndex+1:]
		ioWriter, err := zipWriter.Create(fmt.Sprintf("%s.%s", downMaterialList[i].MaterialName, fileExt))
		if err != nil {
			if os.IsPermission(err) {
				br.Msg = "操作失败"
				br.ErrMsg = "打包权限不足, Err: " + err.Error()
				return
			}
			br.Msg = "操作失败"
			br.ErrMsg = "压缩出错, Err: " + err.Error()
			return
		}

		var content []byte
		content, err = http.Get(downMaterialList[i].ImgUrl)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "资源获取失败, Err: " + err.Error()
			return
		}
		_, err = ioWriter.Write(content)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "压缩文件写入失败, Err: " + err.Error()
			return
		}
		if zipFileName == "" {
			zipFileName = downMaterialList[i].MaterialName
		}
		fmt.Printf("第%d个文件写入成功\n", i+1)
	}
	// 生成zip后关闭,否则下载文件会损坏
	_ = zipWriter.Close()
	_ = zipFile.Close()

	this.Ctx.Output.Download(savePath, fmt.Sprintf("%s.zip", zipFileName))

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

// Download
// @Title 下载素材
// @Description 下载素材
// @Param	request	body material.DeleteSandbox true "type json string"
// @Success 200 标记成功
// @router /download [get]
func (this *MaterialController) Download() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	materialId, _ := this.GetInt("MaterialId")
	if materialId <= 0 {
		br.Msg = "缺少素材库编号"
		return
	}
	// 判断素材是否存在
	info, err := material.GetMaterialById(materialId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "素材不存在"
			return
		}
		br.Msg = "获取素材库信息失败"
		br.ErrMsg = "获取素材库信息失败,Err:" + err.Error()
		return
	}
	if info.ImgUrl == "" {
		br.Msg = "素材地址为空"
		return
	}

	fileName := info.MaterialName
	// 查找文件名中最后一个点的位置
	dotIndex := strings.LastIndex(info.ImgUrl, ".")

	// 如果找不到点，或者点是文件名的第一个字符（不合法情况），则返回空字符串
	if dotIndex == -1 || dotIndex == 0 {
		br.Msg = "素材地址错误"
		return
	}

	fileName += "." + info.ImgUrl[dotIndex+1:] // 添加扩展名到文件名
	// 获取路径中的文件名
	urlFileName := path.Base(info.ImgUrl)
	uploadDir := utils.STATIC_DIR + "hongze/" + time.Now().Format("20060102")
	if e := os.MkdirAll(uploadDir, utils.DIR_MOD); e != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败, Err:" + e.Error()
		return
	}
	var content []byte
	content, err = http.Get(info.ImgUrl)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "资源获取失败, Err: " + err.Error()
		return
	}
	filePath := uploadDir + "/" + urlFileName
	ioWriter, err := os.Create(filePath)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "文件创建失败, Err: " + err.Error()
		return
	}
	n, err := ioWriter.Write(content)
	fmt.Println("n", n)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "压缩文件写入失败, Err: " + err.Error()
		return
	}
	this.Ctx.Output.Download(filePath, fileName)

	defer func() {
		_ = os.Remove(filePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "success"
}
