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

// edit
// @Title 编辑客户
// @Description 编辑客户
// @Param   request	body request.UserEidtReq true "type json string"
// @Success 200 {object} request.UserAddReq
// @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)

	user, err := models.GetUserById(req.UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在或已删除,请重新刷新页面"
			br.ErrMsg = "用户不存在或已删除,请重新刷新页面,Err:" + err.Error()
			return
		}
		br.Msg = "编辑用户失败"
		br.ErrMsg = "编辑用户失败, 系统错误,Err:" + err.Error()
		return
	}
	user.RealName = req.RealName
	user.AreaCode = req.AreaCode
	user.Phone = req.Phone
	user.Email = req.Email
	user.SellerId = req.SellerId
	user.ValidStartTime = validStartTime
	user.ValidEndTime = validEndTime
	user.Company = req.Company
	user.ModifyTime = time.Now()
	// 当用户状态初始为潜在客户时,才更新创建时间
	if user.Status == utils.UserStatusPotential {
		user.CreateTime = time.Now()
	}
	oldStatus := user.Status
	if !req.IsEnabled {
		user.Status = 0
	} else {
		user.Status = 2
	}
	err = models.SaveUser(user, req.ChartPermission)
	if err != nil {
		br.Msg = "添加客户失败"
		br.ErrMsg = "添加客户失败,系统错误,Err:" + err.Error()
		return
	}
	record := &models.UserChangeRecord{}
	record.UserId = req.UserId
	record.SysUserId = this.SysUser.SysUserId
	if oldStatus == utils.UserStatusPotential && user.Status == utils.UserStatusFormal {
		record.Content = this.SysUser.SysRealName + "新增用户"
	} else {
		record.Content = this.SysUser.SysRealName + "编辑用户"
	}
	record.Insert()

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