package talent_service

import (
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"reflect"
	"youngmini_server/app/dao"
	"youngmini_server/app/model/talent_model"
	"youngmini_server/app/utils"
)

type accountExamineState int
const (
	accountExamineWait accountExamineState = iota + 1
	accountExamineSuc
	accountExamineFail
)

type taskStatus int
const (
	 taskStatusNotStart = iota + 1
	 taskStatusInProgress
	 taskStatusComplete
	 taskStatusDelete
)

const taskDetailCacheNamePrefix = "task_cache_"

func GetTaskInfoList(r *ghttp.Request) *TalentHttpResult {

	pageIndex := r.GetQueryInt("idx", -1)
	cntPerPage := r.GetQueryInt("cnt", -1)
	platform := r.Get("platform")
	taskMode := r.Get("mode")
	if pageIndex == -1 || cntPerPage == -1 || cntPerPage == 0 {
		return &TalentHttpResult{Code: -1, Msg: "参数错误"}
	}

	// 如果有平台的过滤条件，则将平台列表保存于platformList
	var platformList []interface{}
	if platform != nil {
		if reflect.TypeOf(platform).Kind() != reflect.Slice {
			return &TalentHttpResult{Code: -2, Msg: "搜索条件平台类型错误"}
		}

		platformList = make([]interface{}, 0)
		platformList = platform.([]interface{})
	}

	// 如果有任务模式的过滤条件，则将过滤条件保存于taskModeList
	var taskModeList []interface{}
	if taskMode != nil {
		if reflect.TypeOf(taskMode).Kind() != reflect.Slice {
			return &TalentHttpResult{Code: -3, Msg: "搜索条件任务模式错误"}
		}

		taskModeList = make([]interface{}, 0)
		taskModeList = taskMode.([]interface{})
	}

	// 构造查询的条件
	startId := pageIndex * cntPerPage
	whereStr := fmt.Sprintf("task_status = %d", taskStatusInProgress)
	if platformList != nil {
		whereStr = whereStr + " and task_platform in ("
		for _, v := range platformList {
			whereStr += v.(string) + ", "
		}

		whereStr = whereStr[0:len(whereStr) - 2]
		whereStr += ")"
	}

	if taskModeList != nil {
		whereStr += " and task_mode in ("
		for _, v := range taskModeList {
			whereStr += v.(string) + ", "
		}

		whereStr = whereStr[0:len(whereStr) - 2]
		whereStr += ")"
	}

	// 判断请求页面是否超过最大页面
	c, err := g.DB().Model(dao.TaskBaseInfo.Table).Fields("task_id").
		Count(whereStr)

	if c <= 0 {
		return &TalentHttpResult{Code: -4, Msg: "has no task", Data: nil}
	}

	maxPage := c / cntPerPage
	if c % cntPerPage > 0 {
		maxPage += 1
	}

	if pageIndex + 1 > maxPage {
		return &TalentHttpResult{Code: -5, Msg: "over max page"}
	}

	var taskSimple = talent_model.SimpleTaskResult{}
	err = g.DB().Model("task_base_info").WithAll().
		Where(whereStr).
		Order("deadline_time DESC, task_id").Limit(startId, cntPerPage).Scan(&taskSimple.TaskInfos)

	if err != nil {
		return &TalentHttpResult{Code: -6, Msg: "查询数据库失败"}
	}

	taskSimple.MaxPage = maxPage

	return &TalentHttpResult{Code: 0, Msg: "success", Data: taskSimple}
}

// GetTaskDetailInfo 获取任务详情
func GetTaskDetailInfo(r *ghttp.Request) *TalentHttpResult {
	tid := r.GetQueryInt("taskid", 0)
	if tid == 0 {
		return &TalentHttpResult{Code: -2, Msg: "parse param error"}
	}

	var taskDetail *talent_model.TaskDetail
	err := g.DB().Model(talent_model.TaskDetail{}).WithAll().
		Where("task_id", tid).Scan(&taskDetail)

	if err != nil {
		return &TalentHttpResult{Code: -3, Msg: "data query failed"}
	}

	// 计算各招募等级的已报名人数
	for _, v := range taskDetail.NeedTalentCount {
		cnt, err1 := g.DB().Model(dao.OrderInfo.Table).Count("task_level_id = ? and order_status > 1", v.TrtId)
		if err1 == nil {
			v.SignupCount = int64(cnt)
		} else {
			v.SignupCount = 0
		}
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: taskDetail}
}

func GetPlatformFansCount(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	pid := r.GetQueryInt("pid", 0)
	if pid == 0 {
		return &TalentHttpResult{Code: -2, Msg: "input pid param"}
	}


	// 如果账号为通过审核则返回空
	rec, err := g.DB().Model(dao.RTalentPlatformTable.Table).
		One("p_id = ? and tid = ?", pid, tid)
	if err != nil {
		return &TalentHttpResult{Code: -3, Msg: "query platform examine info failed"}
	}

	if rec == nil {
		return &TalentHttpResult{Code: -4, Msg: "have no platform account"}
	}

	if rec[dao.RTalentPlatformTable.Columns.ExamineState].Int() == int(accountExamineWait) {
		return &TalentHttpResult{Code: -5, Msg: "platform account waiting examine"}
	}

	if rec[dao.RTalentPlatformTable.Columns.ExamineState].Int() == int(accountExamineFail) {
		return &TalentHttpResult{Code: -6, Msg: "platform account examine failed"}
	}

	rec, err = g.DB().Model(dao.InfoThirdPlatform.Table).
		Fields(dao.InfoThirdPlatform.Columns.PlatformTableName).
		One("platform_id", pid)
	if err != nil || rec == nil {
		return &TalentHttpResult{Code: -7, Msg: "get platform table name failed"}
	}

	fansRec, err := g.DB().Model(rec[dao.InfoThirdPlatform.Columns.PlatformTableName].String()).
		Fields("fans_count").One("talent_id", tid)
	if err != nil {
		return &TalentHttpResult{Code: -8, Msg: "query fans count failed"}
	}

	taskId := r.GetQueryInt("task_id", 0)
	if taskId == 0 {
		return &TalentHttpResult{Code: -9, Msg: "input task id"}
	}

	rec, err = g.DB().Model(dao.OrderInfo.Table).One("task_id = ? and talent_id = ?", taskId, tid)
	if err != nil {
		return &TalentHttpResult{Code: -10, Msg: "query talent signup task info failed"}
	}

	fansCountAndTaskSignupInfo := talent_model.FansCountAndTaskSignupInfo{
		FansCountInfo: fansRec,
		IsSignupTask: 0,
	}

	if rec != nil {
		fansCountAndTaskSignupInfo.IsSignupTask = 1
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: fansCountAndTaskSignupInfo}
}

func GetSignupPageTaskDetail(r *ghttp.Request) *TalentHttpResult {
	tid, err := utils.SessionTalentInfo.GetTalentIdFromSession(r)
	if err != nil {
		return &TalentHttpResult{Code: -1, Msg: "Get talent info failed"}
	}

	taskId := r.GetQueryInt("task_id", 0)
	if taskId == 0 {
		return &TalentHttpResult{Code: -2, Msg: "请输入任务id"}
	}

	addrRec, err := g.DB().Model(dao.TalentDeliveryAddress.Table).One("talent_id = ? and default_tag = 1", tid)
	if err != nil {
		return &TalentHttpResult{Code: -2, Msg: "设置收货地址才可以接任务"}
	}

	var taskDetail *talent_model.SignupPageTaskDetail
	err = g.DB().Model(talent_model.TaskDetail{}).WithAll().Where("task_id", taskId).Scan(&taskDetail)
	if err != nil {
		return &TalentHttpResult{Code: -3, Msg: "data query failed"}
	}

	platRec, err := g.DB().Model(taskDetail.PlatformInfo.PlatformTableName).One("talent_id", tid)
	if err != nil {
		return &TalentHttpResult{Code: -4, Msg: "查询平台信息出错"}
	}

	taskDetail.PlatformDetail = &platRec
	taskDetail.DeliveryAddress = &addrRec

	return &TalentHttpResult{Code: 0, Msg: "success", Data: taskDetail}
}
