package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/services"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
)

// 晨会精华
type MorningMeetingController struct {
	BaseAuthController
}

// @Title 晨会精华汇总列表
// @Description 晨会精华汇总列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /gather/list [get]
func (this *MorningMeetingController) GatherList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(models.CygxMorningMeetingGatherListResp)
	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)
	var condition string
	var pars []interface{}
	condition += ` AND status = 1   AND  meeting_ids != '' `
	total, err := models.GetCygxMorningMeetingGatherCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY publish_time DESC ,id  DESC "
	list, err := models.GetCygxMorningMeetingGatherList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var meetids string
	for _, v := range list {
		meetids += v.MeetingIds + ","
	}
	meetids = strings.TrimRight(meetids, ",")
	mapMeetName := make(map[string]string)
	if meetids != "" {
		pars = make([]interface{}, 0)
		condition = ` 	AND id  IN(` + meetids + `) AND  status = 1  `
		listMeet, err := models.GetCygxMorningMeetingReviewsList(condition, pars, 0, 10000)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
		}
		for _, v := range listMeet {
			mapMeetName[strconv.Itoa(v.Id)] = v.IndustryNames
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	for _, v := range list {
		item := new(models.CygxMorningMeetingGatherResp)
		item.Id = v.Id
		item.Title = v.Title
		sliceMeetingIds := strings.Split(v.MeetingIds, ",")
		for _, vM := range sliceMeetingIds {
			if mapMeetName[vM] != "" {
				item.IndustryName += mapMeetName[vM] + ","
			}
		}
		item.IndustryName = strings.TrimRight(item.IndustryName, ",")
		item.IndustryName = strings.Replace(item.IndustryName, ",", "】,【", -1)
		item.IndustryName = "【" + item.IndustryName + "】"
		resp.List = append(resp.List, item)
	}
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 晨会精华汇总详情
// @Description 晨会精华汇总详情接口
// @Param   Id   query   int  true       "Id"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /gather/detail [get]
func (this *MorningMeetingController) GatherDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	id, _ := this.GetInt("Id")
	resp := new(models.CygxMorningMeetingGatherDetailResp)
	hasPermission, err := services.GetUserhasPermission(user)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户权限信息失败,Err:" + err.Error()
	}
	if user.UserId == 0 {
		hasPermission = 1 //用户未登录(绑定登录信息)的时候也能展示 v12.2.1
	}
	resp.HasPermission = hasPermission
	if hasPermission != 1 {
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	var condition string
	var pars []interface{}
	condition += ` AND status = 1 AND  id = ?  `
	pars = append(pars, id)
	total, err := models.GetCygxMorningMeetingGatherCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if total == 0 {
		br.Msg = "内容不存在，或未发布"
	}
	detail, err := models.GetCygxMorningMeetingGatherById(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var meetids string
	meetids = detail.MeetingIds
	detailResp := new(models.CygxMorningMeetingGatherDetail)
	if meetids != "" {
		pars = make([]interface{}, 0)
		condition = ` 	AND meeting_id  IN(` + meetids + `) `
		listMeet, err := models.GetCygxMorningMeetingReviewChapterList(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()

		}

		var meetingreviewchaptIds []int
		for _, v := range listMeet {
			meetingreviewchaptIds = append(meetingreviewchaptIds, v.Id)
		}
		detailResp.List, err = services.GetCygxMorningMeetingReviewChapterListByIds(meetingreviewchaptIds)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "GetCygxMorningMeetingReviewChapterListByIds，Err:" + err.Error()
		}
	} else {
		detailResp.List = make([]*models.CygxMorningMeetingGatherDetailListResp, 0)
	}
	detailResp.Id = detail.Id
	detailResp.Title = detail.Title
	detailResp.PublishTime = utils.GetTimeDateRemoveYear(detail.PublishTime)
	detailResp.Department = "弘则产品组"
	resp.Detail = detailResp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 晨会精华点击记录
// @Description 晨会精华点击记录接口
// @Param	request	body models.ArticleCollectResp true "type json string"
// @Success 200
// @router /history/add [post]
func (this *MorningMeetingController) SpecialMsg() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请重新登录"
		br.Ret = 408
		return
	}
	var req models.AddCygxMorningMeetingReviewChapterHistoryReq

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

	go services.AddCygxMorningMeetingReviewChapterHistory(user, articleId, sourcePage)
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功！"
}

// @Title 晨会精华汇总日志详情
// @Description 晨会精华汇总日志详情接口
// @Param   LogId   query   int  true       "Id"
// @Success Ret=200 {object} cygx.CygxMorningMeetingReviewLogDetailResp
// @router /log/detail [get]
func (this *MorningMeetingController) LogDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	logId, _ := this.GetInt("LogId")
	logDetail, err := models.GetCygxMorningMeetingReviewLogByLogId(logId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取日志信息失败,Err:" + err.Error()
		return
	}
	meetingId := logDetail.MeetingId
	reviewDetail, err := models.GetMorningMeetingReviewById(meetingId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取晨会信息失败,Err:" + err.Error()
		return
	}
	resp := new(models.CygxMorningMeetingReviewLogDetailResp)
	meetDetail, err := models.GetCygxMorningMeetingReviewChapterDetailByMeetingId(meetingId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	var meetingreviewchaptIds []int
	meetingreviewchaptIds = append(meetingreviewchaptIds, meetDetail.Id)

	respList, err := services.GetCygxMorningMeetingReviewChapterListByIds2(meetingreviewchaptIds)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "GetCygxMorningMeetingReviewChapterListByIds，Err:" + err.Error()
		return
	}

	detailResp := new(models.CygxMorningMeetingReviewLogResp)
	for _, v := range respList {
		detailResp = v
	}

	if logDetail.Operate == "提交审核" {
		detailResp.UserType = 2
	} else {
		detailResp.UserType = 1
	}
	detailResp.Content = logDetail.Content
	detailResp.LogId = logId
	detailResp.Status = reviewDetail.Status
	detailResp.RejectContent = logDetail.Remark
	resp.Detail = detailResp
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 晨会精华汇总审核（通过与驳回）
// @Description 晨会精华汇总审核（通过与驳回）接口
// @Param	request	body models.ReviewLogApproveReq true "type json string"
// @Success 200
// @router /log/approve [post]
func (this *MorningMeetingController) LogApprove() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}

	var req models.ReviewLogApproveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	logId := req.LogId
	status := req.Status
	rejectContent := req.RejectContent
	if status != 1 && status != 3 {
		br.Msg = "操作失败"
		br.ErrMsg = "发布状态错误"
		return
	}
	logDetail, err := models.GetCygxMorningMeetingReviewLogByLogId(logId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取日志信息失败,Err:" + err.Error()
		return
	}
	meetingId := logDetail.MeetingId
	reviewDetail, err := models.GetMorningMeetingReviewById(meetingId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取晨会信息失败,Err:" + err.Error()
		return
	}
	if reviewDetail.Status != 2 {
		br.Msg = "请勿重复审批"
		br.ErrMsg = "请勿重复审批"
		return
	}

	var operate string
	if status == 1 {
		operate = "已通过"
	} else {
		operate = "已驳回"
		if rejectContent == "" {
			br.Msg = "请输入驳回理由"
			return
		}
		logDetail.Remark = rejectContent
	}
	err = models.PublishMorningMeetingReviewById(status, meetingId)
	if err != nil {
		br.Msg = "审核失败"
		br.ErrMsg = "审核失败,Err:" + err.Error()
		return
	}
	go services.AddCygxMorningMeetingReviewLog(logDetail, operate, user.RealName, user.UserId, status) //添加晨会精华日志信息，并发送模版消息
	if status == 1 {
		go services.HandleMorningMeetingReviewPush(meetingId)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 晨会精华汇总审核编辑后提交审核，或通过审核
// @Description 晨会精华汇总审核编辑后提交审核，或通过审核接口
// @Param	request	body models.ReviewLogApproveEditReq true "type json string"
// @Success 200
// @router /log/approve_edit [post]
func (this *MorningMeetingController) LogApproveEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req models.ReviewLogApproveEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	logId := req.LogId
	status := req.Status
	content := req.Content
	if content == "" {
		br.Msg = "内容不能为空"
		return
	}
	if status != 1 && status != 2 {
		br.Msg = "操作失败"
		br.ErrMsg = "发布状态错误"
		return
	}
	logDetail, err := models.GetCygxMorningMeetingReviewLogByLogId(logId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取日志信息失败,Err:" + err.Error()
		return
	}
	meetingId := logDetail.MeetingId
	logDetail.Content = content
	var operate string
	if status == 1 {
		operate = "保存并通过"
	} else {
		operate = "提交审核"
	}
	err = models.UpdateMorningMeetingReviewById(status, meetingId, content)
	if err != nil {
		br.Msg = "审核失败"
		br.ErrMsg = "审核失败,Err:" + err.Error()
		return
	}
	go services.AddCygxMorningMeetingReviewLog(logDetail, operate, user.RealName, user.UserId, status) //添加晨会精华日志信息，并发送模版消息
	if status == 1 {
		go services.HandleMorningMeetingReviewPush(meetingId)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
