package cygx

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

// 报告管理
type SearchKeywordController struct {
	controllers.BaseAuthController
}

// @Title 7天热词
// @Description 获取7天热词列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Success 200 {object} cygx.CygxReportMappingListRep
// @router /hostKeyword/list [get]
func (this *SearchKeywordController) HostKeywordList() {
	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"
		return
	}
	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{}
	currentTime := time.Now()
	starTime := currentTime.AddDate(0, 0, -8).Format("2006-01-02") + " 00:00:00"
	endTime := currentTime.AddDate(0, 0, -1).Format("2006-01-02") + " 23:59:59"
	condition += ` AND create_time < ` + "'" + endTime + "'" + `AND create_time > ` + "'" + starTime + "'"
	total, err := cygx.GetSearchKeyWordCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	if total > 60 {
		total = 60
	}
	list, err := cygx.GetSearchKeyWordList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	for k := range list {
		list[k].Sort = (currentIndex-1)*pageSize + k + 1
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(cygx.SearchKeyWordListResp)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 7天热词下载明细
// @Description 获取7天热词下载明细列表接口
// @Success Ret=200
// @router /hostKeyword/download [get]
func (this *SearchKeywordController) HostKeywordDownload() {
	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"
		return
	}

	resp := new(cygx.CanDownload)
	if sysUser.Role == "admin" || sysUser.Role == "researcher" {
		resp.IsCanDownload = true
	}
	var pars []interface{}
	currentTime := time.Now()
	starTime := currentTime.AddDate(0, 0, -7).Format("2006-01-02") + " 00:00:00"
	endTime := currentTime.AddDate(0, 0, -1).Format("2006-01-02") + " 23:59:59"

	var list []*cygx.KeyWordListDownload
	var err error
	listAdmin, err := cygx.GetSearchKeyWordListDownload(starTime, endTime)

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

	if resp.IsCanDownload == false {
		mapMobile, err := cygxService.GetAdminLookUserMobile(sysUser)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,销售对应权限,Err:" + err.Error()
			return
		}
		for _, v := range listAdmin {
			if _, ok := mapMobile[v.Mobile]; ok {
				list = append(list, v)
			}
		}
	} else {
		list = listAdmin
	}

	listComPany, err := cygx.GetCompanyProductMoreOneList(starTime, endTime)
	var strId string
	for _, v := range listComPany {
		strId += strconv.Itoa(v.CompanyId) + ","
	}
	companyProductNameAndSellerList, err := cygx.GetCompanyProductNameAndSellerAllList(pars, strings.TrimRight(strId, ","))
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.Mobile == "" {
			list[k].Mobile = v.Email
		}
		var productNamestr string
		var sellerNamestr string
		for _, v2 := range companyProductNameAndSellerList {
			if v.CompanyId == v2.CompanyId {
				productNamestr += v2.ProductName + "/"
				sellerNamestr += v2.SellerName + "/"
			}
		}
		list[k].ProductName = strings.TrimRight(productNamestr, "/")
		list[k].SellerName = strings.TrimRight(sellerNamestr, "/")
	}
	//创建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 = "客户类型"
	cellF := rowTitle.AddCell()
	cellF.Value = "所属销售"
	cellG := rowTitle.AddCell()
	cellG.Value = "搜索时间"
	for _, item := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.KeyWord
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		cellC := row.AddCell()
		cellC.Value = item.RealName
		cellD := row.AddCell()
		cellD.Value = item.CompanyName
		cellE := row.AddCell()
		cellE.Value = item.ProductName
		cellF := row.AddCell()
		cellF.Value = item.SellerName
		cellG := row.AddCell()
		cellG.Value = item.CreateTime
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "关键词搜索统计列表" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 是否可以下载
// @Description 获取是否可以下载接口
// @Success Ret=200 {object} cygx.CanDownload
// @router /hostKeyword/canDownload [get]
func (this *SearchKeywordController) CnaDownload() {
	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"
		return
	}
	resp := new(cygx.CanDownload)
	if sysUser.Authority == 1 || sysUser.Authority == 3 {
		resp.IsCanDownload = true
	}
	if sysUser.Role == "admin" {
		resp.IsCanDownload = true
	}
	if sysUser.RoleTypeCode == "rai_admin" || sysUser.RoleTypeCode == "ficc_admin" || sysUser.RoleTypeCode == "admin" {
		resp.IsCanDownload = true
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}