package help_doc

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/help_doc"
	"hongze/hz_crm_api/utils"
	"html"
	"strconv"
	"strings"
	"time"

	"github.com/rdlucklib/rdluck_tools/paging"
)

// HelpDocController 帮助文档
type HelpDocController struct {
	controllers.BaseAuthController
}

// @Title 新增报告接口
// @Description 新增报告
// @Param	request	body help_doc.AddHelpDocReq true "type json string"
// @Success 200 {object} models.AddEnglishReportResp
// @router /add [post]
func (this *HelpDocController) 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 help_doc.AddHelpDocReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	fmt.Println("Id:", req.Id)
	if req.Content == "" {
		br.Msg = "请输入内容"
		return
	}
	var anchor []byte
	if req.AnchorData != nil {
		anchor, err = json.Marshal(req.AnchorData)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}
	var recommend []byte
	if req.RecommendData != nil {
		recommend, err = json.Marshal(req.RecommendData)
		if err != nil {
			br.Msg = "参数解析异常！"
			br.ErrMsg = "参数解析失败，Err:" + err.Error()
			return
		}
	}

	var resp help_doc.HelpDocSaveResp
	resp.HelpDocId = req.Id
	resp.ModifyTime = time.Now().Format(utils.FormatDateTime)

	item := new(help_doc.HelpDoc)
	item.ClassifyId = req.ClassifyId
	item.Title = req.Title
	item.Author = req.Author
	item.Status = req.Status
	item.Content = html.EscapeString(req.Content)
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.AdminId = sysUser.AdminId
	item.AdminRealName = sysUser.RealName
	item.Anchor = string(anchor)
	item.Recommend = string(recommend)
	if req.Status == 2 {
		item.PublishTime = time.Now()
	}
	if req.Id > 0 {
		tmpHelpDoc, err := help_doc.GetHelpDocById(int(req.Id))
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "查询帮助文档失败,Err:" + err.Error()
			return
		}
		if tmpHelpDoc.Status != req.Status {
			req.IsChange = true
		}
	}

	if req.Id == 0 {
		id, e := help_doc.AddHelpDoc(item)
		if e != nil {
			err = e
			br.Msg = "新增失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
		resp.HelpDocId = id
		resp.ModifyTime = item.ModifyTime.Format(utils.FormatDateTime)
	} else if req.IsChange {
		err = help_doc.EditHelpDoc(item, req.Id)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
	}

	if req.Status == 1 {
		br.Msg = "保存成功"
	} else {
		br.Msg = "发布成功"
	}
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 获取报告详情接口
// @Description 获取报告详情
// @Param	request	body models.ReportDetailReq true "type json string"
// @Success 200 {object} models.EnglishReportDetailView
// @router /detail [get]
func (this *HelpDocController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	docId, err := this.GetInt("DocId")
	if err != nil {
		br.Msg = "获取参数失败！"
		br.ErrMsg = "获取参数失败，Err:" + err.Error()
		return
	}
	if docId <= 0 {
		br.Msg = "参数错误"
		return
	}
	item, err := help_doc.GetHelpDocById(docId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	item.Content = html.UnescapeString(item.Content)

	var anchor []help_doc.AnchorList
	if item.Anchor != "" {
		err = json.Unmarshal([]byte(item.Anchor), &anchor)
		if err != nil {
			br.Msg = "解析失败"
			br.ErrMsg = "解析失败，Err:" + err.Error()
			return
		}
	}

	var recommend []help_doc.RecommendList
	if item.Recommend != "" {
		err = json.Unmarshal([]byte(item.Recommend), &recommend)
		if err != nil {
			br.Msg = "解析失败"
			br.ErrMsg = "解析失败，Err:" + err.Error()
			return
		}
	}

	resp := help_doc.HelpDocResp{
		Id:            item.Id,
		ClassifyId:    item.ClassifyId,
		Title:         item.Title,
		Author:        item.Author,
		CreateTime:    item.CreateTime,
		ModifyTime:    item.ModifyTime,
		Status:        item.Status,
		PublishTime:   item.PublishTime,
		Content:       item.Content,
		AdminId:       item.AdminId,
		AdminRealName: item.AdminRealName,
		Anchor:        anchor,
		Recommend:     recommend,
	}

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

// @Title 获取报告列表接口
// @Description 获取报告列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} models.ReportListResp
// @router /list [get]
func (this *HelpDocController) ListReport() {
	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
	}

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

	classifyIds := this.GetString("ClassifyIds")
	keyWord := this.GetString("KeyWord")

	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{}

	if keyWord != "" {
		condition += ` AND title LIKE '%` + keyWord + `%' `
	}

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

	//拿到所有分类信息，显示路径用
	classifyAll, err := help_doc.GetAllHelpDocClassify()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	parentMap := make(map[int]int)
	classifyNameMap := make(map[int]string)
	for _, v := range classifyAll {
		classifyNameMap[v.ClassifyId] = v.ClassifyName
		if v.ParentId != 0 {
			parentMap[v.ClassifyId] = v.ParentId
		}
	}

	total, err := help_doc.GetHelpDocListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := help_doc.GetHelpDocList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	resp := new(help_doc.HelpDocListResp)
	for _, item := range list {
		var anchor []help_doc.AnchorList
		if item.Anchor != "" {
			err = json.Unmarshal([]byte(item.Anchor), &anchor)
			if err != nil {
				br.Msg = "解析失败"
				br.ErrMsg = "解析失败，Err:" + err.Error()
				return
			}
		}

		var recommend []help_doc.RecommendList
		if item.Recommend != "" {
			err = json.Unmarshal([]byte(item.Recommend), &recommend)
			if err != nil {
				br.Msg = "解析失败"
				br.ErrMsg = "解析失败，Err:" + err.Error()
				return
			}
		}
		respItem := help_doc.HelpDocResp{
			Id:            item.Id,
			ClassifyId:    item.ClassifyId,
			Title:         item.Title,
			Author:        item.Author,
			CreateTime:    item.CreateTime,
			ModifyTime:    item.ModifyTime,
			Status:        item.Status,
			PublishTime:   item.PublishTime,
			Content:       item.Content,
			AdminId:       item.AdminId,
			AdminRealName: item.AdminRealName,
			Anchor:        anchor,
			Recommend:     recommend,
		}
		if pid, ok := parentMap[respItem.ClassifyId]; ok {
			pName := classifyNameMap[pid]
			if ppid, ok := parentMap[pid]; ok {
				ppName := classifyNameMap[ppid]
				respItem.ClassifyName = ppName + "/" + pName + "/" + classifyNameMap[respItem.ClassifyId]
			} else {
				respItem.ClassifyName = pName + "/" + classifyNameMap[respItem.ClassifyId]
			}
		} else {
			respItem.ClassifyName = classifyNameMap[respItem.ClassifyId]
		}
		resp.List = append(resp.List, &respItem)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page

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

// @Title 发布报告接口
// @Description 发布报告
// @Param	request	body models.PublishReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /publish [post]
func (this *HelpDocController) PublishReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req help_doc.PublishReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	docId := req.DocId
	if docId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，报告id不可为空"
		return
	}

	doc, err := help_doc.GetHelpDocById(docId)
	if err != nil {
		br.Msg = "获取报告信息失败"
		br.ErrMsg = "获取报告信息失败,Err:" + err.Error()
		return
	}
	if doc == nil {
		br.Msg = "报告不存在"
		return
	}

	var tmpErr error

	if doc.Content == "" {
		br.Msg = "报告内容为空，不可发布"
		br.ErrMsg = "报告内容为空，不需要生成,report_id:" + strconv.Itoa(doc.Id)
		return
	}
	if tmpErr = help_doc.PublishHelpDocById(docId, req.Status); tmpErr != nil {
		br.Msg = "报告发布失败"
		br.ErrMsg = "报告发布失败, Err:" + tmpErr.Error() + ", doc_id:" + strconv.Itoa(docId)
		return
	}

	if req.Status == 1 {
		br.Msg = "取消发布成功"
	} else {
		br.Msg = "发布成功"
	}

	br.Ret = 200
	br.Success = true

}

// @Title 删除报告接口
// @Description 删除报告
// @Param	request	body models.DeleteReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /delete [post]
func (this *HelpDocController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req help_doc.DeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.DocId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，报告id不可为空"
		return
	}
	_, err = help_doc.GetHelpDocById(req.DocId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "报告不存在"
			return
		}
		br.Msg = "查询报告信息失败"
		br.ErrMsg = "查询报告信息失败, Err" + err.Error()
		return
	}

	err = help_doc.DeleteHelpDoc(req.DocId)
	if err != nil {
		br.Msg = "删除报告失败"
		br.ErrMsg = "删除报告失败, Err" + err.Error()
		return
	}

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