package knowledge import ( "encoding/json" "eta_gn/eta_api/controllers" "eta_gn/eta_api/models" "eta_gn/eta_api/models/knowledge" "eta_gn/eta_api/services" knowledgeServ "eta_gn/eta_api/services/knowledge" "eta_gn/eta_api/utils" "fmt" "github.com/h2non/filetype" "github.com/rdlucklib/rdluck_tools/paging" "github.com/tealeg/xlsx" "html" "io/ioutil" "os" "path" "strconv" "strings" "time" ) type ResourceController struct { controllers.BaseAuthController } // @router /resource/list [get] func (this *ResourceController) List() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() pageSize, _ := this.GetInt("PageSize") currentIndex, _ := this.GetInt("CurrentIndex") classifyIds := this.GetString("ClassifyIds") addUserIds, _ := this.GetInt("SysUserIds") tagIds := this.GetString("TagIds") keyWord := this.GetString("Keyword") resourceType, _ := this.GetInt("ResourceType") sourceFrom := this.GetString("SourceFrom") var startSize int if pageSize <= 0 { pageSize = utils.PageSize20 } if currentIndex <= 0 { currentIndex = 1 } startSize = utils.StartIndex(currentIndex, pageSize) var condition string var pars []interface{} condition += ` AND resource_type = ? ` pars = append(pars, resourceType) if keyWord != "" { keyWordArr := strings.Split(keyWord, " ") lengthKey := len(keyWordArr) if lengthKey == 1 { condition += ` AND (title LIKE ?) ` pars = utils.GetLikeKeywordPars(pars, keyWord, 1) } else if lengthKey > 1 { for k, v := range keyWordArr { if k == 0 { condition += ` AND (title LIKE ? ` pars = utils.GetLikeKeywordPars(pars, v, 1) } else if k == lengthKey-1 { condition += ` OR title LIKE ? ) ` pars = utils.GetLikeKeywordPars(pars, v, 1) } else { condition += ` OR title LIKE ? ` pars = utils.GetLikeKeywordPars(pars, v, 1) } } } } if sourceFrom != "" { sourceArr := strings.Split(sourceFrom, ",") condition += ` AND source_from in (?) ` pars = append(pars, sourceArr) } if classifyIds != "" { classifyIdsArr := strings.Split(classifyIds, ",") var classifyIdsInt []int for _, v := range classifyIdsArr { classifyId, _ := strconv.Atoi(v) classifyIdsInt = append(classifyIdsInt, classifyId) } condition += ` AND classify_id in (?) ` pars = append(pars, classifyIdsInt) } if addUserIds > 0 { addUserIdsArr := strings.Split(strconv.Itoa(addUserIds), ",") var addUserIdsInt []int for _, v := range addUserIdsArr { addUserId, _ := strconv.Atoi(v) addUserIdsInt = append(addUserIdsInt, addUserId) } condition += ` AND admin_id in (?) ` pars = append(pars, addUserIdsInt) } if tagIds != "" { tagIdsArr := strings.Split(tagIds, ",") var tagIdsInt []int for _, v := range tagIdsArr { tagId, _ := strconv.Atoi(v) tagIdsInt = append(tagIdsInt, tagId) } condition += ` AND tag_id in (?) ` pars = append(pars, tagIdsInt) } var err error var total int var list []*knowledge.KnowledgeResourceList total, err = knowledge.GetKnowledgeResourceListCount(condition, pars) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } listTmp, err := knowledge.GetKnowledgeResourcePageList(condition, pars, startSize, pageSize) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } classifyFullNameMap := make(map[int]string) classifyIdsArr := make([]int, 0) for _, v := range listTmp { classifyIdsArr = append(classifyIdsArr, v.ClassifyId) } classifyList, err := knowledge.GetFullClassifyListByIdList(classifyIdsArr, resourceType) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } for _, v := range classifyList { name := v.ClassifyName if v.ParentName != "" { name = v.ParentName + "/" + name } if v.RootName != "" { name = v.RootName + "/" + name } classifyFullNameMap[v.ClassifyId] = name } tagNameMap := make(map[int]string) tagIdsArr := make([]int, 0) for _, v := range listTmp { tagIdsArr = append(tagIdsArr, v.TagId) } tagObj := new(knowledge.KnowledgeTag) tagList, err := tagObj.GetListByIdList(tagIdsArr, resourceType) if err != nil { br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() } for _, v := range tagList { tagNameMap[v.TagId] = v.TagName } for _, v := range listTmp { var startTime, endTime string if v.StartTime != nil && !v.StartTime.IsZero() { startTime = v.StartTime.In(time.Local).Format(utils.FormatDateTime) if resourceType == knowledge.KnowledgeResourceTypeOpinion || resourceType == knowledge.KnowledgeResourceTypeKnow { startTime = v.StartTime.In(time.Local).Format(utils.FormatDate) } } if v.EndTime != nil && !v.EndTime.IsZero() { endTime = v.EndTime.In(time.Local).Format(utils.FormatDateTime) if resourceType == knowledge.KnowledgeResourceTypeOpinion || resourceType == knowledge.KnowledgeResourceTypeKnow { endTime = v.EndTime.In(time.Local).Format(utils.FormatDate) } } modifyTime := v.ModifyTime.In(time.Local).Format(utils.FormatDateTime) createTime := v.CreateTime.In(time.Local).Format(utils.FormatDateTime) tmp := &knowledge.KnowledgeResourceList{ KnowledgeResourceId: v.KnowledgeResourceId, ResourceType: v.ResourceType, ClassifyId: v.ClassifyId, Title: v.Title, CreateTime: createTime, ModifyTime: modifyTime, State: v.State, ResourceCode: v.ResourceCode, AdminId: v.AdminId, AdminRealName: v.AdminRealName, SourceFrom: v.SourceFrom, TagId: v.TagId, StartTime: startTime, EndTime: endTime, } classifyName, ok := classifyFullNameMap[tmp.ClassifyId] if ok { tmp.ClassifyFullName = classifyName } tagName, ok := tagNameMap[v.TagId] if ok { tmp.TagName = tagName } list = append(list, tmp) } page := paging.GetPaging(currentIndex, pageSize, total) resp := new(knowledge.KnowledgeResourceListResp) resp.Paging = page resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /resource/add [post] func (this *ResourceController) Add() { 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 knowledge.AddReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.Title == `` { br.Msg = "标题不能为空" br.ErrMsg = "标题不能为空" br.IsSendEmail = false return } if len(req.Title) > 600 { br.Msg = "标题过长" return } if req.ClassifyId <= 0 { br.Msg = "分类必填" br.ErrMsg = "分类必填" br.IsSendEmail = false return } if req.ResourceType == knowledge.KnowledgeResourceTypeEvent || req.ResourceType == knowledge.KnowledgeResourceTypePolicy { if req.StartTime == "" { br.Msg = "开始时间必填" br.ErrMsg = "开始时间必填" return } } item, err, errMsg := knowledgeServ.AddResource(&req, sysUser) if err != nil { br.Msg = "保存失败" if errMsg != "" { br.Msg = errMsg } br.ErrMsg = "保存失败,Err:" + err.Error() return } resp := new(knowledge.AddResp) resp.KnowledgeResourceId = item.KnowledgeResourceId resp.ResourceCode = item.ResourceCode br.Ret = 200 br.Success = true br.Msg = "保存成功" br.Data = resp } // @router /resource/edit [post] func (this *ResourceController) Edit() { 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 knowledge.EditReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.KnowledgeResourceId <= 0 { br.Msg = "请选择事件" br.ErrMsg = "请选择事件" return } if req.Title == `` { br.Msg = "标题不能为空" br.ErrMsg = "标题不能为空" br.IsSendEmail = false return } if len(req.Title) > 600 { br.Msg = "标题过长" return } if req.ClassifyId <= 0 { br.Msg = "分类必填" br.ErrMsg = "分类必填" br.IsSendEmail = false return } if req.ResourceType == knowledge.KnowledgeResourceTypeEvent || req.ResourceType == knowledge.KnowledgeResourceTypePolicy { if req.StartTime == "" { br.Msg = "开始时间必填" br.ErrMsg = "开始时间必填" return } } resourceObj := new(knowledge.KnowledgeResource) resourceInfo, e := resourceObj.GetById(int(req.KnowledgeResourceId)) if e != nil { if utils.IsErrNoRow(e) { br.Msg = "事件已被删除, 请刷新页面" return } br.Msg = "操作失败" br.ErrMsg = "获取事件失败, Err: " + e.Error() return } if resourceInfo.ResourceType != req.ResourceType { br.Msg = "事件类型错误" return } err, errMsg := knowledgeServ.EditResource(resourceInfo, req, sysUser) if err != nil { br.Msg = "保存失败" if errMsg != "" { br.Msg = errMsg } br.ErrMsg = "保存失败,Err:" + err.Error() return } resp := new(knowledge.EditResp) resp.KnowledgeResourceId = req.KnowledgeResourceId resp.ResourceCode = resourceInfo.ResourceCode br.Ret = 200 br.Success = true br.Msg = "保存成功" br.Data = resp } // @router /resource/detail [get] func (this *ResourceController) Detail() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() knowledgeResourceId, err := this.GetInt("KnowledgeResourceId") if err != nil { br.Msg = "获取参数失败!" br.ErrMsg = "获取参数失败,Err:" + err.Error() return } if knowledgeResourceId <= 0 { br.Msg = "参数错误" return } resourceType, _ := this.GetInt("ResourceType") resourceObj := new(knowledge.KnowledgeResource) item, err := resourceObj.GetById(knowledgeResourceId) if err != nil { if utils.IsErrNoRow(err) { br.Msg = "事件已被删除" return } br.Msg = "获取失败" br.ErrMsg = "获取失败,Err:" + err.Error() return } if item.ResourceType != resourceType { br.Msg = "事件类型错误" return } item.Content = html.UnescapeString(item.Content) resp := &knowledge.KnowledgeResourceDetailView{ KnowledgeResource: item, } br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /resource/saveContent [post] func (this *ResourceController) SaveReportContent() { br := new(models.BaseResponse).Init() br.IsSendEmail = false 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 knowledge.SaveReportContent err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } knowledgeResourceId := req.KnowledgeResourceId if knowledgeResourceId <= 0 { resp := new(knowledge.SaveReportContentResp) resp.KnowledgeResourceId = knowledgeResourceId br.Ret = 200 br.Success = true br.Msg = "保存成功" br.Data = resp return } resp := new(knowledge.SaveReportContentResp) resp.KnowledgeResourceId = knowledgeResourceId br.Ret = 200 br.Success = true br.Msg = "保存成功" br.Data = resp } // @router /resource/detail/base [get] func (this *ResourceController) BaseDetail() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() } // @router /resource/delete [post] func (this *ResourceController) Delete() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() var req knowledge.DeleteReq err := json.Unmarshal(this.Ctx.Input.RequestBody, &req) if err != nil { br.Msg = "参数解析异常!" br.ErrMsg = "参数解析失败,Err:" + err.Error() return } if req.KnowledgeResourceId <= 0 { br.Msg = "参数错误" br.ErrMsg = "参数错误,事件id不可为空" return } resourceObj := new(knowledge.KnowledgeResource) item, err := resourceObj.GetById(req.KnowledgeResourceId) if err != nil { if utils.IsErrNoRow(err) { br.Msg = "事件不存在" br.ErrMsg = "事件不存在" return } } if item.ResourceType != req.ResourceType { br.Msg = "事件类型不匹配" return } if err = item.Delete(req.KnowledgeResourceId); err != nil { br.Msg = "删除失败" br.ErrMsg = "删除事件失败, Err: " + err.Error() return } br.Ret = 200 br.Success = true br.Msg = "删除成功" } // @router /resource/import_add [post] func (c *ResourceController) ImportData() { br := new(models.BaseResponse).Init() defer func() { c.Data["json"] = br c.ServeJSON() }() sysUser := c.SysUser if sysUser == nil { br.Msg = "请重新登录" return } resourceType, _ := c.GetInt("ResourceType") file, _, err := c.GetFile("EntryFile") if err != nil { br.Msg = "获取文件失败" br.ErrMsg = "获取文件失败,Err:" + err.Error() return } path := "./static/knowledge_import_" + strconv.Itoa(resourceType) + "_" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx" defer file.Close() err = c.SaveToFile("EntryFile", path) if err != nil { br.Msg = "文件保存失败" br.ErrMsg = "文件保存失败,Err:" + err.Error() return } defer os.Remove(path) successCount, failCount, err, errMsg := knowledgeServ.ImportResourceData(path, resourceType, sysUser) if err != nil { br.Msg = errMsg br.ErrMsg = err.Error() return } resp := models.EdbdataImportResp{ SuccessCount: successCount, FailCount: failCount, } if failCount > 0 { if successCount == 0 { resp.Status = -1 resp.Msg = "导入失败" } else { resp.Status = 1 resp.Msg = "存在部分导入失败" } } else { resp.Status = 0 } br.Msg = "导入成功" br.Ret = 200 br.Success = true br.Data = resp } // @router /resource/download_fail [get] func (this *ResourceController) ImportFailListDownload() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } resourceType, _ := this.GetInt("ResourceType") failObj := new(knowledge.KnowledgeImportFail) item, err := failObj.GetListBySysUserId(sysUser.AdminId, resourceType) if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } xlsxFile := xlsx.NewFile() SheetName := "导入失败数据" if this.Lang == utils.EnLangVersion { SheetName = "Import Fail List" } sheet, err := xlsxFile.AddSheet(SheetName) if err != nil { br.Msg = "获取sheet失败" br.Msg = "获取sheet失败,Err:" + err.Error() return } if resourceType == knowledge.KnowledgeResourceTypeEvent || resourceType == knowledge.KnowledgeResourceTypePolicy { headRow := sheet.AddRow() headRow.AddCell().SetValue("开始日期") headRow.AddCell().SetValue("开始时间") headRow.AddCell().SetValue("结束日期") headRow.AddCell().SetValue("结束时间") headRow.AddCell().SetValue("标题") headRow.AddCell().SetValue("正文") headRow.AddCell().SetValue("来源") headRow.AddCell().SetValue("一级分类") headRow.AddCell().SetValue("二级分类") headRow.AddCell().SetValue("三级分类") headRow.AddCell().SetValue("标签") headRow.AddCell().SetValue("备注") for _, v := range item { row := sheet.AddRow() row.AddCell().SetValue(v.StartDate) row.AddCell().SetValue(v.StartTime) row.AddCell().SetValue(v.EndDate) row.AddCell().SetValue(v.EndTime) row.AddCell().SetValue(v.Title) row.AddCell().SetValue(v.Content) row.AddCell().SetValue(v.SourceFrom) row.AddCell().SetValue(v.ClassifyFirst) row.AddCell().SetValue(v.ClassifySecond) row.AddCell().SetValue(v.ClassifyThird) row.AddCell().SetValue(v.Tag) row.AddCell().SetValue(v.Remark) } } else { headRow := sheet.AddRow() headRow.AddCell().SetValue("时间") headRow.AddCell().SetValue("标题") headRow.AddCell().SetValue("正文") headRow.AddCell().SetValue("来源") headRow.AddCell().SetValue("一级分类") headRow.AddCell().SetValue("二级分类") headRow.AddCell().SetValue("三级分类") headRow.AddCell().SetValue("标签") headRow.AddCell().SetValue("备注") for _, v := range item { row := sheet.AddRow() row.AddCell().SetValue(v.StartDate) row.AddCell().SetValue(v.Title) row.AddCell().SetValue(v.Content) row.AddCell().SetValue(v.SourceFrom) row.AddCell().SetValue(v.ClassifyFirst) row.AddCell().SetValue(v.ClassifySecond) row.AddCell().SetValue(v.ClassifyThird) row.AddCell().SetValue(v.Tag) row.AddCell().SetValue(v.Remark) } } fileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx" savePath := "./static/" + fileName err = xlsxFile.Save(savePath) if err != nil { br.Msg = "文件保存失败" br.ErrMsg = "文件保存失败,Err:" + err.Error() return } defer func() { os.Remove(savePath) }() finalFileName := "失败列表.xlsx" if this.Lang == utils.EnLangVersion { finalFileName = "Failure List.xlsx" } this.Ctx.Output.Download(savePath, finalFileName) } // @router /resource/upload [post] func (this *ResourceController) ResourceUpload() { 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 } f, h, e := this.GetFile("File") if e != nil { br.Msg = "获取资源信息失败" br.ErrMsg = "获取资源信息失败, Err:" + e.Error() return } defer func() { _ = f.Close() }() fileData, e := ioutil.ReadAll(f) if e != nil { br.Msg = "上传失败" br.ErrMsg = "读取文件失败, Err: " + e.Error() return } ext := path.Ext(h.Filename) kind, _ := filetype.Match(fileData) if ext != ".pdf" && ext != ".ppt" && ext != ".pptx" && ext != ".docx" && ext != ".doc" && kind.Extension != "pdf" && kind.Extension != "ppt" && kind.Extension != "pptx" && kind.Extension != "docx" && kind.Extension != "doc" { br.Msg = "文件格式有误" return } 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 } ossFileName := utils.GetRandStringNoSpecialChar(28) + ext filePath := uploadDir + "/" + ossFileName if e = this.SaveToFile("File", filePath); e != nil { br.Msg = "文件保存失败" br.ErrMsg = "文件保存失败, Err:" + e.Error() return } defer func() { _ = os.Remove(filePath) }() ossDir := utils.RESOURCE_DIR + "knowledge_resource/" resourceUrl := `` savePath := ossDir + time.Now().Format("200601/20060102/") + ossFileName ossClient := services.NewOssClient() if ossClient == nil { br.Msg = "上传失败" br.ErrMsg = "初始化OSS服务失败" return } resourceUrl, e = ossClient.UploadFile(ossFileName, filePath, savePath) if e != nil { br.Msg = "文件上传失败" br.ErrMsg = "文件上传失败,Err:" + e.Error() return } resourceItem := &knowledge.UpdateResourceResp{ FileUrl: resourceUrl, } br.Msg = "上传成功" br.Ret = 200 br.Success = true br.Data = resourceItem } // @router /resource/source_from [get] func (this *ResourceController) GetSourceFrom() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } resourceType, _ := this.GetInt("ResourceType") keyword := this.GetString("Keyword") resourceObj := new(knowledge.KnowledgeResource) list, err := resourceObj.GetSourceFrom(keyword, resourceType) if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } resp := new(knowledge.GetSourceFromResp) resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /resource/admins [get] func (this *ResourceController) GetAdminList() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() sysUser := this.SysUser if sysUser == nil { br.Msg = "请重新登录" return } resourceType, _ := this.GetInt("ResourceType") keyword := this.GetString("Keyword") resourceObj := new(knowledge.KnowledgeResource) list, err := resourceObj.GetAdmins(keyword, resourceType) if err != nil { br.Msg = "获取数据失败" br.Msg = "获取数据失败,Err:" + err.Error() return } resp := new(knowledge.GetAdminsResp) resp.List = list br.Ret = 200 br.Success = true br.Msg = "获取成功" br.Data = resp } // @router /resource/template [get] func (this *ResourceController) TemplateDownload() { br := new(models.BaseResponse).Init() defer func() { this.Data["json"] = br this.ServeJSON() }() resourceType, _ := this.GetInt("ResourceType") downUrl := "" fileName := "" switch resourceType { case 1: downUrl = "./static/template/政策库上传模板.xlsx" fileName = "政策库上传模板.xlsx" case 2: downUrl = "./static/template/观点库上传模板.xlsx" fileName = "观点库上传模板.xlsx" case 3: downUrl = "./static/template/知识库上传模板.xlsx" fileName = "知识库上传模板.xlsx" default: downUrl = "./static/template/事件库上传模板.xlsx" fileName = "事件库上传模板.xlsx" } if _, err := os.Stat(downUrl); os.IsNotExist(err) { br.Msg = "文件不存在" return } fmt.Println(downUrl, fileName) this.Ctx.Output.Download(downUrl, fileName) br.Ret = 200 br.Success = true br.Msg = "下载成功" }