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"
	"time"
)

// banner
type BannerCoAntroller struct {
	controllers.BaseAuthController
}

// @Title 图片选择列表
// @Description 图片选择列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} cygx.CygxBannerImgListResp
// @router /banner/img/list [get]
func (this *BannerCoAntroller) ImgList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	resp := new(cygx.CygxBannerImgListResp)
	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{}
	total, err := cygx.GetCygxBannerImgCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY sort DESC  "
	list, err := cygx.GetCygxBannerImgList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	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   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   int  true       "发布状态 -1全部，1；已发布，0：未发布 默认-1"
// @Param   ListType   query   int  true       "ABC哪一列,默认A"
// @Success 200 {object} cygx.CygxBannerImgListResp
// @router /banner/list [get]
func (this *BannerCoAntroller) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	resp := new(cygx.CygxBannerListResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status, _ := this.GetInt("Status", -1)
	listType := this.GetString("ListType", "A")

	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)
	}
	condition += ` AND  art.list_type = ? `
	pars = append(pars, listType)

	total, err := cygx.GetCygxBannerCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY art.sort ASC , art.modify_time DESC   "
	list, err := cygx.GetCygxBannerList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 添加修改banner
// @Description 添加修改banner接口
// @Param	request	body cygx.AddTacticsTimeLineReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /banner/PreserveAndPublish [post]
func (this *BannerCoAntroller) PreserveAndPublish() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.CygxBannerReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	bannerId := req.BannerId
	//var condition string
	//var pars []interface{}
	//
	//condition += ` AND  art.status = 1 `
	//condition += ` AND  art.list_type = ?  AND  art.sort = ?`
	//pars = append(pars, req.ListType, req.Sort)
	//if bannerId > 0 {
	//	condition += ` AND  art.banner_id != ? `
	//	pars = append(pars, bannerId)
	//}
	//
	//total, err := cygx.GetCygxBannerCount(condition, pars)
	//if err != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败，Err:" + err.Error()
	//	return
	//}
	//if total > 0 {
	//	br.Msg = "序号与已发布的已有序号不可重复！"
	//	return
	//}

	item := new(cygx.CygxBanner)
	item.ImgId = req.ImgId
	item.ListType = req.ListType
	item.BannerType = req.BannerType
	item.Title = req.Title
	item.Subtitle = req.Subtitle
	item.Link = req.Link
	item.AdminId = AdminUser.AdminId
	item.Status = 1
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()

	//新的默认排序排到最后
	detailByListTypeMax, err := cygx.GetCygxBannerDetailByListTypeMaxSort(req.ListType)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "保存失败"
		br.ErrMsg = " 获取某一列，最大的排序值失败,Err:" + err.Error()
		return
	}
	if detailByListTypeMax != nil {
		item.Sort = detailByListTypeMax.Sort + 10
	} else {
		item.Sort = 10
	}
	if bannerId == 0 {
		//新增
		err = cygx.AddCygxBanner(item)
	} else {
		//更新
		detail, err := cygx.GetCygxBannerDetail(bannerId)
		if err != nil {
			br.Msg = "详情不存在"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		if detail.Status == 1 {
			item.Sort = detail.Sort
		}
		item.BannerId = bannerId
		err = cygx.UpdateCygxBanner(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   BannerId   query   int  true       "BannerId"
// @Success Ret=200 {object} cygx.ActivitySpecialDetail
// @router /banner/detail [get]
func (this *BannerCoAntroller) 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.GetCygxBannerImgRespDetailResp)
	bannerId, _ := this.GetInt("BannerId")
	if bannerId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	detail, err := cygx.GetCygxBannerDetail(bannerId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	detail.BannerTypeName = cygxService.GetCygxBannerTypeMap()[detail.BannerType]
	BannerImgDetail, err := cygx.GetCygxBannerImgDetail(detail.ImgId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if BannerImgDetail == nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "BannerImgDetail，为空:"
		return
	}

	Uv, err := cygx.GetCygxBannerHistoryCountUv(bannerId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取Uv失败，Err:" + err.Error()
		return
	}
	Pv, err := cygx.GetCygxBannerHistoryCountPv(bannerId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取Pv失败，Err:" + err.Error()
		return
	}
	detail.Uv = Uv
	detail.Pv = Pv
	detail.IndexImg = BannerImgDetail.IndexImg
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 发布/取消发布
// @Description 发布/取消发布报告
// @Param	request	body cygx.CygxBannerIdReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /banner/publishAndcancel [post]
func (this *BannerCoAntroller) PublishReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.CygxBannerIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	bannerId := req.BannerId
	if bannerId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，id不可为空"
		return
	}
	detail, err := cygx.GetCygxBannerDetail(bannerId)
	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.EditCygxBannerStatus(status, bannerId)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title  下载PV
// @Description 下载PV接口
// @Param   BannerId   query   int  true       "BannerId"
// @router /banner/PvExport [get]
func (this *BannerCoAntroller) 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
	}
	bannerId, _ := this.GetInt("BannerId")
	if bannerId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND banner_id = ? `
	pars = append(pars, bannerId)
	var respList []*cygx.CygxBannerHistory
	//respList := new(cygx.CygxTacticsTimeLineHistory)
	list, err := cygx.GetCygxBannerHistoryList(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 = "点击时间"
	cellF := rowTitle.AddCell()
	cellF.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)

		cellF := row.AddCell()
		if item.RegisterPlatform == 1 {
			cellF.Value = "小程序"
		} else {
			cellF.Value = "网页版"
		}
	}
	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 = "获取成功"
}

// @Title 移动顺序
// @Description 移动顺序
// @Param	request	body cygx.CygxBannerIdReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /banner/move [post]
func (this *BannerCoAntroller) Move() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.CygxBannerMoveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	bannerId := req.BannerId
	previousBannerId := req.PreviousBannerId
	nextBannerId := req.NextBannerId
	listType := req.ListType
	if bannerId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，id不可为空"
		return
	}
	if listType != "A" && listType != "B" && listType != "C" {
		br.Msg = "参数错误" + listType
		br.ErrMsg = "移动列数参数错误" + listType
		return
	}
	detailmove, err := cygx.GetCygxBannerDetail(bannerId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if detailmove.Status == 0 {
		br.Msg = "未发布的无法移动"
		return
	}
	//如果是单列就直接移过来
	if previousBannerId+nextBannerId == 0 {
		err = cygx.UpdateCygxBannerlistType(1, bannerId, listType)
		if err != nil {
			br.Msg = "移动失败"
			br.ErrMsg = "获取失败，EditCygxBannerMove Err:" + err.Error()
			return
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "操作成功"
		return
	}

	var sort int
	if previousBannerId > 0 {
		detail, err := cygx.GetCygxBannerDetail(previousBannerId)
		if err != nil {
			br.Msg = "详情不存在"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		listType = detail.ListType
		sort = detail.Sort + 5
	} else {
		detail, err := cygx.GetCygxBannerDetail(nextBannerId)
		if err != nil {
			br.Msg = "详情不存在"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		listType = detail.ListType
		sort = detail.Sort - 5
	}
	err = cygx.UpdateCygxBannerlistType(sort, bannerId, listType)
	//err = cygx.EditCygxBannerMove(sort, bannerId, listType)
	if err != nil {
		br.Msg = "移动失败"
		br.ErrMsg = "获取失败，EditCygxBannerMove Err:" + err.Error()
		return
	}
	go cygxService.UpdateBannerSort(listType)
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
