package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"os"
	"path"
	"time"
)

// banner
type BannerController struct {
	BaseAuthController
}

// @Title 新增banner接口
// @Description 新增banner
// @Param	request	body models.BannerAddReq true "type json string"
// @Success 200 新增成功
// @router /add [post]
func (this *BannerController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.BannerAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	item := new(models.Banner)
	item.ClassifyId = req.ClassifyId
	item.ImageUrl = req.ImgUrl
	item.BannerType = req.BannerType
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.ClassifyName = req.ClassifyName
	item.JumpUrl = req.JumpUrl
	err = models.AddBanner(item)
	if err != nil {
		br.Msg = "新增失败."
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// @Title 编辑banner接口
// @Description 编辑banner
// @Param	request	body models.BannerEditReq true "type json string"
// @Success 200 新增成功
// @router /edit [post]
func (this *BannerController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.BannerEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	err = models.EditBanner(&req)
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
}

// @Title 删除轮播图
// @Description 删除轮播图
// @Param	request	body models.BannerDeleteReq true "type json string"
// @Success 200 新增成功
// @router /delete [post]
func (this *BannerController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.BannerDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	err = models.DeleteBanner(req.BannerId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// @Title 获取分类接口
// @Description 获取分类
// @Success 200 {object} models.Classify
// @router /getClassify [get]
func (this *BannerController) GetClassify() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	items, err := models.GetClassify()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = items
}

// @Title 获取分类接口
// @Description 获取分类
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   BannerType   query   int  true       "分类：1:轮播图，2:头部海报"
// @Param   KeyWord   query   string  true       "检索关键词"
// @Success 200 {object} models.BannerListResp
// @router /list [get]
func (this *BannerController) ListBanner() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	bannerType, _ := this.GetInt("BannerType")
	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 bannerType > 0 {
		condition = " AND banner_type=? "
		pars = append(pars, bannerType)
	}
	if keyWord != "" {
		condition += ` AND classify_name LIKE '%` + keyWord + `%'  `
	}
	total, err := models.GetBannerListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := models.GetBannerList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.BannerListResp)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 图片上传
// @Description 图片上传接口
// @Param   File   query   file  true       "文件"
// @Success 200 新增成功
// @router /upload [post]
func (this *BannerController) Upload() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	f, h, err := this.GetFile("file")
	if err != nil {
		br.Msg = "获取资源信息失败"
		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
		return
	}
	ext := path.Ext(h.Filename)

	uploadDir := "static/images/"
	if !utils.FileIsExist(uploadDir) {
		err = os.MkdirAll(uploadDir, 777)
		if err != nil {
			br.Msg = "存储目录创建失败"
			br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
			return
		}
	}

	fileName := fmt.Sprintf("%s%s", utils.GetRandStringNoSpecialChar(28), ext)
	savePath := uploadDir + "/" + fileName
	defer func() {
		_ = f.Close()
	}()
	err = this.SaveToFile("file", savePath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "SaveToFile, Err:" + err.Error()
		return
	}

	hzUploadDir := "static/images/"
	saveToOssPath := fmt.Sprintf("%s%s%s", hzUploadDir, time.Now().Format("200601/20060102/"), fileName)
	err = services.UploadFileToAliyun("", savePath, saveToOssPath)
	if err != nil {
		br.Msg = "文件上传失败"
		br.ErrMsg = "UploadFileToAliyun, Err:" + err.Error()
		return
	}
	resourceUrl := fmt.Sprintf("%s%s", "https://hzstatic.hzinsights.com/", saveToOssPath)

	defer func() {
		_ = os.Remove(savePath)
	}()

	item := new(models.Resource)
	item.ResourceUrl = resourceUrl
	item.ResourceType = 1
	item.CreateTime = time.Now()
	newId, err := models.AddResource(item)
	if err != nil {
		br.Msg = "资源上传失败"
		br.ErrMsg = "资源上传失败,Err:" + err.Error()
		return
	}
	resp := new(models.ResourceResp)
	resp.Id = newId
	resp.ResourceUrl = resourceUrl

	br.Msg = "上传成功"
	br.Ret = 200
	br.Success = true
	br.Data = resp
	return
}

// @Title
// @Description banner统计
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   BannerType   query   int  true       "分类：1:轮播图，2:头部海报"
// @Param   KeyWord   query   string  true       "检索关键词"
// @Success 200 {object} models.BannerListResp
// @router /statistic [get]
func (this *BannerController) BannerStatistic() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	urlList, err := models.GetBannerUrlList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	list, err := models.GetBannerHistoryList()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//resp := new(models.BannerHistoryListResp)

	souceMap := make(map[string][]*models.SourcePv)

	for _, v := range list {
		item := &models.SourcePv{
			FirstSource:     v.FirstSource,
			SecondSource:    v.SecondSource,
			Pv:              v.Pv,
			LastUpdatedTime: v.LastUpdatedTime,
		}
		souceMap[v.BannerUrl] = append(souceMap[v.BannerUrl], item)
	}
	for _, v := range urlList {
		v.SourceList = souceMap[v.BannerUrl]
	}


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