package yb

import (
	"encoding/json"
	"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/company"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/request"
	ybResp "hongze/hz_crm_api/models/yb/response"
	ybService "hongze/hz_crm_api/services/yb"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// ActivityRegisterController 研报活动报名模块
type ActivityRegisterController struct {
	controllers.BaseAuthController
}

// List
// @Title 获取活动报名列表
// @Description 获取活动报名列表
// @Param   Keyword   query   string  false       "搜索关键字"
// @Param   StartDate   query   string  false       "活动开始日期，格式：2021-11-09"
// @Param   EndDate   query   string  false       "活动结束日期，格式：2021-11-10"
// @Param	ActivityState	query	int	false	"活动状态，1-未开始 2-进行中 3-已结束"
// @Success 200 {object} []yb.RegisterListResp
// @router /activity_register/list [get]
func (this *ActivityRegisterController) 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
	}

	keyword := this.GetString("Keyword")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	activityState, _ := this.GetInt("ActivityState", 0)

	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)

	condition := ""
	pars := make([]interface{}, 0)

	//关键字
	if keyword != "" {
		condition += ` AND activity_name LIKE '%` + keyword + `%' `
	}
	//活动时间
	if startDate != "" && endDate != "" {
		condition += ` AND start_time >= ? AND end_time <= ?`
		pars = append(pars, startDate+" 00:00:00", endDate+" 23:59:59")
	}
	// 活动状态
	now := time.Now().Format(utils.FormatDateTime)
	if activityState != 0 {
		switch activityState {
		case 2:
			condition += ` AND start_time <= ? AND end_time > ?`
		case 3:
			condition += ` AND start_time < ? AND end_time < ?`
		default:
			// 默认未开始
			condition += ` AND start_time > ? AND end_time > ?`
		}
		pars = append(pars, now, now)
	}
	// 仅展示研究员线下沙龙和合作沙龙
	condition += ` AND first_activity_type_id IN (3,4)`

	// 获取所有的分类
	total, list, err := yb.GetActivityRegisterList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取活动列表失败！"
		br.ErrMsg = "获取活动列表失败，Err:" + err.Error()
		return
	}

	if len(list) > 0 {
		activityIdList := make([]string, 0)
		for _, v := range list {
			activityIdList = append(activityIdList, fmt.Sprint(v.ActivityId))
		}
		//获取报名总人数
		activityRegisterTotalList, tmpErr := yb.GetActivityRegisterTotalListByActivityIds(strings.Join(activityIdList, ","))
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取报名总人数失败，Err:" + tmpErr.Error()
			return
		}

		activityRegisterTotalMap := make(map[int]int)

		for _, activityRegisterTotal := range activityRegisterTotalList {
			activityRegisterTotalMap[activityRegisterTotal.ActivityId] = activityRegisterTotal.Total
		}

		for _, activity := range list {
			if registerPeopleNum, ok := activityRegisterTotalMap[activity.ActivityId]; ok {
				activity.RegisterPeopleNum = registerPeopleNum
			}
		}
	}

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

// RegisterList
// @Title 获取活动报名名单列表
// @Description 获取活动报名名单列表
// @Param   ActivityId   query   int  false       "活动id"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success 200 {object} []yb.RegisterListResp
// @router /activity_register_user/list [get]
func (this *ActivityRegisterController) RegisterList() {
	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
	}

	activityId, _ := this.GetInt("ActivityId", 0)
	if activityId <= 0 {
		br.Msg = "请选择活动"
		br.ErrMsg = "请选择活动，活动id不能为空"
		return
	}

	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)
	//是否导出报表
	isExport, _ := this.GetBool("IsExport")
	if isExport {
		pageSize = 10000
		currentIndex = 1
	}

	// 获取所有的报名名单
	total, list, err := yb.GetActivityRegisterListByActivityId(activityId, startSize, pageSize)
	if err != nil {
		br.Msg = "获取活动列表失败！"
		br.ErrMsg = "获取活动列表失败，Err:" + err.Error()
		return
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := ybResp.RegisterDetailListResp{
		List:   list,
		Paging: page,
	}
	//导出excel
	if isExport {
		activityInfo, tmpErr := yb.GetById(activityId)
		if tmpErr != nil {
			br.Msg = "请选择活动"
			br.ErrMsg = "请选择活动，活动id不能为空"
			return
		}
		RegisterListExport(this, resp, activityInfo)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// RegisterListExport 报名名单导出
func RegisterListExport(this *ActivityRegisterController, resp ybResp.RegisterDetailListResp, activityInfo *yb.Activity) {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	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

	sheel, err := xlsxFile.AddSheet("报名列表")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	sheel.SetColWidth(0, 0, 30)
	sheel.SetColWidth(1, 1, 15)
	sheel.SetColWidth(2, 2, 15)
	sheel.SetColWidth(3, 3, 18)

	//统计数据
	statisticRow := sheel.AddRow()

	cell1 := statisticRow.AddCell()
	cell1.SetStyle(style)
	cell1.SetValue(fmt.Sprint(activityInfo.ActivityName, " - 报名名单"))
	cell1.HMerge = 3
	//表头

	titleRow := sheel.AddRow()
	titleRow.SetHeight(30)

	cellName := titleRow.AddCell()
	cellName.SetStyle(style)
	cellName.SetValue("姓名")

	cellProName := titleRow.AddCell()
	cellProName.SetStyle(style)
	cellProName.SetValue("公司名称")

	cellSellerName := titleRow.AddCell()
	cellSellerName.SetStyle(style)
	cellSellerName.SetValue("所属销售")

	cellTime := titleRow.AddCell()
	cellTime.SetStyle(style)
	cellTime.SetValue("报名时间")

	for _, v := range resp.List {
		dataRow := sheel.AddRow()
		dataRow.SetHeight(20)

		cellDataName := dataRow.AddCell()
		cellDataName.SetStyle(style)
		cellDataName.SetValue(v.RealName)

		cellDataProName := dataRow.AddCell()
		cellDataProName.SetStyle(style)
		cellDataProName.SetValue(v.CompanyName)

		cellDataSellerName := dataRow.AddCell()
		cellDataSellerName.SetStyle(style)
		cellDataSellerName.SetValue(v.SellerName)

		cellDataTime := dataRow.AddCell()
		cellDataTime.SetStyle(style)
		cellDataTime.SetValue(v.CreateTime.Format(utils.FormatDateTime))
	}
	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 = "导出成功"
	return
}

// Add
// @Title 新增用户报名活动
// @Description 新增用户报名活动接口
// @Param	request	body request.AddRegisterReq true "type json string"
// @Success 200 {object} 新增报名成功
// @router /activity_register/add [post]
func (this *ActivityRegisterController) Add() {
	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 request.AddRegisterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	for _, userId := range req.UserIdList {
		_, _, _ = ybService.AddRegister(req.ActivityId, userId, sysUser.AdminId)
		//if err != nil {
		//	br.Msg = "新增活动报名失败！"
		//	if errMsg != "" {
		//		br.Msg = errMsg
		//	}
		//
		//	br.ErrMsg = "新增活动报名失败，Err:" + err.Error()
		//	return
		//}
	}
	msg := "新增活动报名成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// CancelRegister
// @Title 取消用户活动报名
// @Description 取消用户活动报名接口
// @Param	request	body request.CancelRegisterReq true "type json string"
// @Success 200 {object} 取消报名成功
// @router /activity_register/cancel [post]
func (this *ActivityRegisterController) CancelRegister() {
	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 request.CancelRegisterReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ActivityId <= 0 {
		br.Msg = "活动ID异常！"
		br.ErrMsg = "活动ID异常"
		return
	}
	_, err, errMsg := ybService.CancelRegister(req.ActivityId, req.UserId)
	if err != nil {
		br.Msg = "取消报名活动失败！" + errMsg
		br.ErrMsg = "取消报名活动失败，Err:" + err.Error()
		return
	}
	msg := "取消报名成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// UserList
// @Title 查询系统中可以报名的联系人列表
// @Description 查询系统中可以报名的联系人列表接口
// @Param   Keyword   query   string  false       "搜索关键字"
// @Success 200 {object} []company.CompanyActivityUser 用户列表
// @router /user/list [get]
func (this *ActivityRegisterController) UserList() {
	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
	}

	keyword := this.GetString("Keyword")
	if keyword == "" {
		br.Msg = "请输入关键字搜索！"
		br.ErrMsg = "请输入关键字搜索"
		return
	}

	var condition string
	var pars []interface{}
	condition = ` and a.real_name like "%` + keyword + `%" `
	list, err := company.GetNoPotentialCompanyUserList(condition, pars)
	if err != nil {
		br.Msg = "查询失败！"
		br.ErrMsg = "查询失败，Err:" + err.Error()
		return
	}
	for _, v := range list {
		v.Mobile = utils.HideString(v.Mobile, 4)
		v.Email = utils.HideString(v.Email, 4)
	}
	msg := "查询成功"

	br.Ret = 200
	br.Success = true
	br.Data = list
	br.Msg = msg
}
