package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"time"
)

// 官网试用用户管理
type OfficialUserController struct {
	BaseAuthController
}

// @Title 官网试用用户列表
// @Description 官网试用用户列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Param   SourceType   query   string  true       "申请来源，枚举值：可选范围：'中文官网','英文官网'"
// @Success 200 {object} models.UserTrialApplyListResp
// @router /official/user/list [get]
func (this *OfficialUserController) OfficialUserList() {
	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
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	sourceType := this.GetString("SourceType")
	markGroup := this.GetString("MarkGroup")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	if sourceType == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "请选择类型"
		return
	}

	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{}
	startTime := "2022-01-01"

	condition += `source_type = ? and create_time > ? `
	pars = append(pars, sourceType)
	pars = append(pars, startTime)

	if keyWord != "" {
		condition += ` and (company_name LIKE '%` + keyWord + `%' OR phone LIKE '%` + keyWord + `%' OR email LIKE '%` + keyWord + `%' OR real_name LIKE '%` + keyWord + `%') `
	}
	if markGroup != "" {
		condition += `AND mark_group = `+"'"+markGroup+"'"
	}
	if startDate != "" {
		startDate += " 00:00:00"
		condition += ` AND create_time >= '` + startDate + `' `
	}
	if endDate != "" {
		endDate += " 23:59:59"
		condition += ` AND create_time <= '` + endDate + `' `
	}

	//获取总数据数
	total, err := models.GetOfficialApplyUserListListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := models.GetOfficialApplyUserListList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	lenList := len(list)
	for i := 0; i < lenList; i++ {
		list[i].CreateTimeStr = list[i].CreateTime.Format(utils.FormatDateTime)
		list[i].ModifyTimeStr = list[i].ModifyTime.Format(utils.FormatDateTime)
	}
	page := paging.GetPaging(currentIndex, pageSize, int(total))
	resp := new(models.UserTrialApplyListResp)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 官网试用用户确认
// @Description 官网试用用户确认接口
// @Param   Id   query   int  true       "申请记录id"
// @Success Ret=200 确认成功
// @router /official/user/confirm [post]
func (this *OfficialUserController) OfficialUserConfirm() {
	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 models.UserTrialApplyConfirmReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	id := req.Id

	//查询记录信息，并做初步判断
	info, err := models.GetOfficialApplyUserById(id)
	if err != nil && err.Error() == utils.ErrNoRow() {
		br.Msg = "确认失败"
		br.ErrMsg = "确认失败，记录异常"
		return
	}
	if info.Status != "待处理" {
		br.Msg = "确认失败"
		br.ErrMsg = "确认失败，当前记录状态信息异常，请刷新页面"
		return
	}
	err = models.ConfirmOfficialApplyUser(id, sysUser.AdminId, sysUser.RealName)
	if err != nil {
		br.Msg = "确认失败"
		br.ErrMsg = "确认失败，Err:" + err.Error()
		return
	}
	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   KeyWord   query   string  true       "搜索关键词"
// @Param   SourceType   query   string  true       "申请来源，枚举值：可选范围：'中文官网','英文官网'"
// @Success Ret=200 导出成功
// @router /official/user/list/export [get]
func (this *OfficialUserController) OfficialUserListExport() {
	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")
	sourceType := this.GetString("SourceType")
	if sourceType == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "请选择类型"
		return
	}

	var condition string
	var pars []interface{}
	//管理员才让导出数据
	if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
		br.Msg = "没有权限"
		br.ErrMsg = "没有权限"
		return
	}
	startTime := "2022-01-01"

	condition += `source_type = ? and create_time > ? `
	pars = append(pars, sourceType)
	pars = append(pars, startTime)

	if keyWord != "" {
		condition += ` and (company_name LIKE '%` + keyWord + `%' OR phone LIKE '%` + keyWord + `%' OR email LIKE '%` + keyWord + `%' OR real_name LIKE '%` + keyWord + `%') `
	}

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

	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
	}
	titleRow := sheel.AddRow()
	if sourceType == "中文官网" {
		titleRow.AddCell().SetValue("企业名称")
		titleRow.AddCell().SetValue("姓名")
		titleRow.AddCell().SetValue("手机号/邮箱")
		titleRow.AddCell().SetValue("所属行业")
		titleRow.AddCell().SetValue("申请时间")
		titleRow.AddCell().SetValue("申请品种")

		for _, v := range list {
			dataRow := sheel.AddRow()
			dataRow.SetHeight(20)
			dataRow.AddCell().SetString(v.CompanyName)
			dataRow.AddCell().SetString(v.RealName)
			if v.Phone != "" {
				dataRow.AddCell().SetString(v.Phone)
			} else {
				dataRow.AddCell().SetString(v.Email)
			}
			dataRow.AddCell().SetString(v.Industry)
			dataRow.AddCell().SetString(v.CreateTime.Format(utils.FormatDateTime))
			dataRow.AddCell().SetString(v.ProductInfo)
		}
	} else {
		titleRow.AddCell().SetValue("企业名称")
		titleRow.AddCell().SetValue("姓名")
		titleRow.AddCell().SetValue("邮箱")
		titleRow.AddCell().SetValue("信息")
		titleRow.AddCell().SetValue("发送时间")

		for _, v := range list {
			dataRow := sheel.AddRow()
			dataRow.SetHeight(20)
			dataRow.AddCell().SetString(v.CompanyName)
			dataRow.AddCell().SetString(v.RealName)
			dataRow.AddCell().SetString(v.Email)
			dataRow.AddCell().SetString(v.Message)
			dataRow.AddCell().SetString(v.CreateTime.Format(utils.FormatDateTime))
		}
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
	downloadFileName := "官网试用申请列表_" + sourceType + "_" + randStr + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		_ = os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "导出成功"
}

// @Title 官网试用用户确认
// @Description 官网试用用户确认接口
// @Param   Id   query   int  true       "申请记录id"
// @Success Ret=200 确认成功
// @router /official/user/mark_group [post]
func (this *OfficialUserController) OfficialUserMarkGroup() {
	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 models.UserTrialApplyMarkGroupReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	id := req.Id

	//查询记录信息，并做初步判断
	info, err := models.GetOfficialApplyUserById(id)
	if err != nil && err.Error() == utils.ErrNoRow() {
		br.Msg = "确认失败"
		br.ErrMsg = "确认失败，记录异常"
		return
	}
	if info.Status != "待处理" {
		br.Msg = "确认失败"
		br.ErrMsg = "确认失败，当前记录状态信息异常，请刷新页面"
		return
	}
	err = models.OfficialApplyUserMarkGroup(id, sysUser.AdminId, sysUser.RealName, req.GroupName)
	if err != nil {
		br.Msg = "确认失败"
		br.ErrMsg = "确认失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "标记成功"
	//br.Data = resp
}