package yb

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

// ChartController 研报图表统计模块
type ChartCensusController struct {
	controllers.BaseAuthController
}

// GetChartVisitCensusList
// @Title 获取图表阅读统计列表
// @Description 获取图表阅读统计列表
// @Param   ClassifyId  query  int  false  "图表分类ID"
// @Success 200 {object} yb.ChartVisitPageListResp
// @router /chartCensus/getVisitList [get]
func (this *ChartCensusController) GetChartVisitCensusList() {
	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
	}

	classifyId, _ := this.GetInt("ClassifyId")
	order, _ := this.GetInt("Order")
	// 分页
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	total, list, err := yb.GetChartVisitPageList(classifyId, startSize, pageSize, order)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err: " + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := yb.ChartVisitPageListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// GetChartVisitDetailCensusList
// @Title 获取图表阅读详情统计列表
// @Description 获取图表阅读详情统计列表
// @Param   ClassifyId		query	int		true	"图表分类ID"
// @Param   SellerId		query	string	false	"销售IDs,多个用英文逗号拼接"
// @Param   CompanyStatus	query	string	false	"图表分类ID,多个用英文逗号拼接"
// @Param   Keyword			query	string	false	"关键词"
// @Param   Order			query	int		false	"排序 1-查看时间升序 2-查看时间倒序"
// @Success 200 {object} yb.ChartVisitDetailPageListResp
// @router /chartCensus/getVisitDetailList [get]
func (this *ChartCensusController) GetChartVisitDetailCensusList() {
	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
	}

	classifyId, _ := this.GetInt("ClassifyId")
	if classifyId <= 0 {
		br.Msg = "分类ID有误"
		return
	}

	sellerId := this.GetString("SellerId")
	companyStatus := this.GetString("CompanyStatus")
	keyword := this.GetString("Keyword")
	order, _ := this.GetInt("Order")
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	totalList, totalClassify, list, err := getChartVisitDetailCensusData(classifyId, order, pageSize, currentIndex, sellerId, companyStatus, keyword)
	if err != nil {
		br.Msg = "获取失败"
		br.Msg = "获取阅读详情统计失败-" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, totalList)
	resp := yb.ChartVisitDetailPageListResp{
		List:       list,
		VisitTotal: totalClassify,
		Paging:     page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// GetCompanyChartVisitDetail
// @Title 获取用户图表访问明细
// @Description 获取用户图表访问明细
// @Param   ClassifyId	query	int	true	"图表分类ID"
// @Param   UserId		query	int	true	"用户ID"
// @Success 200 {object} yb.UserClassifyChartVisitList
// @router /chartCensus/getCompanyChartVisitDetail [get]
func (this *ChartCensusController) GetCompanyChartVisitDetail() {
	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
	}

	classifyId, _ := this.GetInt("ClassifyId")
	if classifyId <= 0 {
		br.Msg = "分类ID有误"
		return
	}
	userId, _ := this.GetInt("UserId")
	if userId <= 0 {
		br.Msg = "用户ID有误"
		return
	}

	list, err := yb.GetUserClassifyChartVisitList(classifyId, userId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取用户分类阅读统计失败, Err: " + err.Error()
		return
	}

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

// GetChartCompanyAuthCensusList
// @Title 获取图库权限开通客户统计列表
// @Description 获取图库权限开通客户统计列表
// @Param   SellerId		query	string	false	"销售IDs,多个用英文逗号拼接"
// @Param   CompanyStatus	query	string	false	"图表分类ID,多个用英文逗号拼接"
// @Param   Keyword			query	string	false	"关键词"
// @Success 200 {object} yb.CompanyAuthCensusPageListResp
// @router /chartCensus/getCompanyAuthCensusList [get]
func (this *ChartCensusController) GetChartCompanyAuthCensusList() {
	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
	}

	sellerId := this.GetString("SellerId")
	companyStatus := this.GetString("CompanyStatus")
	keyword := this.GetString("Keyword")
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	totalUser, totalItem, list, err := getChartCompanyAuthCensusData(sellerId, companyStatus, keyword, pageSize, currentIndex)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图库权限开通客户统计列表-" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, totalUser)
	resp := yb.CompanyAuthCensusPageListResp{
		List:         list,
		Paging:       page,
		UserTotal:    totalUser,
		CompanyTotal: totalItem.CountCompany,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ExportChartVisitCensusList
// @Title 导出图表阅读统计列表
// @Description 导出图表阅读统计列表
// @Param   ClassifyId  query  int  false  "图表分类ID"
// @Success 200 {object} yb.ChartVisitPageListResp
// @router /chartCensus/exportChartVisitCensusList [get]
func (this *ChartCensusController) ExportChartVisitCensusList() {
	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
	}

	classifyId, _ := this.GetInt("ClassifyId")
	order, _ := this.GetInt("Order")

	_, list, err := yb.GetChartVisitPageList(classifyId, 0, 100000, order)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err: " + err.Error()
		return
	}

	// 生成excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downloadFilePath := 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

	sheel, err := xlsxFile.AddSheet("图库阅读统计")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("图分类")
	titleRow.AddCell().SetValue("阅读量")
	titleRow.AddCell().SetValue("最近一次阅读时间")
	// excel赋值
	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		dataRow.AddCell().SetString(v.ClassifyName)
		dataRow.AddCell().SetString(strconv.Itoa(v.VisitCount))
		dataRow.AddCell().SetString(v.LastVisitTime)
	}
	// 保存excel
	err = xlsxFile.Save(downloadFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "图库统计列表_" + randStr + ".xlsx"

	this.Ctx.Output.Download(downloadFilePath, downloadFileName)
	defer func() {
		os.Remove(downloadFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// ExportChartVisitDetailCensusList
// @Title 导出图表阅读详情统计列表
// @Description 导出图表阅读详情统计列表
// @Param   ClassifyId		query	int		true	"图表分类ID"
// @Param   SellerId		query	string	false	"销售IDs,多个用英文逗号拼接"
// @Param   CompanyStatus	query	string	false	"图表分类ID,多个用英文逗号拼接"
// @Param   Keyword			query	string	false	"关键词"
// @Success 200 {object} yb.ChartVisitPageListResp
// @router /chartCensus/exportChartVisitDetailCensusList [get]
func (this *ChartCensusController) ExportChartVisitDetailCensusList() {
	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
	}

	classifyId, _ := this.GetInt("ClassifyId")
	if classifyId <= 0 {
		br.Msg = "分类ID有误"
		return
	}

	sellerId := this.GetString("SellerId")
	companyStatus := this.GetString("CompanyStatus")
	keyword := this.GetString("Keyword")

	_, _, list, err := getChartVisitDetailCensusData(classifyId, 0, 100000, 0, sellerId, companyStatus, keyword)
	if err != nil {
		br.Msg = "获取阅读详情统计失败"
		br.Msg = "获取阅读详情统计失败-" + err.Error()
		return
	}

	// 生成excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downloadFilePath := 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

	sheel, err := xlsxFile.AddSheet("图库阅读统计详情")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("联系人姓名")
	titleRow.AddCell().SetValue("客户名称")
	titleRow.AddCell().SetValue("所属销售")
	titleRow.AddCell().SetValue("客户状态")
	titleRow.AddCell().SetValue("查看明细")
	titleRow.AddCell().SetValue("最近一次查看时间")
	// excel赋值
	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		dataRow.AddCell().SetString(v.UserName)
		dataRow.AddCell().SetString(v.CompanyName)
		dataRow.AddCell().SetString(v.SellerName)
		dataRow.AddCell().SetString(v.CompanyStatus)
		dataRow.AddCell().SetString(strconv.Itoa(v.VisitCount))
		dataRow.AddCell().SetString(v.LastVisitTime)
	}
	// 保存excel
	err = xlsxFile.Save(downloadFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "图库阅读统计详情_" + randStr + ".xlsx"

	this.Ctx.Output.Download(downloadFilePath, downloadFileName)
	defer func() {
		os.Remove(downloadFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// ExportChartCompanyAuthCensusList
// @Title 导出图库权限开通客户统计列表
// @Description 导出图库权限开通客户统计列表
// @Param   SellerId		query	string	false	"销售IDs,多个用英文逗号拼接"
// @Param   CompanyStatus	query	string	false	"图表分类ID,多个用英文逗号拼接"
// @Param   Keyword			query	string	false	"关键词"
// @Success 200 string "导出成功"
// @router /chartCensus/exportChartCompanyAuthCensusList [get]
func (this *ChartCensusController) ExportChartCompanyAuthCensusList() {
	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
	}

	sellerId := this.GetString("SellerId")
	companyStatus := this.GetString("CompanyStatus")
	keyword := this.GetString("Keyword")

	_, _, list, err := getChartCompanyAuthCensusData(sellerId, companyStatus, keyword, 100000, 0)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图库权限开通客户统计列表-" + err.Error()
		return
	}

	// 生成excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downloadFilePath := 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

	sheel, err := xlsxFile.AddSheet("图库权限开通统计")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	titleRow := sheel.AddRow()
	titleRow.AddCell().SetValue("联系人姓名")
	titleRow.AddCell().SetValue("客户名称")
	titleRow.AddCell().SetValue("所属销售")
	titleRow.AddCell().SetValue("客户状态")
	titleRow.AddCell().SetValue("图库服务期限")
	titleRow.AddCell().SetValue("剩余天数")
	// excel赋值
	for _, v := range list {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)
		dataRow.AddCell().SetString(v.UserName)
		dataRow.AddCell().SetString(v.CompanyName)
		dataRow.AddCell().SetString(v.SellerName)
		dataRow.AddCell().SetString(v.CompanyStatus)
		dataRow.AddCell().SetString(v.StartTime + "~" + v.EndTime)
		dataRow.AddCell().SetString(strconv.Itoa(v.RestDay))
	}
	// 保存excel
	err = xlsxFile.Save(downloadFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "图库权限开通统计_" + randStr + ".xlsx"

	this.Ctx.Output.Download(downloadFilePath, downloadFileName)
	defer func() {
		os.Remove(downloadFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// getChartVisitDetailCensusData 图表阅读详情统计数据
func getChartVisitDetailCensusData(classifyId, order, pageSize, currentIndex int, sellerId, companyStatus, keyword string) (totalList, totalClassify int, list []*yb.ChartVisitDetailList, err error) {
	// 根据筛选项查询客户列表
	var condition string
	var pars []interface{}
	pars = append(pars, classifyId)
	if sellerId != "" {
		condition += ` AND p.seller_id IN (` + sellerId + `) `
	}
	if companyStatus != "" {
		statusArr := strings.Split(companyStatus, ",")
		var splitArr []string
		for _, v := range statusArr {
			splitArr = append(splitArr, `"`+v+`"`)
		}
		queryStatus := strings.Join(splitArr, ",")
		condition += ` AND p.status IN (` + queryStatus + `)`
	}
	if keyword != "" {
		keyword = "%" + keyword + "%"
		condition += ` AND (l.real_name LIKE ? OR c.company_name LIKE ?) `
		pars = append(pars, keyword, keyword)
	}

	// 分页
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	// 获取统计详情列表
	totalList, list, err = yb.GetChartVisitDetailPageList(condition, pars, order, startSize, pageSize)
	if err != nil {
		err = errors.New("获取统计详情列表失败, Err: " + err.Error())
		return
	}
	totalClassify, err = yb.GetClassifyChartTotalVisit(condition, pars)
	if err != nil {
		err = errors.New("获取分类阅读总人数失败, Err: " + err.Error())
		return
	}

	return
}

// getChartCompanyAuthCensusData 图库权限开通客户统计数据
func getChartCompanyAuthCensusData(sellerId, companyStatus, keyword string, pageSize, currentIndex int) (totalUser int, totalItem yb.CountCompanyChartAuth, list []*yb.CompanyAuthCensusList, err error) {
	// 筛选条件
	var condition string
	var pars []interface{}
	if sellerId != "" {
		condition += ` AND d.seller_id IN (` + sellerId + `) `
	}
	if companyStatus != "" {
		statusArr := strings.Split(companyStatus, ",")
		var splitArr []string
		for _, v := range statusArr {
			splitArr = append(splitArr, `"`+v+`"`)
		}
		queryStatus := strings.Join(splitArr, ",")
		condition += ` AND d.status IN (` + queryStatus + `)`
	}
	if keyword != "" {
		keyword = "%" + keyword + "%"
		condition += ` AND b.real_name LIKE ? OR c.company_name LIKE ? `
		pars = append(pars, keyword, keyword)
	}

	// 分页
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	// 获取图库权限开通统计列表
	totalUser, list, err = yb.GetCompanyAuthCensusPageList(condition, pars, startSize, pageSize)
	if err != nil {
		err = errors.New("获取统计详情列表失败, Err: " + err.Error())
		return
	}
	totalItem, err = yb.GetCompanyAuthTotal(condition, pars)
	if err != nil {
		err = errors.New("获取分类阅读总人数失败, Err: " + err.Error())
		return
	}

	if len(list) > 0 {
		// 计算剩余天数
		for _, item := range list {
			startTime, timeErr := time.ParseInLocation(utils.FormatDateTime, item.StartTime, time.Local)
			if timeErr != nil {
				err = errors.New("开始时间转换失败, Err: " + timeErr.Error())
				return
			}
			endTime, timeErr := time.ParseInLocation(utils.FormatDateTime, item.EndTime, time.Local)
			if timeErr != nil {
				err = errors.New("结束时间转换失败, Err: " + timeErr.Error())
				return
			}
			diff := endTime.Sub(startTime) + 1
			item.StartTime = startTime.Format(utils.FormatDate)
			item.EndTime = endTime.Format(utils.FormatDate)
			item.RestDay = int(diff.Hours() / 24)
		}
	}

	return
}
