package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"os"
	"path"
	"strings"
	"time"
)

// ReportController 报告
type ReportController struct {
	BaseAuthController
}

// 报告上传
type ReportUploadCommonController struct {
	web.Controller
}

// GetDayWeekReportChapterTypeList
// @Title 获取晨报周报章节类型列表
// @Description 获取晨报周报章节类型列表
// @Param	StopType	query	string	true	"停更类型 stop; disable;"
// @Success 200 {object} models.ReportListResp
// @router /getDayWeekReportChapterTypeList [get]
func (this *ReportController) GetDayWeekReportChapterTypeList() {
	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"
		br.Ret = 408
		return
	}

	var condition string
	var pars []interface{}
	// 停更类型
	stopType := this.GetString("StopType")
	switch stopType {
	case "", "stop":
		condition += ` AND enabled = ? `
		pars = append(pars, 1)
	case "disable":
	default:
		br.Msg = "停更类型异常"
		br.IsSendEmail = false
		return
	}

	dayList := make([]*models.ReportChapterType, 0)
	weekList := make([]*models.ReportChapterType, 0)

	// 晨报
	{
		tmpCondition := condition
		tmpPars := pars
		// 报告类型
		tmpCondition += ` AND research_type = ? `
		tmpPars = append(tmpPars, "day")

		list, err := models.GetAllReportChapterTypeList(tmpCondition, tmpPars)
		if err != nil {
			br.Msg = "获取报告章节类型列表失败"
			br.ErrMsg = "获取报告章节类型列表失败, Err: " + err.Error()
			return
		}
		nowTime := time.Now()
		for _, v := range list {
			if v.IsSet == 1 {
				endTime, _ := time.Parse(utils.FormatDate, v.PauseEndTime)
				if nowTime.After(endTime.AddDate(0, 0, 1)) { //设置过期了已经
					v.IsSet = 0
					v.PauseStartTime = ``
					v.PauseEndTime = ``
				}
			}
			dayList = append(dayList, v)
		}
	}

	// 周报
	{
		tmpCondition := condition
		tmpPars := pars
		// 报告类型
		tmpCondition += ` AND research_type = ? `
		tmpPars = append(tmpPars, "week")

		list, err := models.GetAllReportChapterTypeList(tmpCondition, tmpPars)
		if err != nil {
			br.Msg = "获取报告章节类型列表失败"
			br.ErrMsg = "获取报告章节类型列表失败, Err: " + err.Error()
			return
		}
		nowTime := time.Now()
		for _, v := range list {
			if v.IsSet == 1 {
				endTime, _ := time.Parse(utils.FormatDate, v.PauseEndTime)
				if nowTime.After(endTime.AddDate(0, 0, 1)) { //设置过期了已经
					v.IsSet = 0
					v.PauseStartTime = ``
					v.PauseEndTime = ``
				}
			}
			weekList = append(weekList, v)
		}
	}

	resp := models.UpdateReportChapterTypeResp{
		Day:  dayList,
		Week: weekList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取晨报周报的更新暂停时间
// @Description 获取晨报周报的更新暂停时间
// @Success 200 {object} models.ReportListResp
// @router /getDayWeekReportPauseTime [get]
func (this *ReportController) GetDayWeekReportPauseTime() {
	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"
		br.Ret = 408
		return
	}

	list, err := models.GetDayWeekReportPauseTimeList()
	if err != nil {
		br.Msg = "获取晨报周报的更新暂停时间失败"
		br.ErrMsg = "获取晨报周报的更新暂停时间失败, Err: " + err.Error()
		return
	}

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

// SetDayWeekReportUpdateRule
// @Title 设置晨报周报的更新规则
// @Description 设置晨报周报的更新规则
// @Param	request	body models.SetDayWeekReportUpdateRuleReq true "type json string"
// @Success 200 string "操作成功"
// @router /setDayWeekReportUpdateRule [post]
func (this *ReportController) SetDayWeekReportUpdateRule() {
	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"
		br.Ret = 408
		return
	}

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

	researchType := req.ResearchType
	if researchType == "" {
		br.Msg = "报告类型不能为空"
		return
	}

	// 设置章节类型的暂停时间
	if err := models.SetDayWeekReportUpdateRule(researchType, req.List); err != nil {
		br.Msg = "设置暂停时间失败"
		br.ErrMsg = "设置暂停时间失败, Err: " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// SetDayWeekReportEnableRule
// @Title 设置晨报周报的永久暂停更新规则
// @Description 设置晨报周报的永久暂停更新规则
// @Param	request	body models.SetDayWeekReportEnableUpdateRuleReq true "type json string"
// @Success 200 string "操作成功"
// @router /setDayWeekReportEnableUpdateRule [post]
func (this *ReportController) SetDayWeekReportEnableRule() {
	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"
		br.Ret = 408
		return
	}

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

	dayReportChapterTypeIdList := strings.Split(req.DayReportChapterTypeId, ",")
	weekReportChapterTypeIdList := strings.Split(req.WeekReportChapterTypeId, ",")
	//if len(reportChapterTypeIdList) <= 0 {
	//	br.Msg = "报告类型选择异常"
	//	br.IsSendEmail = false
	//	return
	//}

	// 设置章节类型的禁用状态
	if err := models.SetDayWeekReportEnableUpdateRule(dayReportChapterTypeIdList, weekReportChapterTypeIdList); err != nil {
		br.Msg = "设置永久停更失败"
		br.ErrMsg = "设置永久停更失败, Err: " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// GetStopDayWeekReportChapterTypeList
// @Title 获取暂停更新的晨报周报章节类型列表
// @Description 获取暂停更新的晨报周报章节类型列表
// @Success 200 {object} models.ReportListResp
// @router /getStopDayWeekReportChapterTypeList [get]
func (this *ReportController) GetStopDayWeekReportChapterTypeList() {
	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"
		br.Ret = 408
		return
	}

	stopDay := make([]*models.ReportChapterType, 0)
	stopWeek := make([]*models.ReportChapterType, 0)
	disableDay := make([]*models.ReportChapterType, 0)
	disableWeek := make([]*models.ReportChapterType, 0)

	stopList, err := models.GetStopUpdateReportChapterTypeListByResearchType()
	if err != nil {
		br.Msg = "获取暂停更新报告章节类型列表失败"
		br.ErrMsg = "获取暂停更新报告章节类型列表失败, Err: " + err.Error()
		return
	}

	for _, v := range stopList {
		if v.ResearchType == "day" {
			stopDay = append(stopDay, v)
		} else {
			stopWeek = append(stopWeek, v)
		}
	}

	disableList, err := models.GetDisableUpdateReportChapterTypeListByResearchType()
	if err != nil {
		br.Msg = "获取停止更新报告章节类型列表失败"
		br.ErrMsg = "获取停止更新报告章节类型列表失败, Err: " + err.Error()
		return
	}
	for _, v := range disableList {
		if v.ResearchType == "day" {
			disableDay = append(disableDay, v)
		} else {
			disableWeek = append(disableWeek, v)
		}
	}

	resp := models.StopUpdateReportChapterTypeResp{
		StopDay:     stopDay,
		StopWeek:    stopWeek,
		DisableDay:  disableDay,
		DisableWeek: disableWeek,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 图片上传
// @Description 图片上传接口
// @Param   File   query   file  true       "文件"
// @Success 200 上传成功
// @router /uploadImg [post]
func (this *ReportUploadCommonController) UploadImg() {
	var err error
	defer func() {
		if err != nil {
			fmt.Println("文件上传失败:", err.Error())
			go alarm_msg.SendAlarmMsg("URI:"+this.Ctx.Input.URI()+" 文件上传失败:"+err.Error(), 3)
			//go utils.SendEmail(utils.APPNAME+"失败提醒", "URI:"+this.Ctx.Input.URI()+" 文件上传失败:"+err.Error(), utils.EmailSendToUsers)
		}
	}()
	f, h, err := this.GetFile("file")
	if err != nil {
		return
	}
	ext := path.Ext(h.Filename)
	dateDir := time.Now().Format("20060102")
	uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
	err = os.MkdirAll(uploadDir, 777)
	if err != nil {
		return
	}
	randStr := utils.GetRandStringNoSpecialChar(28)
	fileName := randStr + ext
	fpath := uploadDir + "/" + fileName
	defer f.Close() //关闭上传文件
	err = this.SaveToFile("file", fpath)
	if err != nil {
		return
	}
	//上传到阿里云
	resourceUrl, err := services.UploadAliyunV2(fileName, fpath)
	if err != nil {
		return
	}

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

	item := new(models.Resource)
	item.ResourceUrl = resourceUrl
	item.ResourceType = 1
	item.CreateTime = time.Now()
	newId, err := models.AddResource(item)
	if err != nil {
		return
	}
	resp := new(models.ResourceResp)
	resp.Id = newId
	resp.ResourceUrl = resourceUrl
	this.Data["json"] = map[string]string{"link": resourceUrl}
	this.ServeJSON()
}