package controllers

import (
	"eta/eta_mini_crm/models"
	"eta/eta_mini_crm/models/response"
	"eta/eta_mini_crm/utils"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/rdlucklib/rdluck_tools/paging"
)

type UserReadRecordController struct {
	BaseAuthController
}

// List
// @Title 用户阅读统计列表
// @Description 用户阅读统计列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Param   SellerId   query   int  true       "销售id"
// @Param   Status   query   string  true       "用户状态"
// @Param   KeyWord   query   string  true       "手机号/邮箱/姓名"
// @Param   IsRegistered   query   string  true       "是否注册"
// @Param   IsSubscribed   query   string  true       "是否关注"
// @Param   RegisterStartDate   query   string  true       "注册开始时间"
// @Param   RegisterEndDate   query   string  true       "注册结束时间"
// @Param   CreateStartDate   query   string  true       "创建开始时间"
// @Param   CreateEndDate   query   string  true       "创建结束时间"
// @Param   SortParam   query   string  true       "排序字段"
// @Param   SortType   query   string  true       "排序方式"
// @Success 200 {object} response.UserListResp
// @router /list [get]
func (this *UserReadRecordController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	sellerIdStr := this.GetString("SellerId")
	status := this.GetString("Status")
	keyWord := this.GetString("KeyWord")
	IsRegistered := this.GetString("IsRegisterd")
	IsSubscribed := this.GetString("IsSubscribed")
	registerStartDate := this.GetString("RegisterStartDate")
	registerEndDate := this.GetString("RegisterEndDate")
	createStartDate := this.GetString("CreateStartDate")
	createEndDate := this.GetString("CreateEndDate")
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	var condition string
	var sortCondition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND (u.real_name LIKE ? OR u.phone LIKE ? OR u.email LIKE ? OR u.company LIKE ?) `
		pars = utils.GetLikeKeywordPars(pars, keyWord, 4)
	}

	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	if sellerIdStr != "" {
		sellerIds := strings.Split(sellerIdStr, ",")
		if len(sellerIds) != 0 {
			condition += ` AND ( `
			for i, id := range sellerIds {
				if i == 0 {
					condition += ` u.seller_id = ? `
					pars = append(pars, id)
				} else {
					condition += ` OR u.seller_id = ? `
					pars = append(pars, id)
				}
			}
			condition += `) `
		}
	}
	if sortParam != "" && sortType != "" {
		sortCondition = " ORDER BY "
		var param, sort string
		switch sortParam {
		case "LastUpdateTime":
			param = "last_update_time"
		case "ReadCnt":
			param = "read_cnt"
		}
		switch sortType {
		case "asc":
			sort = " ASC "
		case "desc":
			sort = " DESC "
		}
		if param != "" && sort != "" {
			sortCondition += param + " " + sort
		} else {
			sortCondition = ""
		}
	}

	switch status {
	case fmt.Sprint(utils.UserStatusNo):
		condition += " AND u.status=? "
		pars = append(pars, 0)
	case fmt.Sprint(1):
		condition += " AND u.status=? "
		pars = append(pars, 2)
	default:
		condition += " AND (u.status=? OR u.status=?) "
		pars = append(pars, 0, 2)
	}
	switch IsRegistered {
	case "是":
		condition += " AND u.is_registered=? "
		pars = append(pars, true)
	case "否":
		condition += " AND u.is_registered=? "
		pars = append(pars, false)
	}
	switch IsSubscribed {
	case "是":
		condition += " AND u.is_subscribed=? "
		pars = append(pars, true)
	case "否":
		condition += " AND u.is_subscribed=? "
		pars = append(pars, false)
	}
	if registerStartDate != "" {
		registerStartTime, er := time.Parse(utils.FormatDate, registerStartDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.register_time>=? "
		registerStartDateStr := registerStartTime.Format(utils.FormatDateTime)
		pars = append(pars, registerStartDateStr)
	}
	if registerEndDate != "" {
		registerEndTime, er := time.Parse(utils.FormatDate, registerEndDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.register_time<=? "
		// 结束时间包含今天
		registerEndTime = registerEndTime.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
		registerEndDateStr := registerEndTime.Format(utils.FormatDateTime)
		pars = append(pars, registerEndDateStr)
	}
	if createStartDate != "" {
		createStartTime, er := time.Parse(utils.FormatDate, createStartDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.create_time>=? "
		createStartDateStr := createStartTime.Format(utils.FormatDateTime)
		pars = append(pars, createStartDateStr)
	}
	if createEndDate != "" {
		createEndTime, er := time.Parse(utils.FormatDate, createEndDate)
		if er != nil {
			br.Msg = "日期格式有误"
			return
		}
		condition += " AND u.create_time<=? "
		// 结束时间包含今天
		createEndTime = createEndTime.Add(23*time.Hour + 59*time.Minute + 59*time.Second)
		createEndDateStr := createEndTime.Format(utils.FormatDateTime)
		pars = append(pars, createEndDateStr)
	}
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize := utils.StartIndex(currentIndex, pageSize)

	total, err := models.GetUserReadCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	userList, err := models.GetUserReadList(condition, sortCondition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "查询用户失败"
		br.Msg = "查询用户失败,系统错误,Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.UserListResp)
	resp.Paging = page
	resp.List = userList

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

// Detail
// @Title 用户阅读记录详情
// @Description 用户阅读记录详情信息
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Param   ChartPermissionIds   query   string  true       "品种列表"
// @Param   ClassifyIds   query   string  true       "品种列表"
// @Success 200 {object} models.LoginResp
// @router /detail [get]
func (this *UserReadRecordController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	UserId, _ := this.GetInt("UserId")
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	chartPermissionids := this.GetString("ChartPermissionIds")
	classifyIds := this.GetString("ClassifyIds")
	if UserId <= 0 {
		br.Msg = "查询用户不存在"
		return
	}
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	} else if pageSize > utils.PageSize100 {
		pageSize = utils.PageSize100
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize := utils.StartIndex(currentIndex, pageSize)
	user, err := models.GetUserById(UserId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "用户不存在或已删除,请刷新页面"
			return
		}
		br.Msg = "查询用户失败"
		br.ErrMsg = "查询用户失败,系统错误,Err:" + err.Error()
		return
	}
	if user == nil {
		br.Msg = "用户不存在或已删除,请刷新页面"
		return
	}
	var condition string
	var pars []interface{}

	if chartPermissionids != "" {
		ids := strings.Split(chartPermissionids, ",")
		if len(ids) != 0 {
			condition += ` AND ( `
			for i, id := range ids {
				if i == 0 {
					condition += ` urp2.chart_permission_id = ? `
					pars = append(pars, id)
				} else {
					condition += ` OR urp2.chart_permission_id = ? `
					pars = append(pars, id)
				}
			}
			condition += `) `
		}
	}
	if classifyIds != "" {
		ids := strings.Split(classifyIds, ",")
		if len(ids) != 0 {
			condition += ` AND ( `
			for i, id := range ids {
				if i == 0 {
					condition += ` classify_id2 = ? `
					pars = append(pars, id)
				} else {
					condition += ` OR classify_id2 = ? `
					pars = append(pars, id)
				}
			}
			condition += `) `
		}
	}

	total, err := models.GetUserReadRecordCountByUserId(UserId, condition, pars)
	if err != nil {
		br.Msg = "查询阅读记录失败"
		br.ErrMsg = "查询阅读记录失败,Err:" + err.Error()
		return
	}
	readList, err := models.GetUserReadRecordByUserId(UserId, condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "查询阅读记录失败"
		br.ErrMsg = "查询阅读记录失败,系统错误,Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(response.UserReadRecordListResp)
	resp.Paging = page
	resp.List = readList

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

// ReadCntChart
// @Title 用户阅读量统计图信息
// @Description 用户阅读量统计图信息
// @Param   ChartPermissionIds   query   string  true       "品种列表"
// @Param   ClassifyIds   query   string  true       "品种列表"
// @Param   StartDate   query   string  true       "开始时间"
// @Param   EndDate   query   string  true       "结束时间"
// @Param   UserId   query   int  true       "用户id"
// @Success 200 {object} models.LoginResp
// @router /readCntChart [get]
func (this *UserReadRecordController) ReadCntChart() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	userId, _ := this.GetInt("UserId")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	chartPermissionIds := this.GetString("ChartPermissionIds")
	classifyIds := this.GetString("ClassifyIds")
	var condition string
	var pars []interface{}

	if chartPermissionIds != "" {
		ids := strings.Split(chartPermissionIds, ",")
		if len(ids) != 0 {
			condition += ` AND ( `
			for i, id := range ids {
				if i == 0 {
					condition += ` urp.chart_permission_id = ? `
					pars = append(pars, id)
				} else {
					condition += ` OR urp.chart_permission_id = ? `
					pars = append(pars, id)
				}
			}
			condition += `) `
		}
	}
	if classifyIds != "" {
		ids := strings.Split(classifyIds, ",")
		if len(ids) != 0 {
			condition += ` AND ( `
			for i, id := range ids {
				if i == 0 {
					condition += ` classify_id2 = ? `
					pars = append(pars, id)
				} else {
					condition += ` OR classify_id2 = ? `
					pars = append(pars, id)
				}
			}
			condition += `) `
		}
	}

	if startDate == "" {
		startDate = time.Now().AddDate(-1, 0, 0).Format(utils.FormatDate)
	}
	if endDate == "" {
		endDate = time.Now().AddDate(0, 0, 1).Format(utils.FormatDate)
	}
	if userId > 0 {
		condition += ` AND ur.user_id = ? `
		pars = append(pars, userId)
	}
	readCnts, err := models.GetStaticReadCnt(condition, pars, startDate, endDate)
	if err != nil {
		br.Msg = "获取阅读统计失败"
		br.ErrMsg = "获取阅读统计失败,系统错误,Err:" + err.Error()
		return
	}

	br.Msg = "查询成功"
	br.Data = readCnts
	br.Ret = 200
	br.Success = true
}

// readPermissionChart
// @Title 用户阅读品种图信息
// @Description 用户阅读品种图信息
// @Param   UserId   query   string  true       "用户id"
// @Success 200 {object} models.LoginResp
// @router /readPermissionChart [get]
func (this *UserReadRecordController) ReadPermissionChart() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	userId, _ := this.GetInt("UserId")

	var condition string
	var pars []interface{}
	if userId > 0 {
		condition += ` AND ur.user_id = ? `
		pars = append(pars, userId)
	}

	permissionCnts, err := models.GetStaticPermissionCnt(condition, pars)
	if err != nil {
		br.Msg = "获取品种阅读统计失败"
		br.ErrMsg = "获取品种阅读统计失败,系统错误,Err:" + err.Error()
		return
	}
	var sum int
	for _, v := range permissionCnts {
		sum += v.Count
	}
	for _, v := range permissionCnts {
		percent := float64(v.Count) / float64(sum) * 100
		percentStr := fmt.Sprintf("%.0f", percent)
		parsedFloat, _ := strconv.ParseFloat(percentStr, 64)
		v.Percent = parsedFloat
	}

	br.Msg = "查询成功"
	br.Data = permissionCnts
	br.Ret = 200
	br.Success = true
}