package purchase

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/tables/company_product"
	"hongze/hongze_yb/services/purchase"
	userService "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
	"strconv"
	"strings"
)

// List 已购列表
func List(c *gin.Context) {
	userinfo := userService.GetInfoByClaims(c)
	// 判断用户是否有已购权限
	if userinfo.CompanyID == 0 {
		response.Fail("无权操作", c)
		return
	}

	// 判断用户状态是否是正常和永续
	companyProduct, err := company_product.GetByCompany2ProductId(userinfo.CompanyID, 1)
	if err != nil {
		response.Fail("无权查看", c)
		return
	}
	// 已购仅付费用户可见
	if ! strings.Contains("永续,正式", companyProduct.Status) {
		response.Fail("无权查看", c)
		return
	}
	list, err := purchase.GetLatestReportAndActivity(userinfo)
	if err !=nil {
		response.Fail(err.Error(), c)
		return
	}

	response.OkData("获取成功", list, c)
}

// Detail 已购详情
func Detail(c *gin.Context)  {
    reqClassifyIdFirst := c.DefaultQuery("classify_id_first", "")
	reqActivityId := c.DefaultQuery("activity_id", "")

	reqPageIndex := c.DefaultQuery("current_index", "1")
	reqPageSize := c.DefaultQuery("page_size", strconv.Itoa(utils.PageSize20))

	pageIndex, err := strconv.Atoi(reqPageIndex)
	if err != nil {
		response.Fail("请输入正确的条数限制", c)
		return
	}

	pageSize, err := strconv.Atoi(reqPageSize)
	if err != nil {
		response.Fail("请输入正确的页码", c)
		return
	}

	if reqClassifyIdFirst == "" && reqActivityId == "" {
		response.Fail("请输入分类序号或者活动序号", c)
		return
	}

	var activityId int
	if reqActivityId != "" {
		activityId, err = strconv.Atoi(reqActivityId)
		if err != nil {
			response.Fail("请输入正确的活动序号", c)
			return
		}
	}

	var classifyIdFirst int
	if reqClassifyIdFirst != ""{
		classifyIdFirst, err = strconv.Atoi(reqClassifyIdFirst)
		if err != nil {
			response.Fail("分类ID格式错误", c)
			return
		}
	}


	// 判断用户是否有已购权限
	userinfo := userService.GetInfoByClaims(c)
	if userinfo.CompanyID == 0 {
		response.Fail("无权操作", c)
		return
	}
	// 判断用户状态是否是正常和永续
	companyProduct, err := company_product.GetByCompany2ProductId(userinfo.CompanyID, 1)
	if err != nil {
		response.Fail("无权查看", c)
		return
	}
	// 已购仅付费用户可见
	if ! strings.Contains("永续,正式", companyProduct.Status) {
		response.Fail("无权查看", c)
		return
	}
	list, err := purchase.GetDetail(userinfo, classifyIdFirst, activityId, pageIndex, pageSize)
	if err != nil {
		response.Fail(err.Error(), c)
		global.LOG.Critical(fmt.Sprintf("userId=%d, errMsg:%s", userinfo.UserID, err.Error()))
		return
	}

	response.OkData("获取成功", list, c)
}