package cygx

import (
	"encoding/json"
	"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"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

// 策略时间线
type TacticsTimeLineController struct {
	controllers.BaseAuthController
}

// @Title 新增策略时间线
// @Description 新增策略时间线接口
// @Param	request	body cygx.AddTacticsTimeLineReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /tacticsTimeLine/preserveAndPublish [post]
func (this *TacticsTimeLineController) 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 req cygx.AddTacticsTimeLineReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	publishTime := utils.StrDateToDate(req.PublishTime) //时间字符串格式转时间格式
	timeLineId := req.TimeLineId
	link := req.Link
	articleId, chartId := cygxService.HandleTacticsTimeLinLink(link)
	item := new(cygx.CygxTacticsTimeLine)
	item.PublishTime = publishTime
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.Content = req.Content
	item.Link = req.Link
	item.AdminId = sysUser.AdminId
	if articleId > 0 {
		item.ArticleId = articleId
	}
	if chartId > 0 {
		item.ChartId = chartId
	}
	if timeLineId == 0 {
		//新增
		err = cygx.AddCygxTacticsTimeLine(item)
	} else {
		//更新
		item.TimeLineId = timeLineId
		err = cygx.UpdateCygxTacticsTimeLine(item)
	}
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title 策略时间线列表
// @Description 策略时间线列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   int  false       "发布状态 ，1未发布，1已发布，传2查询所有"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /tacticsTimeLine/list [get]
func (this *TacticsTimeLineController) 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
	}
	resp := new(cygx.GetCygxTacticsTimeLineResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status, _ := this.GetInt("Status")
	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{}
	if status == 0 || status == 1 {
		condition += ` AND art.status = ? `
		pars = append(pars, status)
	}
	total, err := cygx.GetCygxTacticsTimeLineCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY art.publish_time DESC , art.time_line_id DESC "
	list, err := cygx.GetCygxTacticsTimeLineList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var TimeLineIds []int
	var ArticleIds []int
	var ChartIds []int
	for _, v := range list {
		v.PublishTime = utils.TimeRemoveHms(v.PublishTime)
		TimeLineIds = append(TimeLineIds, v.TimeLineId)
		if v.ArticleId > 0 {
			ArticleIds = append(ArticleIds, v.ArticleId)
		}
		if v.ChartId > 0 {
			ChartIds = append(ChartIds, v.ChartId)
		}
	}
	//获取关联的文章map
	articleTitleMap := make(map[int]string)
	if len(ArticleIds) > 0 {
		articleTitleMap = cygxService.GetArticleTitleMapByid(ArticleIds)
	}

	chartTitleMap := make(map[int]string)
	if len(ChartIds) > 0 {
		chartTitleMap = cygxService.GetChartTitleMapByid(ChartIds)
	}
	//获取pv/Uv map
	mapPv, mapUv := cygxService.GetCygxTacticsTimeLineHistoryListMap(TimeLineIds)
	for _, v := range list {
		v.Pv = mapPv[v.TimeLineId]
		v.Uv = mapUv[v.TimeLineId]
		if v.ArticleId > 0 {
			v.Title = articleTitleMap[v.ArticleId]
		}
		if v.ChartId > 0 {
			v.Title = chartTitleMap[v.ChartId]
		}
	}
	detail, err := cygx.GetCygxConfigDetailByCode(utils.CYGX_TACTICS_TIME_LINE_STATUS)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp.Status, _ = strconv.Atoi(detail.ConfigValue)
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  详情
// @Description 获取详情接口
// @Param   TimeLineId   query   int  true       "时间线ID"
// @Success Ret=200 {object} cygx.ActivitySpecialDetail
// @router /tacticsTimeLine/detail [get]
func (this *TacticsTimeLineController) Detail() {
	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
	}
	resp := new(cygx.GetCygxTacticsTimeLineDetailResp)
	timeLineId, _ := this.GetInt("TimeLineId")
	if timeLineId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	detail, err := cygx.GetCygxTacticsTimeLineDetail(timeLineId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	detail.PublishTime = utils.TimeRemoveHms(detail.PublishTime)
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  删除
// @Description 获取详情接口
// @Param	request	body cygx.TacticsTimeLineTimeLineIdReq true "type json string"
// @Success 200 {object} "操作成功"
// @router /tacticsTimeLine/delete [POST]
func (this *TacticsTimeLineController) Delete() {
	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
	}
	var req cygx.TacticsTimeLineTimeLineIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	timeLineId := req.TimeLineId
	if timeLineId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，id不可为空"
		return
	}
	err = cygx.DeleteCygxTacticsTimeLine(timeLineId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

// @Title 发布/取消发布报告
// @Description 发布/取消发布报告接口
// @Param	request	body cygx.TacticsTimeLineTimeLineIdReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /tacticsTimeLine/publishAndcancel [post]
func (this *TacticsTimeLineController) PublishReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.TacticsTimeLineTimeLineIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	timeLineId := req.TimeLineId
	if timeLineId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，id不可为空"
		return
	}
	detail, err := cygx.GetCygxTacticsTimeLineDetail(timeLineId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var status int
	if detail.Status == 0 {
		status = 1
	} else {
		status = 0
	}
	err = cygx.EditCygxTacticsTimeLineStatus(status, timeLineId)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title 一键发布/取消发布报告接口
// @Description 一键发布/取消发布报告
// @Success 200 Ret=200 取消发布成功
// @router /tacticsTimeLine/all/publishAndcancel [post]
func (this *TacticsTimeLineController) PublishCancleReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	detail, err := cygx.GetCygxConfigDetailByCode(utils.CYGX_TACTICS_TIME_LINE_STATUS)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	var status int
	if detail.ConfigValue == "0" {
		status = 1
	} else {
		status = 0
	}
	err = cygx.EditCygxTacticsTimeLineStatusAll(status)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title  下载PV
// @Description 下载PV接口
// @Param   TimeLineId   query   int  true       "时间线ID"
// @router /tacticsTimeLine/PvExport [get]
func (this *TacticsTimeLineController) PvExport() {
	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
	}
	timeLineId, _ := this.GetInt("TimeLineId")
	if timeLineId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND time_line_id = ? `
	pars = append(pars, timeLineId)
	var respList []*cygx.CygxTacticsTimeLineHistory
	//respList := new(cygx.CygxTacticsTimeLineHistory)
	list, err := cygx.GetCygxTacticsTimeLineHistoryList(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(AdminUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}
	//销售查看自己客户，销售组长查看组员
	if resp.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
	}

	//创建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 respList {
		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.Format(utils.FormatDateTime)
	}
	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 = "获取成功"
}
