package controllers

import (
	"encoding/json"
	"eta/eta_mobile/models"
	"eta/eta_mobile/utils"
	"github.com/rdlucklib/rdluck_tools/paging"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"time"
)

// 报告
type PptController struct {
	BaseAuthController
}

// @Title 获取ppt列表
// @Description 获取ppt列表接口
// @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 *PptController) ListPpt() {
	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"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	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 + `%' OR admin_real_name LIKE '%` + keyWord + `%' ) `
	}
	total, err := models.GetPptListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := models.GetPptList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	lenList := len(list)
	for i := 0; i < lenList; i++ {
		adminId := list[i].AdminId
		if adminId == sysUser.AdminId || sysUser.Role == "admin" {
			list[i].IsAuth = true
		} else {
			list[i].IsAuth = false
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.PptListResp)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 新增ppt
// @Description 新增ppt接口
// @Param	request	body models.AddPptReq true "type json string"
// @Success 200 Ret=200 新增成功
// @router /add [post]
func (this *PptController) AddPpt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.AddPptReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.FirstPage.Title == "" {
		br.Msg = "标题不能为空"
		return
	}
	var newId int64
	var msg string
	if req.PptId <= 0 {
		item, err := models.GetPptByTitle(req.FirstPage.Title)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取数据异常！"
			br.ErrMsg = "获取数据异常，Err:" + err.Error()
			return
		}
		if item != nil {
			br.Msg = "标题已存在，不可重复添加"
			return
		}
		ppt := new(models.Ppt)
		ppt.Title = req.FirstPage.Title
		ppt.PptDate = req.FirstPage.PptDate
		ppt.ReportType = req.FirstPage.ReportType
		ppt.CreateTime = time.Now()
		ppt.ModifyTime = time.Now()
		ppt.AdminId = this.SysUser.AdminId
		ppt.AdminRealName = this.SysUser.RealName
		ppt.Version = 2
		newId, err = models.AddPpt(ppt)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败,Err:" + err.Error()
			return
		}

		firstPage := new(models.PptPages)
		firstPage.PptId = newId
		firstPage.Title = req.FirstPage.Title
		firstPage.ResourceId = "0"
		firstPage.Timestamp = 0
		firstPage.BackIndex = req.FirstPage.BackIndex
		_, err = models.AddPptPages(firstPage)

		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增章节失败,Err:" + err.Error()
			return
		}

		for _, v := range req.ContentPage {
			if v.ResourceId == "" {
				br.Msg = "图表参数错误"
				br.ErrMsg = "图表参数错误,ResourceId 等于0"
				return
			}

			count, _ := models.GetPptPagesContent(int(newId), v.ResourceId)
			if count <= 0 {
				page := new(models.PptPages)
				page.PptId = newId
				page.Title = v.Title
				page.ResourceId = v.ResourceId
				page.Timestamp = v.Timestamp
				page.CreateTime = time.Now()
				page.ModifyTime = time.Now()
				_, err = models.AddPptPages(page)
				if err != nil {
					br.Msg = "新增失败"
					br.ErrMsg = "新增章节失败,Err:" + err.Error()
					return
				}
			}
		}
		msg = "新增成功"
	} else {
		newId = req.PptId
		ppt := new(models.Ppt)
		ppt.PptId = int(req.PptId)
		ppt.Title = req.FirstPage.Title
		ppt.PptDate = req.FirstPage.PptDate
		ppt.ReportType = req.FirstPage.ReportType
		ppt.ModifyTime = time.Now()
		err = models.EditPpt(ppt)
		//删除ppt_pages
		err = models.DeletePptPages(req.PptId)
		if err != nil {
			br.Msg = "编辑失败"
			br.ErrMsg = "编辑失败,Err:" + err.Error()
			return
		}
		firstPage := new(models.PptPages)
		firstPage.PptId = newId
		firstPage.Title = req.FirstPage.Title
		firstPage.ResourceId = ""
		firstPage.Timestamp = 0
		firstPage.BackIndex = req.FirstPage.BackIndex
		_, err = models.AddPptPages(firstPage)

		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增章节失败,Err:" + err.Error()
			return
		}
		for _, v := range req.ContentPage {
			if v.ResourceId == "" {
				br.Msg = "图表参数错误"
				br.ErrMsg = "图表参数错误,ResourceId 等于 empty"
				return
			}
			count, _ := models.GetPptPagesContent(int(newId), v.ResourceId)
			if count <= 0 {
				page := new(models.PptPages)
				page.PptId = newId
				page.Title = v.Title
				page.ResourceId = v.ResourceId
				page.Timestamp = v.Timestamp
				page.CreateTime = time.Now()
				page.ModifyTime = time.Now()
				_, err = models.AddPptPages(page)
				if err != nil {
					br.Msg = "新增失败"
					br.ErrMsg = "新增章节失败,Err:" + err.Error()
					return
				}
			}
		}
		msg = "保存成功"
	}
	resp := new(models.AddPptResp)
	resp.PptId = newId
	br.Ret = 200
	br.Success = true
	br.Msg = msg
	br.Data = resp
}

// @Title 编辑ppt
// @Description 编辑ppt接口
// @Param	request	body models.EditPptReq true "type json string"
// @Success 200 Ret=200 编辑成功
// @router /edit [post]
func (this *PptController) EditPpt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.EditPptReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.FirstPage.Title == "" {
		br.Msg = "标题不能为空"
		return
	}
	item, err := models.GetPptByTitle(req.FirstPage.Title)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据异常！"
		br.ErrMsg = "获取数据异常，Err:" + err.Error()
		return
	}
	if item != nil && item.PptId != int(req.PptId) {
		br.Msg = "标题已存在，不可重复添加"
		return
	}

	ppt := new(models.Ppt)
	ppt.PptId = int(req.PptId)
	ppt.Title = req.FirstPage.Title
	ppt.PptDate = req.FirstPage.PptDate
	ppt.ReportType = req.FirstPage.ReportType
	ppt.ModifyTime = time.Now()
	err = models.EditPpt(ppt)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}
	newId := req.PptId
	//删除ppt_pages
	err = models.DeletePptPages(newId)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}
	firstPage := new(models.PptPages)
	firstPage.PptId = newId
	firstPage.Title = req.FirstPage.Title
	firstPage.ResourceId = "0"
	firstPage.Timestamp = 0
	firstPage.BackIndex = req.FirstPage.BackIndex
	_, err = models.AddPptPages(firstPage)

	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "新增章节失败,Err:" + err.Error()
		return
	}

	for _, v := range req.ContentPage {
		if v.ResourceId == "" {
			br.Msg = "图表参数错误"
			br.ErrMsg = "图表参数错误,ResourceId 等于 empty"
			return
		}
		count, _ := models.GetPptPagesContent(int(newId), v.ResourceId)
		if count <= 0 {
			page := new(models.PptPages)
			page.PptId = newId
			page.Title = v.Title
			page.ResourceId = v.ResourceId
			page.Timestamp = v.Timestamp
			page.CreateTime = time.Now()
			page.ModifyTime = time.Now()
			_, err = models.AddPptPages(page)
			if err != nil {
				br.Msg = "编辑失败"
				br.ErrMsg = "新增章节失败,Err:" + err.Error()
				return
			}
		}
	}

	resp := new(models.AddPptResp)
	resp.PptId = req.PptId
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.Data = resp
}

// @Title 删除ppt
// @Description 删除ppt接口
// @Param	request	body models.DeletePptReq true "type json string"
// @Success 200 Ret=200 编辑成功
// @router /delete [post]
func (this *PptController) DeletePpt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.DeletePptReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.PptId <= 0 {
		br.Msg = "参数错误"
		return
	}
	err = models.DeletePpt(req.PptId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// @Title 新增ppt章节
// @Description 新增ppt章节接口
// @Param	request	body models.ContentPageItems true "type json string"
// @Success 200 Ret=200 编辑成功
// @router /addPptPages [post]
func (this *PptController) AddPptPages() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.ContentPageItems
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	page := new(models.PptPages)
	page.PptId = req.PptId
	page.Title = req.Title
	page.CreateTime = time.Now()
	page.ModifyTime = time.Now()
	page.ResourceId = req.ResourceId
	_, err = models.AddPptPages(page)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// @Title 获取ppt详情
// @Description 获取ppt详情接口
// @Param   PptId   query   int  true       "ppt_id"
// @Success 200 {object} models.ReportListResp
// @router /detail [get]
func (this *PptController) DetailPpt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pptId, _ := this.GetInt("PptId")
	ppt, err := models.GetPptById(pptId)
	if err != nil {
		br.Msg = "信息获取失败"
		br.ErrMsg = "信息获取失败,Err:" + err.Error()
		return
	}
	pptPages, err := models.GetPptPagesById(pptId)
	if err != nil {
		br.Msg = "信息获取失败"
		br.ErrMsg = "信息获取失败,Err:" + err.Error()
		return
	}
	resp := new(models.PptDetailResp)
	resp.Ppt = ppt
	resp.PptPages = pptPages
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

type PptCommonController struct {
	BaseCommonController
}

// @Title ppt下载
// @Description ppt下载
// @Param   PptId   query   int  true       "PptId"
// @Success 200 下载成功
// @router /download [get]
func (this *PptCommonController) Download() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pptId, err := this.GetInt("PptId")
	if err != nil {
		br.Msg = "参数错误"
		br.ErrMsg = "获取，pptId，Err:" + err.Error()
		return
	}
	ppt, err := models.GetPptById(pptId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败，Err:" + err.Error()
		return
	}
	filePath := ppt.PptUrl + ".ppt"
	fileName := ppt.Title + ".ppt"
	this.Ctx.Output.Download(filePath, fileName)
	br.Success = true
	br.Ret = 200
	br.Msg = "下载成功"
	return
}

// @Title ppt下载
// @Description ppt下载
// @Param   PptId   query   int  true       "PptId"
// @Success 200 下载成功
// @router /downloadpptx [get]
func (this *PptCommonController) Downloadpptx() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pptId, err := this.GetInt("PptId")
	if err != nil {
		br.Msg = "参数错误"
		br.ErrMsg = "获取，pptId，Err:" + err.Error()
		return
	}
	ppt, err := models.GetPptById(pptId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败，Err:" + err.Error()
		return
	}
	filePath := ppt.PptUrl + ".pptx"
	fileName := ppt.Title + ".pptx"
	this.Ctx.Output.Download(filePath, fileName)
	br.Success = true
	br.Ret = 200
	br.Msg = "下载成功"
	return
}

// @Title 获取首页背景模板接口
// @Description 获取首页背景模板接口
// @Success 200 {object} models.PptImagesResp
// @router /getImages [get]
func (this *PptController) GetImages() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	imageType := 0
	ppt, err := models.GetImages(imageType)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败，Err:" + err.Error()
		return
	}

	resp := new(models.PptImagesResp)
	resp.List = ppt
	br.Data = resp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	return
}

type PublishPptResult struct {
	Result      string `json:"result"`
	PptPath     string `json:"ppt_path"`
	PptName     string `json:"ppt_name"`
	PptFullPath string `json:"ppt_full_path"`
}

/*
func init() {
	fmt.Println("start")
	var err error
	defer func() {
		if err != nil {
			fmt.Println("err:", err.Error())
		}
	}()
	pptId := 111
	if pptId <= 0 {
		return
	}

	pptFirstPages, err := models.GetPptFirstPage(pptId)
	if err != nil {
		return
	}
	pptContentPages, err := models.GetPptContentPages(pptId, pptFirstPages.PptPagesId)
	if err != nil {
		return
	}
	dataMap := make(map[string]interface{})
	dataMap["FirstPage"] = pptFirstPages
	dataMap["ContentPage"] = pptContentPages
	dataMap["ScreenHeight"] = 12000

	postUrl := "http://127.0.0.1:5000/publish_ppt/" //随便写的
	postData, err := json.Marshal(dataMap)
	if err != nil {
		return
	}
	utils.FileLog.Info("%s",string(postData))
	result, err := http.Post(postUrl, string(postData))
	fmt.Println("result:", string(result))
	if err != nil {
		return
	}
	var pptResult PublishPptResult
	err = json.Unmarshal(result, &pptResult)
	if err != nil {
		return
	}
	fmt.Println("ppt:", pptResult.PptFullPath)
	fmt.Println("end")
}
*/

/*func init() {
	fmt.Println("start")
	fmt.Println(time.Now())
	randStr := utils.GetRandStringNoSpecialChar(28)
	fileName := randStr + ".png"
	savePath := "./b1.jpg"
	resourceUrl, err := services.UploadAliyun(fileName, savePath)
	if err != nil {
		fmt.Println("err:", err)
	}
	fmt.Println(resourceUrl)
	fmt.Println(time.Now())
	fmt.Println("end")
}
*/
