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"
)

const ()

type AnalystController struct {
	BaseAuthController
}

// UploadImage
// @Title 上传头像
// @Description 上传头像
// @Param   File   query   file  true       "文件"
// @Success 200 {object} models.ReportAuthorResp
// @router /uploadImage [post]
func (this *AnalystController) 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()
	ext := path.Ext(h.Filename)
	//if ext != ".pdf" {
	//	br.Msg = "文件格式不正确"
	//	return
	//}
	size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)
	if err != nil {
		size = 15
	}
	if h.Size > 1024*int64(size) {
		br.Msg = fmt.Sprintf("头像文件大小不能超过%dK", size)
		return
	}
	dateDir := time.Now().Format("20060102")
	uploadDir := utils.STATIC_DIR + "ht/" + 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
	}
	pdfUploadDir := utils.RESOURCE_DIR + "analyst/"
	savePdfToOssPath := pdfUploadDir + time.Now().Format("200601/20060102/")
	imgName := utils.GetRandStringNoSpecialChar(28)
	savePdfToOssPath += imgName

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

	ossClient := services.NewOssClient()
	if ossClient == nil {
		br.Msg = "头像上传失败"
		br.ErrMsg = "初始化OSS服务失败"
		return
	}
	imgUrl, err := ossClient.UploadFile("", fpath, savePdfToOssPath)
	if err != nil {
		br.Msg = "头像上传失败"
		br.ErrMsg = "头像上传失败，Err:" + err.Error()
		return
	}

	base := path.Base(h.Filename)
	resp := new(response.ReportPdfUploadResp)
	resp.Url = imgUrl
	resp.FileName = base

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

// GetAnalystByName
// @Title 查询研究员信息
// @Description 查询研究员信息
// @Param   File   query   file  true       "文件"
// @Success 200 {object} models.ReportAuthorResp
// @router /analyst [get]
func (this *AnalystController) GetAnalystByName(AnalystName string) {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	analyst, err := models.GetAnalystByName(AnalystName)

	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = analyst.ToView()
}

// List
// @Title 列表
// @Description 列表
// @Param   File   query   file  true       "文件"
// @Success 200 {object} models.ReportAuthorResp
// @router /list [get]
func (this *AnalystController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

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

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	total, err := models.GetAnalystCount()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	list, err := models.GetAnalystList(startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	analystList := make([]*models.AnalystView, 0)
	for _, v := range list {
		analystList = append(analystList, &models.AnalystView{
			Id:           v.Id,
			Name:         v.Name,
			HeadImgURL:   v.HeadImgUrl,
			Introduction: v.Introduction,
			CreatedTime:  v.CreatedTime.Format(time.DateTime),
		})

	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.AnalystListResp)
	resp.List = analystList
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// edit
// @Title 编辑研究员
// @Description 编辑研究员
// @Param   request	body request.AnalystEditReq true "type json string"
// @Success 200 string 编辑成功
// @router /edit [post]
func (this *AnalystController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req request.AnalystEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "请选择用户"
		return
	}
	if req.HeadImgUrl == "" {
		br.Msg = "请输入头像地址"
		return
	}
	req.Introduction = strings.TrimSpace(req.Introduction)

	analyst, err := models.GetAnalystById(req.Id)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在或已删除，请重新刷新页面"
			br.ErrMsg = "用户不存在或已删除，请重新刷新页面，Err:" + err.Error()
			return
		}
		br.Msg = "编辑用户失败"
		br.ErrMsg = "编辑用户失败, 系统错误，Err:" + err.Error()
		return
	}
	if req.HeadImgUrl != `` {
		analyst.HeadImgUrl = req.HeadImgUrl
	}
	analyst.Introduction = req.Introduction
	analyst.UpdatedTime = time.Now()
	err = analyst.Update([]string{"HeadImgURL", "Introduction", "UpdatedTime"})
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败, 系统错误，Err:" + err.Error()
		return
	}

	br.Msg = "编辑成功"
	br.Success = true
	br.Ret = 200
}
