package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/day_new"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"html"
	"strconv"
	"strings"
	"time"
)

type DayNewController struct {
	BaseAuthController
}

// List
// @Title 每日资讯列表
// @Description 每日资讯列表
// @Success 200 {object} models.WeworkMsgListResp
// @router /day_new/list [get]
func (this *DayNewController) List() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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 startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	cond := " and is_add = 0 and is_delete = 0"
	var pars []interface{}
	total, list, e := day_new.GetWeworkMsgList(cond, pars, startSize, pageSize)
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取消息列表失败, Err: " + e.Error()
		return
	}

	// 查询消息发送人
	userIds := ""
	extendUserIds := ""
	userNameMap := make(map[string]string, 0)
	ExtendUserNameMap := make(map[string]string, 0)
	for _, v := range list {
		if v.From != "" {
			if len(v.From) > 10 && strings.HasPrefix(v.From, "wm") {
				extendUserIds += `"` + v.From + `",`
			} else {
				userIds += `"` + v.From + `",`
			}
		}
	}

	if userIds != "" {
		userIds = strings.Trim(userIds, ",")
		users, err := day_new.GetWeworkUserByUserIds(userIds)
		if err != nil {
			br.Msg = "查询企业员工信息失败"
			br.ErrMsg = "查询企业员工信息失败, Err: " + err.Error()
			return
		}
		for _, v := range users {
			userNameMap[v.WwUserId] = v.WwNickName
		}
	}

	if extendUserIds != "" {
		extendUserIds = strings.Trim(extendUserIds, ",")
		users, err := day_new.GetWeworkUserByExtendUserIds(extendUserIds)
		if err != nil {
			br.Msg = "查询企业员工信息失败"
			br.ErrMsg = "查询企业员工信息失败, Err: " + err.Error()
			return
		}
		for _, v := range users {
			ExtendUserNameMap[v.WwExtendUserId] = v.WwNickName
		}
	}

	respList := make([]*day_new.WeworkMsgListItem, 0)
	for _, v := range list {
		tmp := &day_new.WeworkMsgListItem{
			MsgId:      v.MsgId,
			Content:    v.Content,
			ContentEn:  v.ContentEn,
			CreateTime: v.CreateTime.Format(utils.FormatDateTime),
			IsAdd:      v.IsAdd,
			IsDelete:   v.IsDelete,
			ModifyTime: v.ModifyTime.Format(utils.FormatDateTime),
			MsgTime:    time.Unix(int64(v.MsgTime/1e3), 0).Format(utils.FormatDateTime),
		}
		if len(v.From) > 10 && strings.HasPrefix(v.From, "wm") {
			if name, ok := ExtendUserNameMap[v.From]; ok {
				tmp.FromName = name
			}
		} else {
			if name, ok := userNameMap[v.From]; ok {
				tmp.FromName = name
			}
		}
		respList = append(respList, tmp)
	}
	//查询上次更新时间
	lastLog, err := day_new.GetLasReqLog()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "查询上次刷新时间失败"
		br.ErrMsg = "查询上次刷新时间失败, Err: " + err.Error()
		return
	}
	var lastUpdateTime string
	if err == nil {
		lastUpdateTime = lastLog.CreateTime.Format(utils.FormatDateTime)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &day_new.WeworkMsgListResp{
		Paging:         page,
		List:           respList,
		LastUpdateTime: lastUpdateTime,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// RefreshMsg
// @Title 手动刷新企业微信群消息
// @Description 手动刷新
// @router /day_new/refresh [get]
func (this *DayNewController) RefreshMsg() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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
	}
	err := services.DayNewWeworkMsgRefresh()
	if err != nil {
		br.Msg = "刷新失败, " + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "刷新成功"
}

// TranslateContent
// @Title 手动翻译内容
// @Description 手动翻译内容
// @router /day_new/translate [get]
func (this *DayNewController) TranslateContent() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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
	}
	err := services.DayNewTranslateContent()
	if err != nil {
		br.Msg = "翻译失败，" + err.Error()
		return
	}

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

// Delete
// @Title 删除企业微信消息
// @Description 删除企业微信消息
// @Param	request	body day_new.DeleteWeworkMsgReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /day_new/delete [post]
func (this *DayNewController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req day_new.DeleteWeworkMsgReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.MsgId == "" {
		br.Msg = "请选择要删除的消息"
		return
	}
	_, err = day_new.GetWeworkMsgByMsgId(req.MsgId)
	if err != nil {
		br.Msg = "消息不存在"
		return
	}

	err = day_new.DeleteWeworkMsgByMsgId(req.MsgId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}

// EditContentEn
// @Title 编辑英文翻译内容
// @Description 编辑英文翻译内容
// @Param	request	body day_new.EditWeworkMsgContentReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /day_new/edit_content_en [post]
func (this *DayNewController) EditContentEn() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req day_new.EditWeworkMsgContentReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.MsgId == "" {
		br.Msg = "请选择要编辑的消息"
		return
	}
	if req.ContentEn == "" {
		br.Msg = "请输入翻译后的内容"
		return
	}
	_, err = day_new.GetWeworkMsgByMsgId(req.MsgId)
	if err != nil {
		br.Msg = "消息不存在"
		return
	}

	err = day_new.UpdateContentEnByMsgId(req.ContentEn, req.MsgId)
	if err != nil {
		br.Msg = "更新失败"
		br.ErrMsg = "更新失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "更新成功"
}

// @Title 新增英文报告接口
// @Description 新增英文报告接口
// @Param	request	body day_new.AddEnglishReportReq true "type json string"
// @Success 200 {object}
// @router /day_new/add_report [post]
func (this *DayNewController) AddReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	/*var req day_new.AddEnglishReportReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	//校验标题和分类
	if req.ClassifyIdFirst == 0 {
		br.Msg = "报告分类不能为空"
		return
	}
	if req.ClassifyNameFirst == "" {
		br.Msg = "报告分类不能为空"
		return
	}

	if req.Title == "" {
		br.Msg = "报告标题不能为空"
		return
	}

	if req.Author == "" {
		br.Msg = "作者不能为空"
		return
	}
	if req.Frequency == "" {
		br.Msg = "频度不能为空"
		return
	}*/
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	dayNewDefault, err := day_new.GetDayNewDefault()
	if err != nil {
		br.Msg = "获取默认值失败"
		br.ErrMsg = "获取默认值失败, Err: " + err.Error()
		return
	}

	overview := dayNewDefault.Overview
	var contentSub string
	var content string
	var msgIds string
	// 整理报告内容
	{
		var cond string
		var pars []interface{}
		cond = " and is_delete = 0 and is_add = 0"
		msgList, e := day_new.GetWeworkMsgByCondition(cond, pars)
		if e != nil {
			br.Msg = "获取消息列表失败"
			br.ErrMsg = "获取消息列表失败, Err: " + e.Error()
			return
		}
		if len(msgList) == 0 {
			br.Msg = "生成失败，列表无内容"
			return
		}
		for _, v := range msgList {
			if v.ContentEn == "" {
				br.Msg = "生成失败，列表未全部完成英文翻译"
				return
			}

			content += `<p>` + time.Unix(v.MsgTime/1e3, 0).Format(utils.FormatDateTimeMinute) + ` ` + v.ContentEn + `</p></br>`
			msgIds += `"` + v.MsgId + `",`
		}

		if content != "" {
			contentSub, err = services.GetReportContentSub(content)
			if err != nil {
				go alarm_msg.SendAlarmMsg("ContentSub 失败，Err:"+err.Error(), 3)
			}
		}
	}

	maxStage, err := models.GetEnglishReportStage(dayNewDefault.ClassifyIdSecond, dayNewDefault.ClassifyIdThird)
	if err != nil {
		br.Msg = "期数获取失败！"
		br.ErrMsg = "期数获取失败，Err:" + err.Error()
		return
	}

	item := new(models.EnglishReport)
	item.AddType = 1                                      // 新增方式：1:新增报告，2:继承报告
	item.ClassifyIdFirst = dayNewDefault.ClassifyIdSecond // 报告表中的id_first实际为二级ID
	item.ClassifyNameFirst = dayNewDefault.ClassifyNameSecond
	item.ClassifyIdSecond = dayNewDefault.ClassifyIdThird // 报告表中的id_second实际为三级ID
	item.ClassifyNameSecond = dayNewDefault.ClassifyNameThird
	item.Title = dayNewDefault.Title
	item.Abstract = dayNewDefault.Abstract
	item.Author = dayNewDefault.Author
	item.Frequency = dayNewDefault.Frequency
	item.State = 1 //状态：1:未发布，2:已发布
	item.Content = html.EscapeString(content)
	item.Stage = maxStage + 1
	item.ContentSub = html.EscapeString(contentSub)
	item.CreateTime = time.Now().Format(utils.FormatDateTime)
	item.ModifyTime = time.Now()
	item.Overview = overview
	item.AdminId = sysUser.AdminId
	item.AdminRealName = sysUser.RealName
	newReportId, err := models.AddEnglishReport(item)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}

	reportCode := utils.MD5(strconv.Itoa(int(newReportId)))
	//修改唯一编码
	{
		go models.ModifyEnglishReportCode(newReportId, reportCode)
	}

	//更新消息状态为已生成报告
	if msgIds != "" {
		msgIds = strings.Trim(msgIds, ",")
		err = day_new.UpdateWeworkMsgIsAdd(msgIds, newReportId)
		if err != nil {
			br.Msg = "更新消息状态失败"
			br.ErrMsg = "更新消息状态失败,Err:" + err.Error()
			return
		}
	}

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

// ReportDefault
// @Title 转报告默认设置
// @Description 转报告默认设置
// @Success 200 {object} models.WeworkMsgListResp
// @router /day_new/report_default [get]
func (this *DayNewController) ReportDefault() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	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
	}

	dayNewDefault, err := day_new.GetDayNewDefault()
	if err != nil {
		br.Msg = "获取默认值失败"
		br.ErrMsg = "获取默认值失败, Err: " + err.Error()
		return
	}
	defaultReport := &day_new.DayNewReportDefaultResp{
		ClassifyIdFirst:    dayNewDefault.ClassifyIdFirst,
		ClassifyNameFirst:  dayNewDefault.ClassifyNameFirst,
		ClassifyIdSecond:   dayNewDefault.ClassifyIdSecond,
		ClassifyNameSecond: dayNewDefault.ClassifyNameSecond,
		ClassifyIdThird:    dayNewDefault.ClassifyIdThird,
		ClassifyNameThird:  dayNewDefault.ClassifyNameThird,
		Title:              dayNewDefault.Title,
		Abstract:           dayNewDefault.Abstract,
		Author:             dayNewDefault.Author,
		Frequency:          dayNewDefault.Frequency,
		Overview:           dayNewDefault.Overview,
	}

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

// ReportDefaultSave
// @Title 保存-转报告默认设置
// @Description 保存-转报告默认设置
// @Param	request	body day_new.EnglishReportDefaultSaveReq true "type json string"
// @Success 200 {object}
// @router /day_new/report_default/save [post]
func (this *DayNewController) ReportDefaultSave() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req day_new.EnglishReportDefaultSaveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	//校验标题和分类
	if req.ClassifyIdFirst == 0 {
		br.Msg = "报告分类不能为空"
		return
	}
	if req.ClassifyNameFirst == "" {
		br.Msg = "报告分类不能为空"
		return
	}

	if req.Title == "" {
		br.Msg = "报告标题不能为空"
		return
	}

	if req.Author == "" {
		br.Msg = "作者不能为空"
		return
	}
	if req.Frequency == "" {
		br.Msg = "频度不能为空"
		return
	}

	if req.Abstract == "" {
		br.Msg = "摘要不能为空"
		return
	}

	if req.Overview == "" {
		br.Msg = "概述不能为空"
		return
	}
	item := new(day_new.DayNewDefault)
	item.ClassifyIdFirst = req.ClassifyIdFirst
	item.ClassifyNameFirst = req.ClassifyNameFirst
	item.ClassifyIdSecond = req.ClassifyIdSecond
	item.ClassifyNameSecond = req.ClassifyNameSecond
	item.ClassifyIdThird = req.ClassifyIdThird
	item.ClassifyNameThird = req.ClassifyNameThird
	item.Title = req.Title
	item.Abstract = req.Abstract
	item.Author = req.Author
	item.Frequency = req.Frequency
	item.ModifyTime = time.Now().Format(utils.FormatDateTime)
	item.Overview = req.Overview

	exist, err := day_new.GetDayNewDefault()
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			item.CreateTime = time.Now().Format(utils.FormatDateTime)
			err = day_new.AddDayNewDefault(item)
			if err != nil {
				br.Msg = "保存默认值失败"
				br.ErrMsg = "保存默认值失败, Err: " + err.Error()
				return
			}
		} else {
			br.Msg = "获取默认值失败"
			br.ErrMsg = "获取默认值失败, Err: " + err.Error()
			return
		}
	} else {
		item.Id = exist.Id
		ups := []string{"ClassifyIdFirst", "ClassifyNameFirst", "ClassifyIdSecond", "ClassifyNameSecond", "Title", "Abstract", "Author", "Frequency", "Overview", "ModifyTime", "ClassifyIdThird", "ClassifyNameThird"}
		err = item.Update(ups)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
}
