package db

import (
	"context"
	"errors"
	"fmt"
	"github.com/issue9/conv"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
)

func GetRecruittime(ctx context.Context, request http_model.GetRecruitTimeRequest) (*http_model.GetRecruitTimeResponse, error) {
	db := GetReadDB(ctx)
	var info gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).Find(&info).Error
	var result http_model.GetRecruitTimeResponse
	if err != nil {
		return &result, err
	}
	result.RecruitTime = info.RecruitDdl.Format("2006-01-02 15:04:05")
	return &result, nil
}

func GetTalentstatusCount(db *gorm.DB, request http_model.GetTalentstatusNumRequest, status int) (int64, error) {
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = ?", request.ProjectId, status)

	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return 0, err
	}
	return total, nil
}

func GetTalentstatusNum(db *gorm.DB, request http_model.GetTalentstatusCountRequest, status int) (int64, error) {
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_stage = ?", request.ProjectId, status)
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return 0, err
	}
	return total, nil
}

func GetTalentstatusCountNum(ctx context.Context, request http_model.GetTalentstatusCountRequest) (*http_model.GetTalentstatusCountResponse, error) {
	db := GetReadDB(ctx)
	var unoperatenum, agreetalentnum, refusetalentnum int64
	unoperatenum, _ = GetTalentstatusNum(db, request, request.TaskStage)
	agreetalentnum, _ = GetTalentstatusNum(db, request, request.TaskStage+1)
	refusetalentnum, _ = GetTalentstatusNum(db, request, request.TaskStage+2)
	count := &http_model.GetTalentstatusCountResponse{
		UnoperateTalentnum: unoperatenum,
		AgreeTalentnum:     agreetalentnum,
		RefuseTalentnum:    refusetalentnum,
	}
	return count, nil
}

func GetTalentstatusNumCount(ctx context.Context, request http_model.GetTalentstatusNumRequest) (*http_model.GetTalentStatusNumResponse, error) {
	db := GetReadDB(ctx)
	var unoperatenum, agreetalentnum, refusetalentnum int64
	unoperatenum, _ = GetTalentstatusCount(db, request, 1)
	agreetalentnum, _ = GetTalentstatusCount(db, request, 2)
	refusetalentnum, _ = GetTalentstatusCount(db, request, 3)
	count := &http_model.GetTalentStatusNumResponse{
		UnoperateTalentnum: unoperatenum,
		AgreeTalentnum:     agreetalentnum,
		RefuseTalentnum:    refusetalentnum,
	}
	return count, nil
}

func GetProjecttaskList(ctx context.Context, request http_model.GetTaskListRequest) (*http_model.GetTaskListData, error) {
	db := GetReadDB(ctx)
	var projecrtaskinfo []gorm_model.YoungeeTaskInfo
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = ?", request.ProjectId, request.CoopType)
	var projectinfo gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).First(&projectinfo).Error
	if err != nil {
		return &http_model.GetTaskListData{}, err
	}
	// 构建查询条件
	if request.FeeFrom != nil {
		query = query.Where("fee_form = ?", request.FeeFrom)
	}
	if request.Type != nil {
		switch *request.Type {
		case 1:
			query = query.Where("supplier_id = 0 AND supplier_status = 0")
		case 2:
			query = query.Where("supplier_id !=0 AND supplier_status = 2")
		}
	}
	if request.Others != "" {
		query = query.Where("talent_name LIKE ? OR s_operate_name LIKE ?", "%"+request.Others+"%", "%"+request.Others+"%")
	}
	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 添加分页逻辑
	pageSize := request.PageSize
	if pageSize == 0 {
		pageSize = 10
	}
	pageNum := request.PageNum
	if pageNum == 0 {
		pageNum = 1
	}
	offset := (pageNum - 1) * pageSize

	// 处理多字段排序逻辑
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			field := request.SortField[i]
			order := request.SortOrder[i]
			switch field {
			case "fansnum":
				if order == "asc" {
					query = query.Order("fans_num asc")
				} else {
					query = query.Order("fans_num desc")
				}
			case "voteavg":
				if order == "asc" {
					query = query.Order("vote_avg asc")
				} else {
					query = query.Order("vote_avg desc")
				}
			case "commentavg":
				if order == "asc" {
					query = query.Order("commit_avg asc")
				} else {
					query = query.Order("commit_avg desc")
				}
			case "collectnum":
				if order == "asc" {
					query = query.Order("collect_num asc")
				} else {
					query = query.Order("collect_num desc")
				}
			}
		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("task_status asc").Order("task_stage asc")
	}
	// 执行分页查询
	if err := query.Offset(offset).Limit(pageSize).Find(&projecrtaskinfo).Error; err != nil {
		return nil, err
	}

	taskInfoPointers := make([]*http_model.TaskInfo, 0, len(projecrtaskinfo))
	for _, task := range projecrtaskinfo {
		var Time time.Time
		switch request.CoopType {
		case 1:
			Time = task.CreateDate
		case 2:
			Time = task.SelectDate //2 signedtime
		case 3:
			Time = task.CompleteDate
		}
		var listtime, stageintro string
		switch task.TaskStage {
		case 4:
			{
				listtime = task.SelectDate.Format("2006-01-02 15:04:05")
				stageintro = "执行开始时间"
			}
		case 5:
			{
				listtime = task.DeliveryDate.Format("2006-01-02 15:04:05")
				stageintro = "商家寄样时间"
			}
		case 9:
			{
				listtime = task.CurBreakAt.Format("2006-01-02 15:04:05")
				stageintro = "初稿上传截止时间"
			}
		case 10:
			{
				var sketchinfo gorm_model.YounggeeSketchInfo
				err := db.Model(&gorm_model.YounggeeSketchInfo{}).Where("task_id = ? and is_review = 0", task.TaskID).First(&sketchinfo).Error
				if err != nil {
					return nil, err
				}
				listtime = sketchinfo.SubmitAt.Format("2006-01-02 15:04:05")
				stageintro = "达人上传初稿时间" //
			}
		case 11:
			{
				listtime = task.CurBreakAt.Format("2006-01-02 15:04:05")
				stageintro = " 链接上传截止时间"
			}
		case 12:
			{
				var linkinfo gorm_model.YounggeeLinkInfo
				err := db.Model(&gorm_model.YounggeeLinkInfo{}).Where("task_id = ? and is_review = 0", task.TaskID).First(&linkinfo).Error
				if err != nil {
					return nil, err
				}
				listtime = linkinfo.SubmitAt.Format("2006-01-02 15:04:05")
				stageintro = "达人上传链接时间"
			}
		case 13:
			{
				listtime = task.CurBreakAt.Format("2006-01-02 15:04:05")
				stageintro = "数据待传截止时间"
			}
		case 14:
			{
				var datainfo gorm_model.YounggeeDataInfo
				err := db.Model(&gorm_model.YounggeeDataInfo{}).Where("task_id = ? and is_review = 0", task.TaskID).First(&datainfo).Error
				if err != nil {
					return nil, err
				}
				var auto_task_finish gorm_model.InfoAutoTask
				db.Model(&gorm_model.InfoAutoTask{}).Where("enterprise_id = ?", request.EnterPriseId).First(&auto_task_finish)
				// 将小时数转换为 Duration 后相加
				resultTime := datainfo.SubmitAt.Add(time.Duration(auto_task_finish.TaskFinishAuto) * time.Hour)
				listtime = resultTime.Format("2006-01-02 15:04:05")
				stageintro = "品牌最晚结算时间"
			}
		case 15:
			{
				listtime = task.CompleteDate.Format("2006-01-02 15:04:05")
				stageintro = "品牌结算时间"
			}
		case 16:
			{
				listtime = task.CancelTime.Format("2006-01-02 15:04:05")
				stageintro = "解约时间"
			}
		}
		boperator := getBOperator(db, task.BOperator, task.BOperatorType)
		nickname, headurl, gender, fansnum, voteavg := getTalentinfo(db, task.OpenId)
		Iscoop := getIscoop(db, task.TalentID, request.EnterPriseId)
		s_type, s_name := stype(db, task.SupplierId, task.SupplierStatus, projectinfo.ProjectType)
		response := &http_model.TaskInfo{
			TaskId:             task.TaskID,
			ProjectId:          task.ProjectID,
			TalentId:           task.TalentID,
			FansNum:            fansnum,
			DraftFee:           task.DraftFee,
			Voteavg:            voteavg,
			FeeFrom:            task.FeeForm,
			TaskStage:          task.TaskStage,
			Commentavg:         0, //暂时获取不到
			CollectNum:         0,
			CurrentDefaultType: task.CurDefaultType,
			From:               determineFrom(task.SupplierId, task.SupplierStatus),
			SType:              s_type,
			SName:              s_name,
			Boperator:          boperator,
			CreateAt:           Time.Format("2006-01-02 15:04:05"),
			NickName:           nickname,
			Gender:             gender,
			HeadUrl:            headurl,
			ISCoop:             Iscoop,
			Sprojectid:         task.SprojectId,
			City:               task.City,
			ListTime:           listtime,
			StageIntro:         stageintro,
		}
		taskInfoPointers = append(taskInfoPointers, response)
	}

	return &http_model.GetTaskListData{
		TaskList: taskInfoPointers,
		Total:    conv.MustString(total, ""),
	}, nil
}

func getBOperator(db *gorm.DB, bOperatorID string, bOperatorType int) string {
	if bOperatorID == "" {
		return ""
	}
	if bOperatorType == 1 {
		var boperatorinfo gorm_model.Enterprise
		if err := db.Where(gorm_model.Enterprise{EnterpriseID: bOperatorID}).First(&boperatorinfo).Error; err != nil {
			return ""
		}
		return boperatorinfo.BusinessName
	}
	if bOperatorType == 2 {
		var bsubaccount gorm_model.YounggeeSubAccount
		if err := db.Where(gorm_model.YounggeeSubAccount{SubAccountId: conv.MustInt(bOperatorID)}).First(&bsubaccount).Error; err != nil {
			return ""
		}
		return bsubaccount.SubAccountName
	}
	if bOperatorType == 3 {
		return "管理后台"
	}
	return ""
}

func getTalentinfo(db *gorm.DB, OpenId string) (string, string, string, int, int) {
	var talentinfo gorm_model.PlatformKuaishouUserInfo
	if err := db.Where(gorm_model.PlatformKuaishouUserInfo{OpenId: OpenId}).First(&talentinfo).Error; err != nil {
		return "", "", "", 0, 0
	}
	fan, _ := conv.Int(talentinfo.Fan)
	return talentinfo.NickName, talentinfo.HeadUri, talentinfo.Gender, fan, talentinfo.LikeNum
}

func getIscoop(db *gorm.DB, talentid string, enterpriseid string) int {
	var etcoop gorm_model.EnterpriseTalentCooperate
	if err := db.Where(gorm_model.EnterpriseTalentCooperate{TalentId: talentid, EnterpriseId: enterpriseid}).First(&etcoop).Error; err != nil {
		return 0
	}
	return 1
}

func determineFrom(supplierID, supplierStatus int) int {
	if supplierID != 0 && supplierStatus == 2 {
		return 2
	}
	return 1
}

func stype(db *gorm.DB, supplierID, supplierStatus int, projecttype int64) (int, string) {
	if projecttype == 1 {
		if supplierID != 0 && supplierStatus == 2 {
			var supplierinfo gorm_model.Supplier
			err := db.Model(gorm_model.Supplier{}).Where("supplier_id = ?", supplierID).First(&supplierinfo).Error
			if err != nil {
				return 0, "公海"
			}
			return supplierinfo.SupplierType, supplierinfo.SupplierName
		}
		return 0, "公海"
	} else {
		if supplierID != 0 && supplierStatus == 2 {
			var supplierinfo gorm_model.Supplier
			err := db.Model(gorm_model.Supplier{}).Where("supplier_id = ?", supplierID).First(&supplierinfo).Error
			if err != nil {
				return 0, "私域"
			}
			return supplierinfo.SupplierType, supplierinfo.SupplierName
		}
		return 0, "私域"
	}
}
func PassProTaskCoop(ctx context.Context, projectId string, taskIds []string, operatorid string, operatetype int, Isspecial int, Enterpriseid string, req http_model.PassproTaskCoopRequest) (bool, error) {
	db := GetReadDB(ctx)
	var count int64
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id IN ? AND task_stage = 1", taskIds).Count(&count).Error

	if err != nil {
		return false, err
	}
	if int64(len(taskIds)) == 0 || count != int64(len(taskIds)) {
		return false, errors.New("任务id有误")
	}

	// 2. 查询任务对应达人id（用于生成达人消息）
	var talentIds []string
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id IN ?", taskIds).Select("talent_id").Find(&talentIds).Error
	if err != nil {
		return false, err
	}

	// 3. 查询任务对应project名称（用于生成达人消息）
	var project gorm_model.ProjectInfo
	err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectId).Find(&project).Error
	if err != nil {
		return false, err
	}

	var taskstages int
	if project.ProjectForm == 1 {
		taskstages = 4
	} else {
		taskstages = 9
	}
	nextstage := [6]int{0, 0, 0, 0, 0, 0} // 数组长度为6，表示6种工具 4,9,11,13
	if Isspecial == 1 {
		toolList := strings.Split(project.Tools, ",")
		for _, tool := range toolList {
			// 将 tool 转换为整数
			if t, err := strconv.Atoi(tool); err == nil && t >= 0 && t <= len(nextstage) {
				nextstage[t-1] = 1
			}
		}
		fmt.Println(nextstage)
		for i := 1; i < len(nextstage); i++ { // 从位置1开始
			if nextstage[i] == 1 {
				switch i {
				case 1:
					taskstages = 4
				case 2:
					taskstages = 9
				case 3:
					taskstages = 11
				case 4:
					taskstages = 13
				case 5:
					taskstages = 15
				}
				break
			}
		}
	}

	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}

	//4.根据达人来源改变状态、阶段、数目
	var tasks []gorm_model.YoungeeTaskInfo
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id IN ? AND task_stage = 1", taskIds).Find(&tasks).Error
	if err != nil {
		return false, err
	}
	err = db.Transaction(func(tx *gorm.DB) error {
		// 2. 修改任务状态和任务阶段
		for _, taskInfo := range tasks {
			if taskInfo.SupplierId != 0 && taskInfo.SupplierStatus == 2 { //服务商招募数量+1
				updateData := gorm_model.YoungeeTaskInfo{
					TaskStage:     taskstages,
					TaskStatus:    2,
					UpdateAt:      time.Now(),
					BOperator:     opid,
					BOperatorType: optype,
					SelectDate:    time.Now(),
				}
				err = tx.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ? AND task_stage = 1", taskInfo.TaskID).Updates(updateData).Error
				if err != nil {
					return err
				}

				//project招募数+1,预估成本+服务商价格
				var projectinfo gorm_model.ProjectInfo
				err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectId).Find(&projectinfo).Error
				if err != nil {
					return err
				}
				projectinfo.RecruitNum += 1
				projectinfo.NeedPay += taskInfo.DraftFee + taskInfo.ServiceCharge
				err = tx.Model(gorm_model.ProjectInfo{}).Where("project_id = ? ", projectId).Updates(projectinfo).Error
				if err != nil {
					return err
				}
				//服务商s_project已招募人数+1
				var sprojectinfo gorm_model.YounggeeSProjectInfo
				err = db.Model(gorm_model.YounggeeSProjectInfo{}).Where(" s_project_id =?", taskInfo.SprojectId).Find(&sprojectinfo).Error
				if err != nil {
					return err
				}
				sprojectinfo.RecruitNum += 1
				sprojectinfo.ServiceCharge += taskInfo.ServiceCharge
				sprojectinfo.EstimateSupportFee += taskInfo.SupportFee
				sprojectinfo.EstimateDraftFee += taskInfo.DraftFee
				err = tx.Model(gorm_model.YounggeeSProjectInfo{}).Where(" s_project_id =?", taskInfo.SprojectId).Updates(sprojectinfo).Error
				if err != nil {
					return err
				}

			}

			if project.ProjectForm != 1 { //非签收截止时间
				var draft_default gorm_model.InfoAutoTask
				err = db.Model(gorm_model.InfoAutoTask{}).Where("auto_task_id = ?", project.AutoTaskID).Find(&draft_default).Error
				if err != nil {
					return err
				}
				duration := time.Duration(draft_default.DraftDefault) * time.Hour
				upbreakdate := gorm_model.YoungeeTaskInfo{
					CurBreakAt: time.Now().Add(duration),
				}
				err = tx.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ? ", taskInfo.TaskID).Updates(upbreakdate).Error
				if err != nil {
					return err
				}
			}

			if taskInfo.SupplierId == 0 && taskInfo.SupplierStatus == 0 { //来源于公海
				updateData := gorm_model.YoungeeTaskInfo{
					TaskStage:     taskstages,
					TaskStatus:    2,
					UpdateAt:      time.Now(),
					BOperator:     opid,
					BOperatorType: optype,
					SelectDate:    time.Now(),
				}
				err = tx.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ? AND task_stage = 1", taskInfo.TaskID).Updates(updateData).Error
				if err != nil {
					return err
				}

				//project招募数+1,成本
				var projectinfo gorm_model.ProjectInfo
				err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectId).Find(&projectinfo).Error
				if err != nil {
					return err
				}
				projectinfo.RecruitNum += 1
				projectinfo.NeedPay += taskInfo.DraftFee + taskInfo.ServiceCharge
				err = tx.Model(gorm_model.ProjectInfo{}).Where("project_id = ? ", projectId).Updates(projectinfo).Error
				if err != nil {
					return err
				}
			}

		}
		// 4. 生成达人消息
		for _, talendId := range talentIds {
			err = CreateMessage(ctx, 1, 1, talendId, project.ProjectName)
			if err != nil {
				return err
			}
		}
		// 返回 nil 提交事务
		return nil
	})
	if err != nil {
		return false, err
	}
	return true, nil
}

func RefuseproTaskCoop(ctx context.Context, taskIds []string, operatorid string, operatetype int, Enterpriseid string) (bool, error) {
	db := GetWriteDB(ctx)
	// 1. 校验
	var count int64
	err := db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id IN ? AND task_stage = 1", taskIds).Count(&count).Error
	if err != nil {
		return false, err
	}
	if count != int64(len(taskIds)) {
		return false, errors.New("任务id有误")
	}

	var opid string
	var optype int
	switch operatetype {
	case 3:
		{
			opid = Enterpriseid
			optype = 1
		}
	case 4:
		{
			opid = operatorid
			optype = 2
		}
	}

	// 2. 查询任务对应达人id（用于生成达人消息）
	var talentIds []string
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id IN ?", taskIds).Select("talent_id").Find(&talentIds).Error
	if err != nil {
		return false, err
	}

	var tasks []gorm_model.YoungeeTaskInfo
	err = db.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id IN ? AND task_stage = 1", taskIds).Find(&tasks).Error

	err = db.Transaction(func(tx *gorm.DB) error {
		// 2. 修改任务状态和任务阶段
		for _, taskInfo := range tasks {
			updateData := gorm_model.YoungeeTaskInfo{
				TaskStage:     3,
				TaskStatus:    3,
				UpdateAt:      time.Now(),
				BOperator:     opid,
				BOperatorType: optype,
				CompleteDate:  time.Now(),
			}
			err = tx.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ? AND task_stage = 1", taskInfo.TaskID).Updates(updateData).Error
		}
		if err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	})
	if err != nil {
		return false, err
	}
	return true, nil
}

func GetPreSketchList(ctx context.Context, request http_model.PreSketchListRequest) (*http_model.GetSketchTaskListData, error) {
	db := GetReadDB(ctx)
	var projecrtaskinfo []gorm_model.YoungeeTaskInfo
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_stage = ?", request.ProjectId, request.ScriptStatus)
	var projectinfo gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).First(&projectinfo).Error
	if err != nil {
		return &http_model.GetSketchTaskListData{}, err
	}
	if request.Others != "" {
		query = query.Where("talent_name LIKE ? OR s_operate_name LIKE ?", "%"+request.Others+"%", "%"+request.Others+"%")
	}

	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 添加分页逻辑
	pageSize := request.PageSize
	if pageSize == 0 {
		pageSize = 10
	}
	pageNum := request.PageNum
	if pageNum == 0 {
		pageNum = 1
	}
	offset := (pageNum - 1) * pageSize
	// 执行分页查询
	// 处理多字段排序逻辑
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			field := request.SortField[i]
			order := request.SortOrder[i]
			switch field {
			case "fansnum":
				if order == "asc" {
					query = query.Order("fans_num asc")
				} else {
					query = query.Order("fans_num desc")
				}
			case "voteavg":
				if order == "asc" {
					query = query.Order("vote_avg asc")
				} else {
					query = query.Order("vote_avg desc")
				}
			case "commentavg":
				if order == "asc" {
					query = query.Order("commit_avg asc")
				} else {
					query = query.Order("commit_avg desc")
				}
			case "collectnum":
				if order == "asc" {
					query = query.Order("view_num asc")
				} else {
					query = query.Order("view_num desc")
				}
			}
		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("task_status asc").Order("task_stage asc")
	}
	if err := query.Offset(offset).Limit(pageSize).Find(&projecrtaskinfo).Error; err != nil {
		return nil, err
	}
	taskInfoPointers := make([]*http_model.TasksketchInfo, 0, len(projecrtaskinfo))

	for _, task := range projecrtaskinfo {
		nickname, headurl, gender, fansnum, voteavg := getTalentinfo(db, task.OpenId)
		Iscoop := getIscoop(db, task.TalentID, request.EnterpriseId)
		s_type, s_name := stype(db, task.SupplierId, task.SupplierStatus, projectinfo.ProjectType)
		taskinfo := &http_model.TaskInfo{
			TaskId:             task.TaskID,
			ProjectId:          task.ProjectID,
			TalentId:           task.TalentID,
			FansNum:            fansnum,
			DraftFee:           task.DraftFee,
			Voteavg:            voteavg,
			FeeFrom:            task.FeeForm,
			TaskStage:          task.TaskStage,
			Commentavg:         0,
			CollectNum:         0,
			CurrentDefaultType: task.CurDefaultType,
			From:               determineFrom(task.SupplierId, task.SupplierStatus),
			SType:              s_type,
			SName:              s_name,
			NickName:           nickname,
			Gender:             gender,
			HeadUrl:            headurl,
			ISCoop:             Iscoop,
			City:               task.City,
		}
		response := &http_model.TasksketchInfo{
			Task: taskinfo,
			DDl:  task.CurBreakAt.Format("2006-01-02 15:04:05"),
		}
		taskInfoPointers = append(taskInfoPointers, response)

	}
	return &http_model.GetSketchTaskListData{
		TasksketchList: taskInfoPointers,
		Total:          conv.MustString(total, ""),
	}, nil
}

func GetSketchList(ctx context.Context, request http_model.TasksketchlistRequest) (*http_model.GetsketchtaskListData, error) {
	db := GetReadDB(ctx)
	var projecrtaskinfo []gorm_model.YoungeeTaskInfo
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_stage = ?", request.ProjectId, request.ScriptStatus)
	var projectinfo gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).First(&projectinfo).Error
	if err != nil {
		return &http_model.GetsketchtaskListData{}, err
	}
	if request.Others != "" {
		query = query.Where("talent_name LIKE ? OR s_operate_name LIKE ?", "%"+request.Others+"%", "%"+request.Others+"%")
	}

	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 添加分页逻辑
	pageSize := request.PageSize
	if pageSize == 0 {
		pageSize = 10
	}
	pageNum := request.PageNum
	if pageNum == 0 {
		pageNum = 1
	}
	offset := (pageNum - 1) * pageSize
	// 执行分页查询
	// 处理多字段排序逻辑
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			field := request.SortField[i]
			order := request.SortOrder[i]
			switch field {
			case "fansnum":
				if order == "asc" {
					query = query.Order("fans_num asc")
				} else {
					query = query.Order("fans_num desc")
				}
			case "voteavg":
				if order == "asc" {
					query = query.Order("vote_avg asc")
				} else {
					query = query.Order("vote_avg desc")
				}
			case "commentavg":
				if order == "asc" {
					query = query.Order("commit_avg asc")
				} else {
					query = query.Order("commit_avg desc")
				}
			case "collectnum":
				if order == "asc" {
					query = query.Order("view_num asc")
				} else {
					query = query.Order("view_num desc")
				}
			}
		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("task_status asc").Order("task_stage asc")
	}
	if err := query.Offset(offset).Limit(pageSize).Find(&projecrtaskinfo).Error; err != nil {
		return nil, err
	}
	taskInfoPointers := make([]*http_model.Tasksketchinfo, 0, len(projecrtaskinfo))
	for _, task := range projecrtaskinfo {
		nickname, headurl, gender, fansnum, voteavg := getTalentinfo(db, task.OpenId)
		s_type, s_name := stype(db, task.SupplierId, task.SupplierStatus, projectinfo.ProjectType)
		taskinfo := &http_model.TaskInfo{
			TaskId:             task.TaskID,
			ProjectId:          task.ProjectID,
			TalentId:           task.TalentID,
			FansNum:            fansnum,
			DraftFee:           task.DraftFee,
			Voteavg:            voteavg,
			FeeFrom:            task.FeeForm,
			TaskStage:          task.TaskStage,
			Commentavg:         0,
			CollectNum:         0,
			CurrentDefaultType: task.CurDefaultType,
			From:               determineFrom(task.SupplierId, task.SupplierStatus),
			SType:              s_type,
			SName:              s_name,
			NickName:           nickname,
			Gender:             gender,
			HeadUrl:            headurl,
			City:               task.City,
		}

		var sketchinfo gorm_model.YounggeeSketchInfo
		switch request.ScriptStatus {
		case 10:
			err := db.Model(&gorm_model.YounggeeSketchInfo{}).Where("task_id = ? and is_review = 0 ", task.TaskID).First(&sketchinfo).Error
			if err != nil {
				return nil, err
			}
		case 11:
			err := db.Model(&gorm_model.YounggeeSketchInfo{}).Where("task_id = ? and is_ok = 1", task.TaskID).First(&sketchinfo).Error
			if err != nil {
				return nil, err
			}
		}

		boperator := getBOperator(db, task.BOperator, task.BOperatorType)
		response := &http_model.Tasksketchinfo{
			Task:       taskinfo,
			SketchId:   sketchinfo.SketchID,
			SubmitAt:   sketchinfo.SubmitAt.Format("2006-01-02 15:04:05"),
			AgreeAt:    sketchinfo.AgreeAt.Format("2006-01-02 15:04:05"),
			SketchType: sketchinfo.Type,
			Operator:   boperator,
		}
		taskInfoPointers = append(taskInfoPointers, response)

	}
	return &http_model.GetsketchtaskListData{
		TasksketchList: taskInfoPointers,
		Total:          conv.MustString(total, ""),
	}, nil
}

func GetPreLinkList(ctx context.Context, request http_model.PreLinkListRequest) (*http_model.GetprelinkListData, error) {
	db := GetReadDB(ctx)
	var projecrtaskinfo []gorm_model.YoungeeTaskInfo
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_stage = ?", request.ProjectId, request.LinkStatus)
	var projectinfo gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).First(&projectinfo).Error
	if err != nil {
		return &http_model.GetprelinkListData{}, err
	}
	if request.Others != "" {
		query = query.Where("talent_name LIKE ? OR s_operate_name LIKE ?", "%"+request.Others+"%", "%"+request.Others+"%")
	}

	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 添加分页逻辑
	pageSize := request.PageSize
	if pageSize == 0 {
		pageSize = 10
	}
	pageNum := request.PageNum
	if pageNum == 0 {
		pageNum = 1
	}
	offset := (pageNum - 1) * pageSize
	// 执行分页查询
	// 处理多字段排序逻辑
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			field := request.SortField[i]
			order := request.SortOrder[i]
			switch field {
			case "fansnum":
				if order == "asc" {
					query = query.Order("fans_num asc")
				} else {
					query = query.Order("fans_num desc")
				}
			case "voteavg":
				if order == "asc" {
					query = query.Order("vote_avg asc")
				} else {
					query = query.Order("vote_avg desc")
				}
			case "commentavg":
				if order == "asc" {
					query = query.Order("commit_avg asc")
				} else {
					query = query.Order("commit_avg desc")
				}
			case "collectnum":
				if order == "asc" {
					query = query.Order("view_num asc")
				} else {
					query = query.Order("view_num desc")
				}
			}
		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("task_status asc").Order("task_stage asc")
	}
	if err := query.Offset(offset).Limit(pageSize).Find(&projecrtaskinfo).Error; err != nil {
		return nil, err
	}
	taskInfoPointers := make([]*http_model.Tasklinkinfo, 0, len(projecrtaskinfo))
	for _, task := range projecrtaskinfo {
		nickname, headurl, gender, fansnum, voteavg := getTalentinfo(db, task.OpenId)
		Iscoop := getIscoop(db, task.TalentID, request.EnterpriseId)
		s_type, s_name := stype(db, task.SupplierId, task.SupplierStatus, projectinfo.ProjectType)
		taskinfo := &http_model.TaskInfo{
			TaskId:             task.TaskID,
			ProjectId:          task.ProjectID,
			TalentId:           task.TalentID,
			FansNum:            fansnum,
			DraftFee:           task.DraftFee,
			Voteavg:            voteavg,
			FeeFrom:            task.FeeForm,
			TaskStage:          task.TaskStage,
			Commentavg:         0,
			CollectNum:         0,
			CurrentDefaultType: task.CurDefaultType,
			From:               determineFrom(task.SupplierId, task.SupplierStatus),
			SType:              s_type,
			SName:              s_name,
			NickName:           nickname,
			Gender:             gender,
			HeadUrl:            headurl,
			ISCoop:             Iscoop,
			City:               task.City,
		}
		response := &http_model.Tasklinkinfo{
			Task: taskinfo,
			DDl:  task.CurBreakAt.Format("2006-01-02 15:04:05"),
		}
		taskInfoPointers = append(taskInfoPointers, response)

	}
	return &http_model.GetprelinkListData{
		TasklinkList: taskInfoPointers,
		Total:        conv.MustString(total, ""),
	}, nil
}

func GetLinkList(ctx context.Context, request http_model.TaskLinklistRequest) (*http_model.GettasklinkListData, error) {
	db := GetReadDB(ctx)
	var projecrtaskinfo []gorm_model.YoungeeTaskInfo
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_stage = ?", request.ProjectId, request.LinkStatus)
	var projectinfo gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).First(&projectinfo).Error
	if err != nil {
		return &http_model.GettasklinkListData{}, err
	}
	if request.Others != "" {
		query = query.Where("talent_name LIKE ? OR s_operate_name LIKE ?", "%"+request.Others+"%", "%"+request.Others+"%")
	}

	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 添加分页逻辑
	pageSize := request.PageSize
	if pageSize == 0 {
		pageSize = 10
	}
	pageNum := request.PageNum
	if pageNum == 0 {
		pageNum = 1
	}
	offset := (pageNum - 1) * pageSize
	// 执行分页查询
	// 处理多字段排序逻辑
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			field := request.SortField[i]
			order := request.SortOrder[i]
			switch field {
			case "fansnum":
				if order == "asc" {
					query = query.Order("fans_num asc")
				} else {
					query = query.Order("fans_num desc")
				}
			case "voteavg":
				if order == "asc" {
					query = query.Order("vote_avg asc")
				} else {
					query = query.Order("vote_avg desc")
				}
			case "commentavg":
				if order == "asc" {
					query = query.Order("commit_avg asc")
				} else {
					query = query.Order("commit_avg desc")
				}
			case "collectnum":
				if order == "asc" {
					query = query.Order("view_num asc")
				} else {
					query = query.Order("view_num desc")
				}
			}
		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("task_status asc").Order("task_stage asc")
	}
	if err := query.Offset(offset).Limit(pageSize).Find(&projecrtaskinfo).Error; err != nil {
		return nil, err
	}
	taskInfoPointers := make([]*http_model.TaskLinkinfo, 0, len(projecrtaskinfo))
	for _, task := range projecrtaskinfo {
		nickname, headurl, gender, fansnum, voteavg := getTalentinfo(db, task.OpenId)
		Iscoop := getIscoop(db, task.TalentID, request.EnterpriseId)
		s_type, s_name := stype(db, task.SupplierId, task.SupplierStatus, projectinfo.ProjectType)
		taskinfo := &http_model.TaskInfo{
			TaskId:             task.TaskID,
			ProjectId:          task.ProjectID,
			TalentId:           task.TalentID,
			FansNum:            fansnum,
			DraftFee:           task.DraftFee,
			Voteavg:            voteavg,
			FeeFrom:            task.FeeForm,
			TaskStage:          task.TaskStage,
			Commentavg:         0,
			CollectNum:         0,
			CurrentDefaultType: task.CurDefaultType,
			From:               determineFrom(task.SupplierId, task.SupplierStatus),
			SType:              s_type,
			SName:              s_name,
			NickName:           nickname,
			Gender:             gender,
			HeadUrl:            headurl,
			ISCoop:             Iscoop,
			City:               task.City,
		}
		var linkinfo gorm_model.YounggeeLinkInfo
		switch request.LinkStatus {
		case "12":
			err := db.Model(&gorm_model.YounggeeLinkInfo{}).Where("task_id = ? and is_review = 0 ", task.TaskID).First(&linkinfo).Error
			if err != nil {
				return nil, err
			}
		case "13":
			err := db.Model(&gorm_model.YounggeeLinkInfo{}).Where("task_id = ? and is_ok = 1", task.TaskID).First(&linkinfo).Error
			if err != nil {
				return nil, err
			}
		}
		boperator := getBOperator(db, task.BOperator, task.BOperatorType)
		response := &http_model.TaskLinkinfo{
			Task:     taskinfo,
			LinkId:   linkinfo.LinkID,
			SubmitAt: linkinfo.SubmitAt.Format("2006-01-02 15:04:05"),
			AgreeAt:  linkinfo.AgreeAt.Format("2006-01-02 15:04:05"),
			LinkUrl:  linkinfo.LinkUrl,
			PhotoUrl: linkinfo.PhotoUrl,
			Operator: boperator,
		}
		taskInfoPointers = append(taskInfoPointers, response)

	}
	return &http_model.GettasklinkListData{
		TaskLinklist: taskInfoPointers,
		Total:        conv.MustString(total, ""),
	}, nil
}

func GetPreDataList(ctx context.Context, request http_model.PreDataListRequest) (*http_model.GetPreDataListData, error) {
	db := GetReadDB(ctx)
	var projecrtaskinfo []gorm_model.YoungeeTaskInfo
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_stage = ?", request.ProjectId, request.DataStatus)
	var projectinfo gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).First(&projectinfo).Error
	if err != nil {
		return &http_model.GetPreDataListData{}, err
	}
	if request.Others != "" {
		query = query.Where("talent_name LIKE ? OR s_operate_name LIKE ?", "%"+request.Others+"%", "%"+request.Others+"%")
	}
	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 添加分页逻辑
	pageSize := request.PageSize
	if pageSize == 0 {
		pageSize = 10
	}
	pageNum := request.PageNum
	if pageNum == 0 {
		pageNum = 1
	}
	offset := (pageNum - 1) * pageSize
	// 执行分页查询
	// 处理多字段排序逻辑
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			field := request.SortField[i]
			order := request.SortOrder[i]
			switch field {
			case "fansnum":
				if order == "asc" {
					query = query.Order("fans_num asc")
				} else {
					query = query.Order("fans_num desc")
				}
			case "voteavg":
				if order == "asc" {
					query = query.Order("vote_avg asc")
				} else {
					query = query.Order("vote_avg desc")
				}
			case "commentavg":
				if order == "asc" {
					query = query.Order("commit_avg asc")
				} else {
					query = query.Order("commit_avg desc")
				}
			case "collectnum":
				if order == "asc" {
					query = query.Order("view_num asc")
				} else {
					query = query.Order("view_num desc")
				}
			}
		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("task_status asc").Order("task_stage asc")
	}
	if err := query.Offset(offset).Limit(pageSize).Find(&projecrtaskinfo).Error; err != nil {
		return nil, err
	}
	taskInfoPointers := make([]*http_model.Taskdatainfo, 0, len(projecrtaskinfo))
	for _, task := range projecrtaskinfo {
		nickname, headurl, gender, fansnum, voteavg := getTalentinfo(db, task.OpenId)
		Iscoop := getIscoop(db, task.TalentID, request.EnterpriseId)
		s_type, s_name := stype(db, task.SupplierId, task.SupplierStatus, projectinfo.ProjectType)
		taskinfo := &http_model.TaskInfo{
			TaskId:             task.TaskID,
			ProjectId:          task.ProjectID,
			TalentId:           task.TalentID,
			FansNum:            fansnum,
			DraftFee:           task.DraftFee,
			Voteavg:            voteavg,
			FeeFrom:            task.FeeForm,
			TaskStage:          task.TaskStage,
			Commentavg:         0,
			CollectNum:         0,
			CurrentDefaultType: task.CurDefaultType,
			From:               determineFrom(task.SupplierId, task.SupplierStatus),
			SType:              s_type,
			SName:              s_name,
			NickName:           nickname,
			Gender:             gender,
			HeadUrl:            headurl,
			ISCoop:             Iscoop,
			City:               task.City,
		}
		response := &http_model.Taskdatainfo{
			Task: taskinfo,
			DDl:  task.CurBreakAt.Format("2006-01-02 15:04:05"),
		}
		taskInfoPointers = append(taskInfoPointers, response)

	}
	return &http_model.GetPreDataListData{
		TaskdataList: taskInfoPointers,
		Total:        conv.MustString(total, ""),
	}, nil
}

func GetDataList(ctx context.Context, request http_model.TaskDatalistRequest) (*http_model.GetTaskDatalistData, error) {
	db := GetReadDB(ctx)
	var projectinfo gorm_model.ProjectInfo
	err := db.Model(&gorm_model.ProjectInfo{}).Where("project_id = ?", request.ProjectId).First(&projectinfo).Error
	if err != nil {
		return &http_model.GetTaskDatalistData{}, err
	}
	var projecrtaskinfo []gorm_model.YoungeeTaskInfo
	query := db.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_stage = ?", request.ProjectId, request.DataStatus)
	if request.Others != "" {
		query = query.Where("talent_name LIKE ? OR s_operate_name LIKE ?", "%"+request.Others+"%", "%"+request.Others+"%")
	}
	// 计算总数
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, err
	}

	// 添加分页逻辑
	pageSize := request.PageSize
	if pageSize == 0 {
		pageSize = 10
	}
	pageNum := request.PageNum
	if pageNum == 0 {
		pageNum = 1
	}
	offset := (pageNum - 1) * pageSize
	// 执行分页查询
	// 处理多字段排序逻辑
	if len(request.SortField) > 0 && len(request.SortOrder) > 0 && len(request.SortField) == len(request.SortOrder) {
		for i := 0; i < len(request.SortField); i++ {
			field := request.SortField[i]
			order := request.SortOrder[i]
			switch field {
			case "fansnum":
				if order == "asc" {
					query = query.Order("fans_num asc")
				} else {
					query = query.Order("fans_num desc")
				}
			case "voteavg":
				if order == "asc" {
					query = query.Order("vote_avg asc")
				} else {
					query = query.Order("vote_avg desc")
				}
			case "commentavg":
				if order == "asc" {
					query = query.Order("commit_avg asc")
				} else {
					query = query.Order("commit_avg desc")
				}
			case "collectnum":
				if order == "asc" {
					query = query.Order("view_num asc")
				} else {
					query = query.Order("view_num desc")
				}
			}
		}
	} else {
		// Default sorting if no valid sort parameters
		query = query.Order("task_status asc").Order("task_stage asc")
	}
	if err := query.Offset(offset).Limit(pageSize).Find(&projecrtaskinfo).Error; err != nil {
		return nil, err
	}
	taskInfoPointers := make([]*http_model.TaskDatainfo, 0, len(projecrtaskinfo))
	for _, task := range projecrtaskinfo {
		nickname, headurl, gender, fansnum, voteavg := getTalentinfo(db, task.OpenId)
		Iscoop := getIscoop(db, task.TalentID, request.EnterpriseId)
		s_type, s_name := stype(db, task.SupplierId, task.SupplierStatus, projectinfo.ProjectType)
		taskinfo := &http_model.TaskInfo{
			TaskId:             task.TaskID,
			ProjectId:          task.ProjectID,
			TalentId:           task.TalentID,
			FansNum:            fansnum,
			DraftFee:           task.DraftFee,
			Voteavg:            voteavg,
			FeeFrom:            task.FeeForm,
			TaskStage:          task.TaskStage,
			Commentavg:         0,
			CollectNum:         0,
			CurrentDefaultType: task.CurDefaultType,
			From:               determineFrom(task.SupplierId, task.SupplierStatus),
			SType:              s_type,
			SName:              s_name,
			NickName:           nickname,
			Gender:             gender,
			HeadUrl:            headurl,
			ISCoop:             Iscoop,
			City:               task.City,
		}
		var datainfo gorm_model.YounggeeDataInfo
		switch request.DataStatus {
		case "12":
			err := db.Model(&gorm_model.YounggeeDataInfo{}).Where("task_id = ? and is_review = 0 ", task.TaskID).First(&datainfo).Error
			if err != nil {
				return nil, err
			}
		case "13":
			err := db.Model(&gorm_model.YounggeeDataInfo{}).Where("task_id = ? and is_ok = 1", task.TaskID).First(&datainfo).Error
			if err != nil {
				return nil, err
			}
		}
		boperator := getBOperator(db, task.BOperator, task.BOperatorType)
		response := &http_model.TaskDatainfo{
			Task:          taskinfo,
			DataId:        datainfo.DataID,
			SubmitAt:      datainfo.SubmitAt.Format("2006-01-02 15:04:05"),
			AgreeAt:       datainfo.AgreeAt.Format("2006-01-02 15:04:05"),
			PhotoUrl:      datainfo.PhotoUrl,
			PlayNumber:    datainfo.PlayNumber,
			LikeNumber:    datainfo.LikeNumber,
			CollectNumber: datainfo.CollectNumber,
			CommentNumber: datainfo.CommentNumber,
			SettleAmount:  task.SettleAmount,
			Breakrate:     task.SketchBreakRate + task.LinkBreakRate + task.DataBreakRate,
			Operator:      boperator,
		}
		taskInfoPointers = append(taskInfoPointers, response)

	}
	return &http_model.GetTaskDatalistData{
		TaskDatalist: taskInfoPointers,
		Total:        conv.MustString(total, ""),
	}, nil
}
