package controllers

import (
	"encoding/json"
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/models/request"
	"eta/eta_mini_crm_ht/models/response"
	"eta/eta_mini_crm_ht/services"
	"eta/eta_mini_crm_ht/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

type ImageController struct {
	BaseAuthController
}

// UploadImage @Title 上传图片
// @Description 上传视频
// @Param   File   query   file  true       "文件"
// @Success 200 {object} models.ReportAuthorResp
// @router /uploadImage [post]
func (this *ImageController) UploadImage() {
	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
	}
	defer f.Close()
	size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)
	if err != nil {
		size = 100
	}
	if h.Size > 1024*1024*int64(size) {
		br.Msg = fmt.Sprintf("图片大小不能超过%dK", size)
		br.ErrMsg = "图片上传失败，Err:" + err.Error()
		return
	}
	ext := path.Ext(h.Filename)
	//if ext != ".mp3" {
	//	br.Msg = "音频格式不正确"
	//	br.ErrMsg = "音频上传失败，Err:" + err.Error()
	//	return
	//}
	dateDir := time.Now().Format("20060102")
	uploadDir := utils.STATIC_DIR + "ht/audio" + dateDir
	err = os.MkdirAll(uploadDir, utils.DIR_MOD)
	if err != nil {
		br.Msg = "存储目录创建失败"
		br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
		return
	}
	randStr := utils.GetRandStringNoSpecialChar(28)
	fileName := randStr + ext
	fpath := uploadDir + "/" + fileName
	err = this.SaveToFile("File", fpath)
	if err != nil {
		br.Msg = "图片上传失败"
		br.ErrMsg = "图片上传失败，Err:" + err.Error()
		return
	}
	audioUploadDir := utils.RESOURCE_DIR + "img/"
	savePdfToOssPath := audioUploadDir + time.Now().Format("200601/20060102/")
	audioName := utils.GetRandStringNoSpecialChar(28)
	savePdfToOssPath += audioName + ext

	defer func() {
		err = os.Remove(fpath)
		fmt.Sprintf("删除文件失败:%v", err)
	}()
	ossClient := services.NewOssClient()
	if ossClient == nil {
		br.Msg = "图片上传失败"
		br.ErrMsg = "初始化OSS服务失败"
		return
	}
	mp3Url, err := ossClient.UploadFile("", fpath, savePdfToOssPath)
	if err != nil {
		br.Msg = "图片上传失败"
		br.ErrMsg = "图片上传失败，Err:" + err.Error()
		return
	}
	base := path.Base(h.Filename)
	resp := new(response.MediaUploadResp)
	resp.Url = mp3Url
	resp.FileName = base
	br.Data = resp
	br.Msg = "上传成功"
	br.Ret = 200
	br.Success = true
}

// AddImage @Title 新增图片
// @Description 新增图片
// @Param   File   query   file  true       "文件"
// @router /addImage [post]
func (this *ImageController) AddImage() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.ImageReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析失败"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ImageName == "" {
		br.Msg = "图片名称为空"
		return
	}

	if req.SrcUrl == "" {
		br.Msg = "音频地址为空"
		return
	}

	if req.PermissionId <= 0 {
		br.Msg = "品种标签为空"
		return
	}
	var err error
	imageInsert := &models.ImageSource{
		ImgName:      req.ImageName,
		SrcUrl:       req.SrcUrl,
		PermissionId: req.PermissionId,
		Deleted:      0,
		CreatedTime:  time.Now(),
	}

	_, err = imageInsert.Insert()
	if err != nil {
		br.Msg = "添加失败"
		br.ErrMsg = "图片新增失败，Err:" + err.Error()
		return
	}
	br.Msg = "添加成功"
	br.Ret = 200
	br.Success = true
}

// EditImage
//
//	@Title 编辑音频
//
// @Description 编辑音频
// @Success 200 {object} models.ReportAuthorResp
// @router /editImage [post]
func (this *ImageController) EditImage() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.ImageReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析失败"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ImageId <= 0 {
		br.Msg = "图片ID为空"
		return
	}
	if req.ImageName == "" {
		br.Msg = "图片名称为空"
		return
	}
	if req.SrcUrl == "" {
		br.Msg = "图片src为空"
		return
	}
	if req.PermissionId <= 0 {
		br.Msg = "品种标签为空"
		return
	}
	var err error

	imageUpdate := &models.ImageSource{
		Id:           req.ImageId,
		ImgName:      req.ImageName,
		SrcUrl:       req.SrcUrl,
		PermissionId: req.PermissionId,
		Deleted:      0,
		CreatedTime:  time.Now(),
	}

	err = imageUpdate.Update()
	if err != nil {
		br.Msg = "更新失败"
		br.ErrMsg = "图片更新失败，Err:" + err.Error()
		return
	}
	br.Msg = "编辑成功"
	br.Ret = 200
	br.Success = true
}

// DeleteImage
// @Title 删除音频
//
// @Description 删除音频
// @Success 200 {object} models.ReportAuthorResp
// @router /deleteImage [post]
func (this *ImageController) DeleteImage() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.ImageReq
	if err := json.Unmarshal(this.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析失败"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ImageId <= 0 {
		br.Msg = "图片ID为空"
		return
	}
	var err error

	imageDelete := &models.ImageSource{
		Id:      req.ImageId,
		Deleted: 1,
	}

	err = imageDelete.Delete()
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "图片删除失败，Err:" + err.Error()
		return
	}
	br.Msg = "删除成功"
	br.Ret = 200
	br.Success = true
}

// ImageList
// @Title 研报列表
// @Description pdf研报列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ClassifyIds   query   string  true       "二级分类id,可多选用英文,隔开"
// @Param   KeyWord   query   string  true       "报告标题/创建人"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} models.ReportAuthorResp
// @router /imageList [get]
func (this *ImageController) ImageList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	permissionIds := this.GetString("PermissionIds")
	sortType := this.GetString("SortType")
	KeyWord := this.GetString("KeyWord")
	var condition string
	var pars []interface{}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	if KeyWord != "" {
		condition += " AND img_name like '%" + KeyWord + "%'"
	}
	if permissionIds != "" {
		permissionArr := strings.Split(permissionIds, ",")
		for _, permissionId := range permissionArr {
			perId, _ := strconv.Atoi(permissionId)
			pars = append(pars, perId)
		}
		condition += " AND permission_id in (" + utils.GetOrmReplaceHolder(len(pars)) + ")"
	}

	sortCondition := " ORDER BY created_time "
	if sortType == "" {
		sortType = "DESC"
	}
	sortCondition = sortCondition + sortType
	total, err := models.GetImageCountByCondition(condition, pars)
	if err != nil {
		br.Msg = "获取图片列表失败"
		br.ErrMsg = "获取图片列表统计失败，Err:" + err.Error()
		return
	}

	startSize := utils.StartIndex(currentIndex, pageSize)
	imageList, err := models.GetImageByCondition(condition, sortCondition, pars, startSize, pageSize)
	var results []*models.ImageSourceView
	for _, image := range imageList {
		var view *models.ImageSourceView
		view, err = image.ToView()
		if err != nil {
			br.Msg = "获取图片列表失败"
			br.ErrMsg = "获取图片品种名称失败，Err:" + err.Error()
			return
		}
		results = append(results, view)
	}
	if err != nil {
		br.Msg = "获取图片列表失败"
		br.ErrMsg = "获取图片列表失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.ImageSourceListResp)
	resp.List = results
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.Msg = "获取成功"
}
