package cygx

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/services/elastic"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 晨会点评
type MorningMeetingController struct {
	controllers.BaseAuthController
}

// @Title 晨会点评列表
// @Description 活动客户列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  false       "关键词搜索"
// @Param   MeetingTime   query   string  false       "晨会日期"
// @Param   Status   query   string  false       "发布状态，1，已发布，0未发布"
// @Param   PublishSort   query   string  true       "desc:降序，asc 升序（预留）"
// @Success 200 {object} cygx.CygxMorningMeetingReviewsList
// @router /morningMeeting/list [get]
func (this *MorningMeetingController) List() {
	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
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	meetingTimeDate := this.GetString("MeetingTime")
	status := this.GetString("Status")
	var startSize int
	var condition string
	var pars []interface{}

	if status != "" {
		condition += ` AND status = ` + status + ` `
	}

	if keyWord != "" {
		condition += ` AND  ( industry_names LIKE '%` + keyWord + `%' )`
	}

	if meetingTimeDate != "" {
		//meetingTime := utils.StrDateToDate(meetingTimeDate) //时间字符串格式转时间格式
		//meetingTimeString := meetingTime.Format(utils.FormatDateTime)
		condition += ` AND  meeting_time = ? `
		pars = append(pars, meetingTimeDate)
	}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}

	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = utils.StartIndex(currentIndex, pageSize)
	total, err := cygx.GetCygxMorningMeetingReviewsListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	condition += ` ORDER BY publish_time DESC  `
	resp := new(cygx.CygxMorningMeetingReviewsList)
	list, err := cygx.GetCygxMorningMeetingReviewsList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	var meetingIds []int
	for _, item := range list {
		respItem := cygx.CygxMorningMeetingReviewItem{
			Id:            item.Id,
			MeetingTime:   item.MeetingTime.Local().Format(utils.FormatDate),
			CreateTime:    item.CreateTime.Local().Format(utils.FormatDateTime),
			ModifyTime:    item.ModifyTime.Local().Format(utils.FormatDateTime),
			Status:        item.Status,
			PartNums:      item.PartNums,
			IndustryNames: item.IndustryNames,
		}
		if item.Status == 1 {
			respItem.PublishTime = item.PublishTime.Local().Format(utils.FormatDateTime)
		}
		meetingIds = append(meetingIds, item.Id)
		resp.List = append(resp.List, &respItem)
	}
	//PvUv 数量
	mapPv, mapUv := cygxService.GetCygxMorningMeetingReviewChapterHistoryPvUvMap(meetingIds)
	for _, v := range resp.List {
		v.Pv = mapPv[v.Id]
		v.Uv = mapUv[v.Id]
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page

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

// @Title 新增晨会点评
// @Description 新增晨会点评接口
// @Param	request	body cygx.AddMorningMeetingReviewsReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /morningMeeting/preserveAndPublish [post]
func (this *MorningMeetingController) PreserveAndPublish() {
	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 reqList cygx.AddMorningMeetingReviewsReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &reqList)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	meetingTime := utils.StrDateToDate(reqList.MeetingTime) //时间字符串格式转时间格式

	var industryNameslice []string
	for _, item := range reqList.List {
		industryNameslice = append(industryNameslice, item.IndustryName)
	}
	industryNames := strings.Join(industryNameslice, ",")

	if reqList.MeetingId <= 0 {
		//先新增主表
		reviewItem := cygx.CygxMorningMeetingReviews{
			MeetingTime:   meetingTime,
			CreateTime:    time.Now(),
			ModifyTime:    time.Now(),
			PartNums:      len(reqList.List),
			IndustryNames: industryNames,
		}

		if reqList.DoType == 1 {
			reviewItem.PublishTime = time.Now()
			reviewItem.Status = 1
		}

		meetingId, err := cygx.AddCygxMorningMeetingReviews(&reviewItem)
		if err != nil {
			br.Msg = "新增晨报点评失败！"
			br.ErrMsg = "新增晨报点评失败，Err:" + err.Error()
			return
		}

		for _, req := range reqList.List {
			if req.ChartPermissionId <= 0 || req.ChartPermissionName == "" {
				br.Msg = "行业不可为空"
				br.ErrMsg = "行业不可为空"
				return
			}

			if req.IndustryId <= 0 || req.ChartPermissionName == "" {
				br.Msg = "产业不可为空"
				br.ErrMsg = "产业不可为空"
				return
			}

			// 标的ID校验
			industrialSubjectIds := req.IndustrialSubjectIds
			if industrialSubjectIds != "" {
				industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
				for _, v := range industrialSubjectIdList {
					_, err := strconv.Atoi(v)
					if err != nil {
						br.Msg = "参数解析异常！"
						br.ErrMsg = "标的ID不规范，Err:" + err.Error() + industrialSubjectIds
						return
					}
				}
			}
			//解析报告链接中的ID
			var linkArticleId int
			if req.ReportLink != "" {
				linkArticleId, err = cygxService.GetReportLinkToArticleid(req.ReportLink)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "解析报告链接ID失败，Err:" + err.Error()
					return
				}
			}

			item := cygx.CygxMorningMeetingReviewChapter{
				MeetingTime:          meetingTime,
				CreateTime:           time.Now(),
				ModifyTime:           time.Now(),
				IndustryId:           req.IndustryId,
				IndustryName:         req.IndustryName,
				ChartPermissionName:  req.ChartPermissionName,
				ChartPermissionId:    req.ChartPermissionId,
				IndustrialSubjectIds: req.IndustrialSubjectIds,
				MeetingId:            meetingId,
				Content:              req.Content,
				ReportLink:           req.ReportLink,
				LinkArticleId:        linkArticleId,
				Title:                req.Title,
			}
			err := cygx.AddCygxMorningMeetingReviewChapter(&item)
			if err != nil {
				br.Msg = "新增晨报点评章节失败！"
				br.ErrMsg = "新增晨报点评章节失败，Err:" + err.Error()
				return
			}
			go cygxService.GetIndustrialManagementArticleNewPublishData(req.IndustryId)

		}
		br.Ret = 200
		br.Success = true
		if reqList.DoType == 0 {
			br.Msg = "保存成功"
			br.Data = meetingId
		} else {
			for _, item := range reqList.List {
				go services.SendWxMsgWithCygxMorningMeeting(int(meetingId), item.IndustryId, item.IndustryName)
			}
			//添加到首页最新
			listchapter, err := cygx.GetCygxMorningMeetingReviewsListById(int(meetingId))
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取数据失败，Err:" + err.Error()
				return
			}
			for _, itemchapter := range listchapter {
				//go cygxService.UpdateResourceData(itemchapter.Id, "meetingreviewchapt", "add", time.Now().Format(utils.FormatDateTime))
				go cygxService.UpdateMeetingreviewchaptResourceData(itemchapter.Id) //写入首页最新  cygx_resource_data 表
				go elastic.AddComprehensiveMeetingreviewchapt(itemchapter.Id)       //Es添加晨会精华
			}
			br.Msg = "发布成功"
			br.Data = meetingId
		}
	} else {
		//更新
		reviewInfo, err := cygx.GetMorningMeetingReviewById(reqList.MeetingId)
		if err != nil {
			err = errors.New("报告信息有误, Err: " + err.Error())
			return
		}
		if reviewInfo == nil {
			br.Msg = "文章不存在"
			return
		}

		reviewItem := cygx.CygxMorningMeetingReviews{
			Id:            reqList.MeetingId,
			MeetingTime:   meetingTime,
			ModifyTime:    time.Now(),
			PartNums:      len(reqList.List),
			IndustryNames: industryNames,
		}

		if reqList.DoType == 1 {
			reviewItem.PublishTime = time.Now()
			reviewItem.Status = 1
		} else {
			reviewItem.PublishTime = reviewInfo.PublishTime
			reviewItem.Status = reviewInfo.Status
		}

		err = cygx.UpdateCygxMorningMeetingReviews(&reviewItem)
		if err != nil {
			br.Msg = "更新晨报点评失败！"
			br.ErrMsg = "更新晨报点评失败，Err:" + err.Error()
			return
		}
		if reviewInfo.PartNums > len(reqList.List) {
			//有删除
			chapterList, err := cygx.GetCygxMorningMeetingReviewsListById(reqList.MeetingId)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取数据失败，Err:" + err.Error()
				return
			}
			chapterIdMap := make(map[int]int, 0)
			for _, chapter := range reqList.List {
				chapterIdMap[chapter.ChapterId] = chapter.ChapterId
			}
			for _, item := range chapterList {
				if _, ok := chapterIdMap[item.Id]; !ok {
					//删除该id
					err := cygx.DeleteMorningMeetingChapterById(item.Id)
					if err != nil {
						br.Msg = "删除失败"
						br.ErrMsg = "删除章节失败，Err:" + err.Error()
						return
					}
					go elastic.DeleteComprehensiveMeetingreviewchapt(item.Id) //Es删除晨会精华
				}
			}
		}
		for _, req := range reqList.List {
			if req.ChartPermissionId <= 0 || req.ChartPermissionName == "" {
				br.Msg = "行业不可为空"
				br.ErrMsg = "行业不可为空"
				return
			}

			if req.IndustryId <= 0 || req.ChartPermissionName == "" {
				br.Msg = "产业不可为空"
				br.ErrMsg = "产业不可为空"
				return
			}

			// 标的ID校验
			industrialSubjectIds := req.IndustrialSubjectIds
			if industrialSubjectIds != "" {
				industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
				for _, v := range industrialSubjectIdList {
					_, err := strconv.Atoi(v)
					if err != nil {
						br.Msg = "参数解析异常！"
						br.ErrMsg = "标的ID不规范，Err:" + err.Error() + industrialSubjectIds
						return
					}
				}
			}
			//解析报告链接中的ID
			var linkArticleId int
			if req.ReportLink != "" {
				linkArticleId, err = cygxService.GetReportLinkToArticleid(req.ReportLink)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "解析报告链接ID失败，Err:" + err.Error()
					return
				}
			}

			//有可能在编辑时新增了段落
			if req.ChapterId == 0 {
				item := cygx.CygxMorningMeetingReviewChapter{
					MeetingTime:          meetingTime,
					CreateTime:           time.Now(),
					ModifyTime:           time.Now(),
					IndustryId:           req.IndustryId,
					IndustryName:         req.IndustryName,
					ChartPermissionName:  req.ChartPermissionName,
					ChartPermissionId:    req.ChartPermissionId,
					IndustrialSubjectIds: req.IndustrialSubjectIds,
					MeetingId:            int64(reqList.MeetingId),
					Content:              req.Content,
					ReportLink:           req.ReportLink,
					LinkArticleId:        linkArticleId,
					Title:                req.Title,
				}
				err := cygx.AddCygxMorningMeetingReviewChapter(&item)
				if err != nil {
					br.Msg = "新增晨报点评章节失败！"
					br.ErrMsg = "新增晨报点评章节失败，Err:" + err.Error()
					return
				}
			} else {
				item := cygx.CygxMorningMeetingReviewChapter{
					Id:                   req.ChapterId,
					MeetingTime:          meetingTime,
					ModifyTime:           time.Now(),
					IndustryId:           req.IndustryId,
					IndustryName:         req.IndustryName,
					ChartPermissionName:  req.ChartPermissionName,
					ChartPermissionId:    req.ChartPermissionId,
					IndustrialSubjectIds: req.IndustrialSubjectIds,
					MeetingId:            int64(reqList.MeetingId),
					Content:              req.Content,
					ReportLink:           req.ReportLink,
					LinkArticleId:        linkArticleId,
					Title:                req.Title,
				}
				err := cygx.UpdateCygxMorningMeetingReviewChapter(&item)
				if err != nil {
					br.Msg = "编辑晨报点评章节失败！"
					br.ErrMsg = "编辑晨报点评章节失败，Err:" + err.Error()
					return
				}
			}
			go cygxService.GetIndustrialManagementArticleNewPublishData(req.IndustryId)
		}

		for _, item := range reqList.List {
			// 更新产业布局时间 2023-05-22
			var industryIds []int
			industryIds = append(industryIds, item.IndustryId)
			go cygxService.UpdateIndustryLayoutTime(industryIds, false)
		}
		//添加到首页最新
		listchapter, err := cygx.GetCygxMorningMeetingReviewsListById(reqList.MeetingId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		for _, itemchapter := range listchapter {
			go elastic.AddComprehensiveMeetingreviewchapt(itemchapter.Id) //Es添加晨会精华
		}
		br.Ret = 200
		br.Success = true
		if reqList.DoType == 0 {
			br.Msg = "保存成功"
		} else {
			for _, item := range reqList.List {
				go services.SendWxMsgWithCygxMorningMeeting(reqList.MeetingId, item.IndustryId, item.IndustryName)
			}
			for _, itemchapter := range listchapter {
				//go cygxService.UpdateResourceData(itemchapter.Id, "meetingreviewchapt", "add", time.Now().Format(utils.FormatDateTime))
				go cygxService.UpdateMeetingreviewchaptResourceData(itemchapter.Id) //写入首页最新  cygx_resource_data 表
			}
			br.Msg = "发布成功"
		}
	}
}

// @Title 晨会点评列表
// @Description 活动客户列表接口
// @Param   MeetingId   query   int  true       "晨会点评id"
// @Success 200 {object} cygx.ActivityCcustomerTypeList
// @router /morningMeeting/detail [get]
func (this *MorningMeetingController) Detail() {
	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
	}

	meetingId, _ := this.GetInt("MeetingId")

	if meetingId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "晨会点评id有误！"
		return
	}

	list, err := cygx.GetCygxMorningMeetingReviewsListById(meetingId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	reviewItem, err := cygx.GetMorningMeetingReviewById(meetingId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	var resp cygx.CygxMorningMeetingReviewChapterResp
	var meetingTime string
	for _, chapter := range list {
		var subjectItemList []*cygx.IndustrialSubjectItem
		if chapter.IndustrialSubjectIds != "" {
			subjectList, err := cygx.GetIndustrySubjectListByIds(chapter.IndustrialSubjectIds)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取数据失败，Err:" + err.Error()
				return
			}

			for _, subject := range subjectList {
				subjectItem := cygx.IndustrialSubjectItem{
					IndustrialSubjectId: subject.IndustrialSubjectId,
					SubjectName:         subject.SubjectName,
				}
				subjectItemList = append(subjectItemList, &subjectItem)
			}
		}
		meetingTime = chapter.MeetingTime.Local().Format(utils.FormatDate)
		respItem := cygx.CygxMorningMeetingReviewChapterRespItem{
			Id:                    chapter.Id,
			MeetingTime:           chapter.MeetingTime,
			CreateTime:            chapter.CreateTime,
			ModifyTime:            chapter.ModifyTime,
			IndustryId:            chapter.IndustryId,
			IndustryName:          chapter.IndustryName,
			ChartPermissionName:   chapter.ChartPermissionName,
			ChartPermissionId:     chapter.ChartPermissionId,
			IndustrialSubjectList: subjectItemList,
			MeetingId:             chapter.MeetingId,
			Content:               chapter.Content,
			Title:                 chapter.Title,
			ReportLink:            chapter.ReportLink,
		}
		resp.List = append(resp.List, &respItem)
	}
	resp.MeetingTime = meetingTime
	resp.Status = reviewItem.Status

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

// @Title 发布报告接口
// @Description 发布报告
// @Param	request	body cygx.MorningReviewPublishReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /morningMeeting/publish [post]
func (this *MorningMeetingController) PublishReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.MorningReviewPublishReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	reviewIds := req.ReviewIds
	if reviewIds == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，报告id不可为空"
		return
	}

	reviewArr := strings.Split(reviewIds, ",")
	for _, v := range reviewArr {
		vint, err := strconv.Atoi(v)
		if err != nil {
			br.Msg = "参数错误"
			br.ErrMsg = "参数错误,Err:" + err.Error()
			return
		}
		review, err := cygx.GetMorningMeetingReviewById(vint)
		if err != nil {
			br.Msg = "获取晨会点评信息失败"
			br.ErrMsg = "获取晨会点评信息失败,Err:" + err.Error()
			return
		}
		if review == nil {
			br.Msg = "晨会点评不存在"
			return
		}

		var tmpErr error

		if tmpErr = cygx.PublishMorningMeetingReviewById(review.Id); tmpErr != nil {
			br.Msg = "晨会点评发布失败"
			br.ErrMsg = "晨会点评发布失败, Err:" + tmpErr.Error() + ", review_id:" + strconv.Itoa(review.Id)
			return
		}

		list, err := cygx.GetCygxMorningMeetingReviewsListById(vint)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取数据失败，Err:" + err.Error()
			return
		}
		for _, item := range list {
			fmt.Println(item.Id)
			go services.SendWxMsgWithCygxMorningMeeting(vint, item.IndustryId, item.IndustryName)
			//go cygxService.UpdateResourceData(item.Id, "meetingreviewchapt", "add", time.Now().Format(utils.FormatDateTime))
			go cygxService.UpdateMeetingreviewchaptResourceData(item.Id) //写入首页最新  cygx_resource_data 表
			go elastic.AddComprehensiveMeetingreviewchapt(item.Id)       //Es添加晨会精华
		}
	}

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

// @Title 取消发布报告接口
// @Description 取消发布报告
// @Param	request	body cygx.MorningReviewPublishCancelReq true "type json string"
// @Success 200 Ret=200 取消发布成功
// @router /morningMeeting/publish/cancel [post]
func (this *MorningMeetingController) PublishCancleReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.MorningReviewPublishCancelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReviewId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，晨会id不可为空"
		return
	}
	err = cygx.PublishCancelMorningMeetingReview(req.ReviewId)
	if err != nil {
		br.Msg = "取消发布失败"
		br.ErrMsg = "取消发布失败,Err:" + err.Error()
		return
	}

	list, err := cygx.GetCygxMorningMeetingReviewsListById(req.ReviewId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	for _, item := range list {
		//go cygxService.UpdateResourceData(item.Id, "meetingreviewchapt", "delete", time.Now().Format(utils.FormatDateTime))
		go cygxService.UpdateMeetingreviewchaptResourceData(item.Id) //写入首页最新  cygx_resource_data 表
		go elastic.DeleteComprehensiveMeetingreviewchapt(item.Id)    //Es删除晨会精华
	}
	var condition string
	var pars []interface{}
	condition += ` AND meeting_ids  like '%` + strconv.Itoa(req.ReviewId) + `%'  `

	listMeetingGather, err := cygx.GetCygxMorningMeetingGatherList(condition, pars, 0, 9999)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	if len(listMeetingGather) > 0 {
		var meetingGatherId int
		//var middelete string
		var meetingsliceId []string
		for _, v := range listMeetingGather {
			sliceId := strings.Split(v.MeetingIds, ",")
			for _, mid := range sliceId {
				if mid == strconv.Itoa(req.ReviewId) {
					meetingGatherId = v.Id
					meetingsliceId = sliceId
				}
			}
		}
		var newMeetingIds string
		if meetingGatherId > 0 {
			for _, v := range meetingsliceId {
				if strconv.Itoa(req.ReviewId) == v {
					continue
				}
				newMeetingIds += v + ","
			}
			newMeetingIds = strings.TrimRight(newMeetingIds, ",")
			err = cygx.UpdateCygxMorningMeetingGather(newMeetingIds, meetingGatherId)
			if err != nil {
				br.Msg = "取消发布失败"
				br.ErrMsg = "取消发布失败,Err:" + err.Error()
				return
			}
		}
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "取消发布成功"
}

// @Title 删除报告接口
// @Description 删除报告
// @Param	request	body cygx.MorningReviewDeleteReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /morningMeeting/delete [post]
func (this *MorningMeetingController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.MorningReviewDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ReviewId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，报告id不可为空"
		return
	}

	if err := cygx.DeleteMorningReviewAndChapter(req.ReviewId); err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除报告失败, Err: " + err.Error()
		return
	}

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

// @Title  下载PV
// @Description 下载PV接口
// @Param   MeetingId   query   int  true       "晨会点评id"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @router /morningMeeting/list_pv [get]
func (this *MorningMeetingController) ListPv() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	meetingId, _ := this.GetInt("MeetingId")
	if meetingId < 1 {
		br.Msg = "请输入晨会ID"
		return
	}
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	var condition string
	var pars []interface{}
	condition = ` AND meeting_id = ?  ORDER BY id DESC  `
	pars = append(pars, meetingId)
	var respList []*cygx.CygxMorningMeetingReviewChapterHistoryResp

	list, err := cygx.GetCygxMorningMeetingReviewChapterHistoryList(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	var isCanDownload bool
	adminInfo, errAdmin := system.GetSysUserById(AdminUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		isCanDownload = true
	}
	//销售查看自己客户，销售组长查看组员
	if isCanDownload == false {
		mapMobile, err := cygxService.GetAdminLookUserMobile(adminInfo)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,销售对应权限，Err:" + err.Error()
			return
		}
		for _, v := range list {
			if _, ok := mapMobile[v.Mobile]; ok {
				respList = append(respList, v)
			}
		}
	} else {
		respList = list
	}
	resp := cygx.CygxMorningMeetingReviewChapterHistoryResptListResp{
		List: list,
	}
	//导出excel
	if isExport {
		MorningMeetingHistoryListExport(this, resp, br)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp

}

// MorningMeetingHistoryListExport 导出Excel
func MorningMeetingHistoryListExport(this *MorningMeetingController, resp cygx.CygxMorningMeetingReviewChapterHistoryResptListResp, br *models.BaseResponse) {
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("阅读明细")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "手机号"
	cellC := rowTitle.AddCell()
	cellC.Value = "公司名称"
	cellD := rowTitle.AddCell()
	cellD.Value = "所属权益销售"
	cellE := rowTitle.AddCell()
	cellE.Value = "阅读时间"

	for _, item := range resp.List {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		cellC := row.AddCell()
		cellC.Value = item.CompanyName
		cellD := row.AddCell()
		cellD.Value = item.SellerName
		cellE := row.AddCell()
		cellE.Value = item.CreateTime
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	downloadFileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}
