package db

import (
	"context"
	"fmt"
	"github.com/issue9/conv"
	"time"
	"youngee_b_api/model/gorm_model"

	log "github.com/sirupsen/logrus"
)

func AutoUpdateStatus() error {
	db := GetReadDB(context.Background())
	// 查找所有到达招募截止时间的项目id
	var projectIds []string
	db = db.Debug().Model(gorm_model.ProjectInfo{}).Select("project_id").Where("project_status = 6").Find(&projectIds)
	//fmt.Println("projectIds",projectIds)
	if len(projectIds) != 0 {
		for _, projectId := range projectIds {
			db1 := GetReadDB(context.Background())
			db1 = db1.Debug().Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? and task_status = 1", projectId).Update("task_status", 3)
		}
	}
	db1 := GetReadDB(context.Background())
	// 更新招募中项目状态为待支付
	err := db1.Debug().Model(gorm_model.ProjectInfo{}).
		Where("project_status = ? AND recruit_ddl < ?", 4, time.Now()).Update("project_status", 6).Error
	if err != nil {
		log.Println("DB AutoUpdateStatus error :", err)
		return err
	}
	return nil
}

func GetLastAutoTaskID() (int, error) {
	db := GetReadDB(context.Background())
	// 查找最后一个
	LastTask := gorm_model.InfoAutoTask{}
	result := db.Last(&LastTask)
	err := result.Error
	if err != nil {
		log.Println("DB GetLastAutoTaskID:", err)
		return 0, err
	}
	//fmt.Printf("auto task %+v %+v", result, LastTask)
	return LastTask.AutoTaskID, nil
}

func AutoUpdateApplyTimes() error {
	db := GetReadDB(context.Background())
	// 查询task表信息
	db = db.Debug().Model(gorm_model.YoungeeTalentInfo{})
	err := db.Where("1 = 1").Update("apply_num", 5).Error
	if err != nil {
		log.Println("DB AutoUpdateStatus error :", err)
		return err
	}
	return nil
}

func AutoCompleteSelection() error {
	db := GetReadDB(context.Background())
	// 查询selection表，查询所有到截至时间的选品项目
	var completedSelectionList []gorm_model.YounggeeSelectionInfo
	err := db.Model(gorm_model.YounggeeSelectionInfo{}).Where("task_ddl < ?", time.Now()).Scan(&completedSelectionList).Error
	if err != nil {
		log.Println("DB AutoCompleteSelection error :", err)
		return err
	}
	// 遍历结束选品列表
	for _, v := range completedSelectionList {
		if v.SelectionStatus == 6 { // 若处于执行中阶段
			// 查询该选品下所有待结算任务
			var settleSecTaskList []gorm_model.YounggeeSecTaskInfo
			err = db.Model(gorm_model.YounggeeSecTaskInfo{}).Where("selection_id = ? and task_stage = 9", v.SelectionID).Scan(&settleSecTaskList).Error
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}
			// 结算选品
			for _, w := range settleSecTaskList {
				// 更新任务信息
				updateSecTaskData := gorm_model.YounggeeSecTaskInfo{
					TaskID:           w.TaskID,
					TaskStage:        10,
					AssignmentStatus: 5,
					IsPayReward:      0,
					IsPayPayment:     0,
					CompleteDate:     time.Now(),
				}
				_, err = UpdateSecTask(context.Background(), updateSecTaskData)
				if err != nil {
					log.Println("DB AutoCompleteSelection error :", err)
					return err
				}

				// 添加任务日志和达人消息
				err = CreateTaskLog(context.Background(), w.TaskID, "结算时间")
				if err != nil {
					log.Println("DB AutoCompleteSelection error :", err)
				}

				err = CreateMessageBySecTaskId(context.Background(), 5, 1, w.TaskID)
				if err != nil {
					log.Println("DB AutoCompleteSelection error :", err)
					return err
				}
			}

			// 计算结算金额，并返还剩余冻结资金
			var leftMoney float64 = conv.MustFloat64(v.EstimatedCost, 0) - conv.MustFloat64(v.SettlementAmount, 0)
			_, err = UpdateEnterpriseBalance(context.Background(), v.EnterpriseID, 0, leftMoney, -leftMoney)
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}

			// 更新选品阶段为已结案
			updateSelectionInfo := gorm_model.YounggeeSelectionInfo{
				SelectionID:     v.SelectionID,
				SelectionStatus: 8,
				FinishAt:        time.Now(),
			}
			err = UpdateSelection(context.Background(), updateSelectionInfo)
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}
		} else { // 否则
			// 更新选品阶段为失效，失效原因为逾期未支付
			updateSelectionInfo := gorm_model.YounggeeSelectionInfo{
				SelectionID:     v.SelectionID,
				SelectionStatus: 7,
				FailReason:      1,
				FinishAt:        time.Now(),
			}
			err = UpdateSelection(context.Background(), updateSelectionInfo)
			if err != nil {
				log.Println("DB AutoCompleteSelection error :", err)
				return err
			}
		}
	}

	return nil
}

// GetAutoDraftDefaultTask 初稿违约一
func GetAutoDraftDefaultTask() error {
	fmt.Println("GetAutoDraftDefaultInPicTask Running")
	db := GetReadDB(context.Background())

	// 1. 根据种草任务形式取出对应的Project
	var projectInfos []*gorm_model.ProjectInfo
	projectInfoErr := db.Model(gorm_model.ProjectInfo{}).Where("project_type = ? AND project_form = ? ", 1, 1).Find(&projectInfos).Error
	if projectInfoErr != nil {
		return projectInfoErr
	}

	// 2. 构建查询map
	var projectIds []string
	projectIdToAutoTaskIdMap := map[string]int{}    // 项目id 对 定时任务id 的map
	projectIdToAutoDefaultIdMap := map[string]int{} // 项目id 对 违约扣款设置id 的map
	taskIdToFeeFormMap := make(map[string]int)      // taskId 对 稿费形式的 map
	TaskIdToProjectId := make(map[string]string)    // taskId 对 项目id的 map
	var taskNeedModIds []string                     // 首次提交初稿的任务记录id
	var submitTaskNeedModIds []string               // 修改后提交初稿的任务记录id
	for _, projectInfo := range projectInfos {
		projectIds = append(projectIds, projectInfo.ProjectID)
		projectIdToAutoTaskIdMap[projectInfo.ProjectID] = int(projectInfo.AutoTaskID)
		projectIdToAutoDefaultIdMap[projectInfo.ProjectID] = int(projectInfo.AutoDefaultID)
	}
	for _, projectId := range projectIds {
		db1 := GetReadDB(context.Background())
		var taskInfos []gorm_model.YoungeeTaskInfo
		db1.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = ? AND task_stage = ? AND cur_default_type = ? AND logistics_status = 3", projectId, 2, 9, 0).Find(&taskInfos)
		for _, taskInfo := range taskInfos {
			TaskIdToProjectId[taskInfo.TaskID] = projectId
			taskNeedMod := gorm_model.YoungeeTaskInfo{}
			db2 := GetReadDB(context.Background())

			// 保存所有满足物流状态为 3 且 初稿上传状态为 1或 3 的任务记录的id
			db2.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskInfo.TaskID).First(&taskNeedMod)
			taskIdToFeeFormMap[taskInfo.TaskID] = taskInfo.FeeForm
			if taskNeedMod.TaskStage == 9 && taskNeedMod.SketchStatus == 1 {
				taskNeedModIds = append(taskNeedModIds, taskInfo.TaskID)
			}
			if taskNeedMod.TaskStage == 9 && taskNeedMod.SketchStatus == 3 {
				submitTaskNeedModIds = append(submitTaskNeedModIds, taskInfo.TaskID)
			}
		}
	}

	// 3. 对初次初稿未上传的操作
	for _, taskNeedModId := range taskNeedModIds {
		// 获取taskId对应的autoTaskId
		autoTaskId := projectIdToAutoTaskIdMap[TaskIdToProjectId[taskNeedModId]]

		// 根据autoTaskId去查找对应的初稿违约小时数
		dbStart := GetReadDB(context.Background())
		var DraftDefaultInPic int32
		dbStart.Model(gorm_model.InfoAutoTask{}).Select("draft_default").Where("auto_task_id = ?", autoTaskId).First(&DraftDefaultInPic)

		// 根据taskId查询taskInfo
		db3 := GetReadDB(context.Background())
		taskLogisticNeedMod := gorm_model.YoungeeTaskInfo{}
		db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskNeedModId).First(&taskLogisticNeedMod)

		// 获取task对应的autoDefaultId 并取出违约扣款比例
		autoDefaultHandle := gorm_model.InfoAutoDefaultHandle{}
		db6 := GetReadDB(context.Background())
		db6.Model(gorm_model.InfoAutoDefaultHandle{}).Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[TaskIdToProjectId[taskNeedModId]]).Find(&autoDefaultHandle)

		var sketchDefaultRate int
		var sketchErrRate int
		// 稿费形式为产品置换
		if taskIdToFeeFormMap[taskNeedModId] == 1 {
			sketchDefaultRate = autoDefaultHandle.SketchReplaceTimeOut
			sketchErrRate = autoDefaultHandle.SketchReplaceNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("sketch_replace_time_out", "sketch_replace_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[TaskIdToProjectId[taskNeedModId]]).Find(&autoDefaultHandle)
		} else {
			// 稿费形式为其他
			sketchDefaultRate = autoDefaultHandle.SketchOtherTimeOut
			sketchErrRate = autoDefaultHandle.SketchOtherNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("sketch_other_time_out", "sketch_other_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[TaskIdToProjectId[taskNeedModId]]).Find(&sketchDefaultRate, &sketchErrRate)
		}

		//	若无违约自动处理时间 则添加初稿违约自动处理时间
		if taskLogisticNeedMod.TaskID != "" && taskLogisticNeedMod.SketchMissingTime.IsZero() {
			dd, _ := time.ParseDuration(conv.MustString(DraftDefaultInPic, "") + "h")
			db4 := GetReadDB(context.Background())
			t := taskLogisticNeedMod.SignedTime.Add(dd)
			db4.Where("task_id = ?", taskNeedModId).Updates(&gorm_model.YoungeeTaskInfo{
				SketchMissingTime: t,
			})
			taskLogisticNeedMod.SketchMissingTime = t
			fmt.Println("已添加 品牌种草-商品寄拍-初次初稿未上传 初稿违约自动处理时间")
			fmt.Println(sketchDefaultRate, sketchErrRate)
		}

		// 判断是否超时违约
		if taskLogisticNeedMod.TaskID != "" && taskLogisticNeedMod.SketchMissingTime.Sub(time.Now()) <= 0 {
			fmt.Println("taskId: ", taskLogisticNeedMod.TaskID, "超时违约触发")
			taskInfo := gorm_model.YoungeeTaskInfo{}
			dbt := GetReadDB(context.Background())
			err2 := dbt.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskLogisticNeedMod.TaskID).Find(&taskInfo).Error
			if err2 != nil {
				return err2
			}

			// 计算违约扣款后的达人所得
			settleAmount := taskInfo.DraftFee * (1.0 - float64(taskInfo.LinkBreakRate+taskInfo.DataBreakRate+sketchDefaultRate+taskInfo.ScriptBreakRate)/100)
			if settleAmount <= 0 {
				settleAmount = 0.0
			}

			// 计算违约扣款后的服务商所得
			realServiceCharge := taskInfo.ServiceCharge * (1.0 - float64(taskInfo.LinkBreakRate+taskInfo.DataBreakRate+sketchDefaultRate+taskInfo.ScriptBreakRate)/100)
			if realServiceCharge <= 0 {
				realServiceCharge = 0.0
			}

			// 计算企业需要实际支付金额
			realPayment := settleAmount + realServiceCharge
			if realPayment <= 0 {
				realPayment = 0.0
			}

			db8 := GetReadDB(context.Background())
			fmt.Println("待更新的taskId: ", taskLogisticNeedMod.TaskID)
			db8.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskLogisticNeedMod.TaskID).Updates(
				map[string]interface{}{
					"sketch_missing_status": 1,
					"cur_default_type":      3,
					"sketch_break_rate":     sketchDefaultRate,
					"settle_amount":         settleAmount,
					"err_break_rate":        sketchErrRate,
					"real_service_charge":   realServiceCharge,
					"real_payment":          realPayment,
				})
			createTaskLogErr := CreateTaskLog(context.Background(), taskLogisticNeedMod.TaskID, "初稿逾期")
			if createTaskLogErr != nil {
				log.WithContext(context.Background()).Errorf("[operate db] call CreateTaskLog error,err:%+v", createTaskLogErr)
			}
			createMessageByTaskIdErr := CreateMessageByTaskId(context.Background(), 22, 4, taskLogisticNeedMod.TaskID)
			if createMessageByTaskIdErr != nil {
				log.WithContext(context.Background()).Errorf("[operate db] call CreateMessageByTaskId error,err:%+v", createMessageByTaskIdErr)
			}
			fmt.Println("已创建 品牌种草-商品寄拍-初次初稿未上传 初稿违约记录")
		}
	}

	// 4. 判断应该修改后上传的任务
	for _, submitTaskNeedModId := range submitTaskNeedModIds {

		// 获取 autoTaskId 及其对应的限制时间
		db2 := GetReadDB(context.Background())
		var DraftDefaultInMv int32
		db2.Model(&gorm_model.InfoAutoTask{}).Select("draft_default").Where("auto_task_id = ?", projectIdToAutoTaskIdMap[TaskIdToProjectId[submitTaskNeedModId]]).First(&DraftDefaultInMv)
		dd, _ := time.ParseDuration(conv.MustString(DraftDefaultInMv, "") + "h")

		// 查询违约扣款比例
		autoDefaultHandle := gorm_model.InfoAutoDefaultHandle{}
		db6 := GetReadDB(context.Background())
		db6.Model(gorm_model.InfoAutoDefaultHandle{}).Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[TaskIdToProjectId[submitTaskNeedModId]]).Find(&autoDefaultHandle)

		var sketchDefaultRate int
		var sketchErrRate int
		if taskIdToFeeFormMap[submitTaskNeedModId] == 1 {
			sketchDefaultRate = autoDefaultHandle.SketchReplaceTimeOut
			sketchErrRate = autoDefaultHandle.SketchReplaceNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("sketch_replace_time_out", "sketch_replace_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[TaskIdToProjectId[submitTaskNeedModId]]).Find(&sketchDefaultRate, &sketchErrRate)
		} else {
			sketchDefaultRate = autoDefaultHandle.SketchOtherTimeOut
			sketchErrRate = autoDefaultHandle.SketchOtherNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("sketch_other_time_out", "sketch_other_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[TaskIdToProjectId[submitTaskNeedModId]]).Find(&sketchDefaultRate, &sketchErrRate)
		}

		//	添加初稿违约自动处理时间
		db1 := GetReadDB(context.Background())
		var taskSketchInfo gorm_model.YounggeeSketchInfo
		db1.Model(gorm_model.YounggeeSketchInfo{}).Where("task_id = ? and is_review = 1", submitTaskNeedModId).Order("reject_at desc").First(&taskSketchInfo)
		if taskSketchInfo.AutoSketchBreakAt.IsZero() {
			err4 := db1.Where("task_id = ?", submitTaskNeedModId).Updates(&gorm_model.YounggeeSketchInfo{AutoSketchBreakAt: taskSketchInfo.RejectAt.Add(dd)}).Error
			if err4 != nil {
				return err4
			}
			taskSketchInfo.AutoSketchBreakAt = taskSketchInfo.RejectAt.Add(dd)
			fmt.Println("已添加 品牌种草-商品寄拍-修改后上传初稿未上传自动处理时间")
		}

		// 判断是否违约
		if taskSketchInfo.TaskID != "" && taskSketchInfo.AutoSketchBreakAt.Sub(time.Now()) <= 0 {
			db4 := GetReadDB(context.Background())
			err1 := db4.Model(gorm_model.YoungeeContractInfo{}).Create(&gorm_model.YoungeeContractInfo{
				TaskID: submitTaskNeedModId, ProjectID: TaskIdToProjectId[submitTaskNeedModId], BreakType: 2, BreakAt: time.Now(), DefaultStatus: 1}).Error
			if err1 != nil {
				return err1
			}
			taskInfo := gorm_model.YoungeeTaskInfo{}
			dbt := GetReadDB(context.Background())
			err2 := dbt.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", submitTaskNeedModId).Find(&taskInfo).Error
			if err2 != nil {
				return err2
			}

			// 计算违约扣款后的达人所得
			settleAmount := taskInfo.DraftFee * (1.0 - float64(sketchDefaultRate+taskInfo.DataBreakRate+taskInfo.LinkBreakRate+taskInfo.ScriptBreakRate)/100)
			if settleAmount <= 0 {
				settleAmount = 0.
			}

			// 计算违约扣款后的服务商所得
			realServiceCharge := taskInfo.ServiceCharge * (1.0 - float64(taskInfo.LinkBreakRate+taskInfo.DataBreakRate+sketchDefaultRate+taskInfo.ScriptBreakRate)/100)
			if realServiceCharge <= 0 {
				realServiceCharge = 0.0
			}

			// 计算企业需要实际支付金额
			realPayment := settleAmount + realServiceCharge
			if realPayment <= 0 {
				realPayment = 0.0
			}

			db3 := GetReadDB(context.Background())
			err2 = db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", submitTaskNeedModId).Updates(
				map[string]interface{}{
					"sketch_missing_status": 1,
					"cur_default_type":      3,
					"sketch_break_rate":     sketchDefaultRate,
					"settle_amount":         settleAmount,
					"err_break_rate":        sketchErrRate,
					"real_service_charge":   realServiceCharge,
					"real_payment":          realPayment,
				}).Error
			if err2 != nil {
				return err2
			}
			createTaskLogErr := CreateTaskLog(context.Background(), submitTaskNeedModId, "初稿逾期")
			if createTaskLogErr != nil {
				log.WithContext(context.Background()).Errorf("[operate db] call CreateTaskLog error,err:%+v", createTaskLogErr)
			}
			createMessageByTaskIdErr := CreateMessageByTaskId(context.Background(), 22, 4, submitTaskNeedModId)
			if createMessageByTaskIdErr != nil {
				log.WithContext(context.Background()).Errorf("[operate db] call CreateMessageByTaskId error,err:%+v", createMessageByTaskIdErr)
			}
			fmt.Println("创建已提交初稿的初稿违约记录")
		}
	}
	return nil
}

// GetAutoLinkDefaultTask 链接质检违约
func GetAutoLinkDefaultTask() error {

	// 1. 筛选出可能链接超时违约的子任务，首次/修改
	db := GetReadDB(context.Background())
	var projectInfos []*gorm_model.ProjectInfo
	err := db.Model(gorm_model.ProjectInfo{}).Where("project_type = ?", 1).Find(&projectInfos).Error
	if err != nil {
		return err
	}
	var projectIds []string
	// 任务id 对 项目id 的map
	taskIdToProjectIdMap := map[string]string{}
	// 项目id 对 定时任务id 的map
	projectIdToAutoTaskIdMap := map[string]int{}
	// 项目id 对 违约定时任务id 的map
	projectIdToAutoDefaultIdMap := map[string]int{}
	var taskIds []string
	// taskId 对 稿费形式的 map
	taskIdToFeeFormMap := make(map[string]int)
	for _, projectInfo := range projectInfos {
		projectIds = append(projectIds, projectInfo.ProjectID)
		projectIdToAutoTaskIdMap[projectInfo.ProjectID] = int(projectInfo.AutoTaskID)
		projectIdToAutoDefaultIdMap[projectInfo.ProjectID] = int(projectInfo.AutoDefaultID)

		var taskInfos []*gorm_model.YoungeeTaskInfo
		db1 := GetReadDB(context.Background())
		db1.Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = ? AND task_stage = ? AND cur_default_type = ? ", projectInfo.ProjectID, 2, 11, 0).Find(&taskInfos)
		for _, taskInfo := range taskInfos {
			taskIdToProjectIdMap[taskInfo.TaskID] = projectInfo.ProjectID
			taskIds = append(taskIds, taskInfo.TaskID)
			taskIdToFeeFormMap[taskInfo.TaskID] = taskInfo.FeeForm
		}
	}
	// 首次提交链接的任务记录id
	var taskNeedModIds []string
	// 已提交链接的任务记录id
	var submitTaskNeedModIds []string
	for _, taskId := range taskIds {
		var taskInfo gorm_model.YoungeeTaskInfo
		db3 := GetReadDB(context.Background())
		// 保存所有链接上传状态为 1  且任务状态为12 的任务记录的id
		db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskId).First(&taskInfo)
		if taskInfo.LinkStatus == 1 && taskInfo.TaskStage == 11 {
			taskNeedModIds = append(taskNeedModIds, taskId)
		}
		// 保存所有链接上传状态为 3  且任务状态为12 的任务记录的id
		if taskInfo.LinkStatus == 3 && taskInfo.TaskStage == 11 {
			submitTaskNeedModIds = append(submitTaskNeedModIds, taskId)
		}
	}

	// 2. 对于需要初次上传链接但是未上传的子任务
	for _, taskNeedModId := range taskNeedModIds {
		db2 := GetReadDB(context.Background())
		var linkBreach int32
		db2.Model(&gorm_model.InfoAutoTask{}).Select("link_breach").Where("auto_task_id = ?", projectIdToAutoTaskIdMap[taskIdToProjectIdMap[taskNeedModId]]).First(&linkBreach)
		dd, _ := time.ParseDuration(conv.MustString(linkBreach, "") + "h")

		autoDefaultHandle := gorm_model.InfoAutoDefaultHandle{}
		db6 := GetReadDB(context.Background())
		db6.Model(gorm_model.InfoAutoDefaultHandle{}).Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[taskNeedModId]]).Find(&autoDefaultHandle)

		var linkDefaultRate int
		var linkErrRate int
		if taskIdToFeeFormMap[taskNeedModId] == 1 {
			linkDefaultRate = autoDefaultHandle.LinkReplaceTimeOut
			linkErrRate = autoDefaultHandle.LinkReplaceNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("link_replace_time_out", "link_replace_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[taskNeedModId]]).Find(&linkDefaultRate, &linkErrRate)
		} else {
			linkDefaultRate = autoDefaultHandle.LinkOtherTimeOut
			linkErrRate = autoDefaultHandle.LinkOtherNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("link_other_time_out", "link_other_not_uploadsg").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[taskNeedModId]]).Find(&linkDefaultRate, &linkErrRate)
		}
		db1 := GetReadDB(context.Background())
		var taskSketchInfo gorm_model.YounggeeSketchInfo
		db1.Model(gorm_model.YounggeeSketchInfo{}).Where("task_id = ? AND is_ok = ?", taskNeedModId, 1).Find(&taskSketchInfo)
		dbTask := GetReadDB(context.Background())
		var taskInfoCurr gorm_model.YoungeeTaskInfo
		dbTask.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskNeedModId).Find(&taskInfoCurr)
		if taskInfoCurr.LinkMissingTime.IsZero() {
			// db1.Where("task_id = ?", taskNeedModId).Updates(&gorm_model.YounggeeSketchInfo{AutoLinkBreakAt: taskSketchInfo.AgreeAt.Add(dd)})
			dbTask.Where("task_id = ?", taskNeedModId).Updates(&gorm_model.YoungeeTaskInfo{LinkMissingTime: taskSketchInfo.AgreeAt.Add(dd)})
			fmt.Println("已添加链接违约自动处理时间")
		} else {
			if taskInfoCurr.TaskID != "" && taskInfoCurr.LinkMissingTime.Sub(time.Now()) <= 0 {
				//db4 := GetReadDB(context.Background())
				//err1 := db4.Model(gorm_model.YoungeeContractInfo{}).Create(&gorm_model.YoungeeContractInfo{
				//	TaskID: taskNeedModId, ProjectID: taskIdToProjectIdMap[taskNeedModId], BreakType: 3, BreakAt: time.Now(), DefaultStatus: 1}).Error
				//if err1 != nil {
				//	return err1
				//}
				taskInfo := gorm_model.YoungeeTaskInfo{}
				dbt := GetReadDB(context.Background())
				err2 := dbt.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskNeedModId).Find(&taskInfo).Error
				if err2 != nil {
					return err2
				}
				// 达人实际所得
				settleAmount := taskInfo.DraftFee * (1.0 - float64(linkDefaultRate+taskInfo.DataBreakRate+taskInfo.SketchBreakRate+taskInfo.ScriptBreakRate)/100)
				if settleAmount <= 0 {
					settleAmount = 0.0
				}
				// 服务商实际所得
				realServiceCharge := taskInfo.ServiceCharge * (1.0 - float64(taskInfo.LinkBreakRate+taskInfo.DataBreakRate+linkDefaultRate+taskInfo.ScriptBreakRate)/100)
				if realServiceCharge <= 0 {
					realServiceCharge = 0.0
				}
				// 企业实际支付
				realPayment := settleAmount + realServiceCharge
				if realPayment <= 0 {
					realPayment = 0.0
				}
				db3 := GetReadDB(context.Background())
				err2 = db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskNeedModId).Updates(
					map[string]interface{}{
						"link_missing_status": 1,
						"cur_default_type":    5,
						"link_break_rate":     linkDefaultRate,
						"settle_amount":       settleAmount,
						"real_service_charge": realServiceCharge,
						"err_break_rate":      linkErrRate,
						"real_payment":        realPayment,
					}).Error
				if err2 != nil {
					return err2
				}
				err = CreateTaskLog(context.Background(), taskNeedModId, "链接逾期")
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateTaskLog error,err:%+v", err)
				}
				err = CreateMessageByTaskId(context.Background(), 23, 4, taskNeedModId)
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateMessageByTaskId error,err:%+v", err)
				}
				fmt.Println("已创建链接违约记录")
			}
		}
	}

	// 3. 对于需要修改后上传的链接
	for _, submitTaskNeedModId := range submitTaskNeedModIds {
		db2 := GetReadDB(context.Background())
		var LinkBreach int32
		db2.Model(&gorm_model.InfoAutoTask{}).Select("link_breach").Where("auto_task_id = ?", projectIdToAutoTaskIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).First(&LinkBreach)
		dd, _ := time.ParseDuration(conv.MustString(LinkBreach, "") + "h")

		autoDefaultHandle := gorm_model.InfoAutoDefaultHandle{}
		db6 := GetReadDB(context.Background())
		db6.Model(gorm_model.InfoAutoDefaultHandle{}).Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).Find(&autoDefaultHandle)

		var linkDefaultRate int
		var linkErrRate int
		if taskIdToFeeFormMap[submitTaskNeedModId] == 1 {
			linkDefaultRate = autoDefaultHandle.LinkReplaceTimeOut
			linkErrRate = autoDefaultHandle.LinkReplaceNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("link_replace_time_out", "link_replace_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).Find(&linkDefaultRate, &linkErrRate)
		} else {
			linkDefaultRate = autoDefaultHandle.LinkOtherTimeOut
			linkErrRate = autoDefaultHandle.LinkOtherNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("link_other_time_out", "link_other_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).Find(&linkDefaultRate, &linkErrRate)
		}
		db1 := GetReadDB(context.Background())
		var taskLinkInfo gorm_model.YounggeeLinkInfo
		db1.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id = ?", submitTaskNeedModId).Order("reject_at desc").First(&taskLinkInfo)
		dbTask := GetReadDB(context.Background())
		var taskInfoCurr gorm_model.YoungeeTaskInfo
		dbTask.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", submitTaskNeedModId).Find(&taskInfoCurr)
		if taskLinkInfo.AutoLinkBreakAt.IsZero() {
			err4 := db1.Where("task_id = ?", submitTaskNeedModId).Updates(&gorm_model.YounggeeLinkInfo{AutoLinkBreakAt: taskLinkInfo.RejectAt.Add(dd)}).Error
			if err4 != nil {
				return err4
			}
			taskInfoCurrErr := dbTask.Where("task_id = ?", submitTaskNeedModId).Updates(&gorm_model.YoungeeTaskInfo{LinkMissingTime: taskLinkInfo.RejectAt.Add(dd)}).Error
			if taskInfoCurrErr != nil {
				return taskInfoCurrErr
			}
			fmt.Println("已添加链接违约自动处理时间")
		} else {
			if taskLinkInfo.TaskID != "" && taskLinkInfo.AutoLinkBreakAt.Sub(time.Now()) <= 0 {
				//db4 := GetReadDB(context.Background())
				//err1 := db4.Model(gorm_model.YoungeeContractInfo{}).Create(&gorm_model.YoungeeContractInfo{
				//	TaskID: submitTaskNeedModId, ProjectID: taskIdToProjectIdMap[submitTaskNeedModId], BreakType: 3, BreakAt: time.Now(), DefaultStatus: 1}).Error
				//if err1 != nil {
				//	return err1
				//}
				taskInfo := gorm_model.YoungeeTaskInfo{}
				dbt := GetReadDB(context.Background())
				err2 := dbt.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", submitTaskNeedModId).Find(&taskInfo).Error
				if err2 != nil {
					return err2
				}
				// 达人实际所得
				settleAmount := taskInfo.DraftFee * (1.0 - float64(linkDefaultRate+taskInfo.DataBreakRate+taskInfo.SketchBreakRate+taskInfo.ScriptBreakRate)/100)
				if settleAmount <= 0 {
					settleAmount = 0.0
				}
				// 服务商实际所得
				realServiceCharge := taskInfo.ServiceCharge * (1.0 - float64(taskInfo.LinkBreakRate+taskInfo.DataBreakRate+linkDefaultRate+taskInfo.ScriptBreakRate)/100)
				if realServiceCharge <= 0 {
					realServiceCharge = 0.0
				}
				// 企业实际支付
				realPayment := settleAmount + realServiceCharge
				if realPayment <= 0 {
					realPayment = 0.0
				}
				db3 := GetReadDB(context.Background())
				err2 = db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", submitTaskNeedModId).Updates(
					map[string]interface{}{
						"link_missing_status": 1,
						"cur_default_type":    5,
						"link_break_rate":     linkDefaultRate,
						"settle_amount":       settleAmount,
						"real_service_charge": realServiceCharge,
						"err_break_rate":      linkErrRate,
						"real_payment":        realPayment,
					}).Error
				if err2 != nil {
					return err2
				}
				err = CreateTaskLog(context.Background(), submitTaskNeedModId, "链接逾期")
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateTaskLog error,err:%+v", err)
				}
				err = CreateMessageByTaskId(context.Background(), 23, 4, submitTaskNeedModId)
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateMessageByTaskId error,err:%+v", err)
				}
				fmt.Println("创建已提交链接的链接违约记录")
			}
		}
	}
	return nil
}

// GetAutoCaseCloseDefaultTask 数据质检违约
func GetAutoCaseCloseDefaultTask() error {

	// 1. 筛选出可能数据违约的种草子任务 待上传/待修改
	db := GetReadDB(context.Background())
	var projectInfos []*gorm_model.ProjectInfo
	err := db.Model(gorm_model.ProjectInfo{}).Where("project_type = ?", 1).Find(&projectInfos).Error
	if err != nil {
		return err
	}
	var projectIds []string
	// 任务id 对 项目id 的map
	taskIdToProjectIdMap := map[string]string{}
	// 项目id 对 定时任务id 的map
	projectIdToAutoTaskIdMap := map[string]int{}
	// 项目id 对 违约定时任务id 的map
	projectIdToAutoDefaultIdMap := map[string]int{}
	var taskIds []string
	for _, projectInfo := range projectInfos {
		projectIds = append(projectIds, projectInfo.ProjectID)
		projectIdToAutoTaskIdMap[projectInfo.ProjectID] = int(projectInfo.AutoTaskID)
		projectIdToAutoDefaultIdMap[projectInfo.ProjectID] = int(projectInfo.AutoDefaultID)
		var taskInfos []string
		db1 := GetReadDB(context.Background())
		db1.Select("task_id").Model(&gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = ? AND task_stage = ? AND cur_default_type = ? ", projectInfo.ProjectID, 2, 13, 0).Find(&taskInfos)
		for _, taskInfo := range taskInfos {
			taskIdToProjectIdMap[taskInfo] = projectInfo.ProjectID
			taskIds = append(taskIds, taskInfo)
		}
	}
	// 首次提交链接的任务记录id
	var taskNeedModIds []string
	// 已提交链接的任务记录id
	var submitTaskNeedModIds []string
	// taskId 对 稿费形式的 map
	taskIdToFeeFormMap := make(map[string]int)
	for _, taskId := range taskIds {
		var taskInfo gorm_model.YoungeeTaskInfo
		db3 := GetReadDB(context.Background())
		// 保存所有数据上传状态为 1  且任务状态为14 的任务记录的id
		db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskId).First(&taskInfo)
		if taskInfo.DataStatus == 1 && taskInfo.TaskStage == 13 {
			taskNeedModIds = append(taskNeedModIds, taskId)
		}
		// 保存所有数据上传状态为 3  且任务状态为14 的任务记录的id
		if taskInfo.DataStatus == 3 && taskInfo.TaskStage == 13 {
			submitTaskNeedModIds = append(submitTaskNeedModIds, taskId)
		}
		taskIdToFeeFormMap[taskId] = taskInfo.FeeForm
	}

	// 2. 对待上传数据的子任务判断
	for _, taskNeedModId := range taskNeedModIds {
		db2 := GetReadDB(context.Background())
		var CaseCloseDefault int32
		db2.Model(&gorm_model.InfoAutoTask{}).Select("case_close_default").Where("auto_task_id = ?", projectIdToAutoTaskIdMap[taskIdToProjectIdMap[taskNeedModId]]).First(&CaseCloseDefault)
		dd, _ := time.ParseDuration(conv.MustString(CaseCloseDefault, "") + "h")

		autoDefaultHandle := gorm_model.InfoAutoDefaultHandle{}
		db6 := GetReadDB(context.Background())
		db6.Model(gorm_model.InfoAutoDefaultHandle{}).Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[taskNeedModId]]).Find(&autoDefaultHandle)

		var dataDefaultRate int
		var dataErrRate int
		if taskIdToFeeFormMap[taskNeedModId] == 1 {
			dataDefaultRate = autoDefaultHandle.DataReplaceTimeOut
			dataErrRate = autoDefaultHandle.DataReplaceNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("data_replace_time_out", "data_replace_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[taskNeedModId]]).Find(&dataDefaultRate, &dataErrRate)
		} else {
			dataDefaultRate = autoDefaultHandle.DataOtherTimeOut
			dataErrRate = autoDefaultHandle.DataOtherNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("data_other_time_out", "data_other_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[taskNeedModId]]).Find(&dataDefaultRate, &dataErrRate)
		}
		//fmt.Println("dataDefaultRate:", dataDefaultRate)
		db1 := GetReadDB(context.Background())
		var taskLinkInfo gorm_model.YounggeeLinkInfo
		db1.Model(gorm_model.YounggeeLinkInfo{}).Where("task_id = ? AND is_ok = ?", taskNeedModId, 1).Find(&taskLinkInfo)
		dbTask := GetReadDB(context.Background())
		var taskInfoCurr gorm_model.YoungeeTaskInfo
		dbTask.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskNeedModId).Find(&taskInfoCurr)
		if taskInfoCurr.DataMissingTime.IsZero() {
			db1.Where("task_id = ?", taskNeedModId).Updates(&gorm_model.YounggeeLinkInfo{AutoDataBreakAt: taskLinkInfo.AgreeAt.Add(dd)})
			dbTask.Where("task_id = ?", taskNeedModId).Updates(&gorm_model.YoungeeTaskInfo{DataMissingTime: taskLinkInfo.AgreeAt.Add(dd)})
			fmt.Println("已添加数据违约自动处理时间")
		} else {
			if taskInfoCurr.TaskID != "" && taskInfoCurr.DataMissingTime.Sub(time.Now()) <= 0 {
				//db4 := GetReadDB(context.Background())
				//err1 := db4.Model(gorm_model.YoungeeContractInfo{}).Create(&gorm_model.YoungeeContractInfo{
				//	TaskID: taskNeedModId, ProjectID: taskIdToProjectIdMap[taskNeedModId], BreakType: 4, BreakAt: time.Now(), DefaultStatus: 1}).Error
				//if err1 != nil {
				//	return err1
				//}
				taskInfo := gorm_model.YoungeeTaskInfo{}
				dbt := GetReadDB(context.Background())
				err2 := dbt.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskNeedModId).Find(&taskInfo).Error
				if err2 != nil {
					return err2
				}
				// 达人实际所得
				settleAmount := taskInfo.DraftFee * (1.0 - float64(dataDefaultRate+taskInfo.DataBreakRate+taskInfo.SketchBreakRate+taskInfo.ScriptBreakRate)/100)
				if settleAmount <= 0 {
					settleAmount = 0.0
				}
				// 服务商实际所得
				realServiceCharge := taskInfo.ServiceCharge * (1.0 - float64(taskInfo.LinkBreakRate+taskInfo.DataBreakRate+dataDefaultRate+taskInfo.ScriptBreakRate)/100)
				if realServiceCharge <= 0 {
					realServiceCharge = 0.0
				}
				// 企业实际支付
				realPayment := settleAmount + realServiceCharge
				if realPayment <= 0 {
					realPayment = 0.0
				}
				fmt.Println("settleAmount: ", settleAmount)
				db3 := GetReadDB(context.Background())
				err2 = db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", taskNeedModId).Updates(
					map[string]interface{}{
						"data_missing_status": 1,
						"cur_default_type":    7,
						"sketch_break_rate":   dataDefaultRate,
						"settle_amount":       settleAmount,
						"err_break_rate":      dataErrRate,
						"real_payment":        realPayment,
						"real_service_charge": realServiceCharge,
					}).Error
				if err2 != nil {
					return err2
				}
				err = CreateTaskLog(context.Background(), taskNeedModId, "数据逾期")
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateTaskLog error,err:%+v", err)
				}
				err = CreateMessageByTaskId(context.Background(), 24, 4, taskNeedModId)
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateMessageByTaskId error,err:%+v", err)
				}
				fmt.Println("已创建数据违约记录")
			}
		}
	}

	// 3. 针对待修改的子任务
	for _, submitTaskNeedModId := range submitTaskNeedModIds {
		db2 := GetReadDB(context.Background())
		var LinkBreach int32
		db2.Model(&gorm_model.InfoAutoTask{}).Select("case_close_default").Where("auto_task_id = ?", projectIdToAutoTaskIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).First(&LinkBreach)
		dd, _ := time.ParseDuration(conv.MustString(LinkBreach, "") + "h")

		autoDefaultHandle := gorm_model.InfoAutoDefaultHandle{}
		db6 := GetReadDB(context.Background())
		db6.Model(gorm_model.InfoAutoDefaultHandle{}).Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).Find(&autoDefaultHandle)

		var dataDefaultRate int
		var dataErrRate int
		if taskIdToFeeFormMap[submitTaskNeedModId] == 1 {
			dataDefaultRate = autoDefaultHandle.DataReplaceTimeOut
			dataErrRate = autoDefaultHandle.DataReplaceNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("data_replace_time_out", "data_replace_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).Find(&dataDefaultRate, &dataErrRate)
		} else {
			dataDefaultRate = autoDefaultHandle.DataOtherTimeOut
			dataErrRate = autoDefaultHandle.DataOtherNotUpload
			// db6 := GetReadDB(context.Background())
			// db6.Model(gorm_model.InfoAutoDefaultHandle{}).Select("data_other_time_out", "data_other_not_upload").Where("auto_default_id = ?", projectIdToAutoDefaultIdMap[taskIdToProjectIdMap[submitTaskNeedModId]]).Find(&dataDefaultRate, &dataErrRate)
		}
		db1 := GetReadDB(context.Background())
		var taskDataInfo gorm_model.YounggeeDataInfo
		db1.Model(gorm_model.YounggeeDataInfo{}).Where("task_id = ? and is_review = 1", submitTaskNeedModId).Order("reject_at desc").First(&taskDataInfo)
		if taskDataInfo.AutoDataBreakAt.IsZero() {
			err4 := db1.Where("task_id = ?", submitTaskNeedModId).Updates(&gorm_model.YounggeeDataInfo{AutoDataBreakAt: taskDataInfo.RejectAt.Add(dd)}).Error
			if err4 != nil {
				return err4
			}
			fmt.Println("已添加数据违约自动处理时间")
		} else {
			if taskDataInfo.TaskID != "" && taskDataInfo.AutoDataBreakAt.Sub(time.Now()) <= 0 {
				db4 := GetReadDB(context.Background())
				err1 := db4.Model(gorm_model.YoungeeContractInfo{}).Create(&gorm_model.YoungeeContractInfo{
					TaskID: submitTaskNeedModId, ProjectID: taskIdToProjectIdMap[submitTaskNeedModId], BreakType: 4, BreakAt: time.Now(), DefaultStatus: 1}).Error
				if err1 != nil {
					return err1
				}
				taskInfo := gorm_model.YoungeeTaskInfo{}
				dbt := GetReadDB(context.Background())
				err2 := dbt.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", submitTaskNeedModId).Find(&taskInfo).Error
				if err2 != nil {
					return err2
				}
				// 达人实际所得
				settleAmount := taskInfo.DraftFee * (1.0 - float64(dataDefaultRate+taskInfo.DataBreakRate+taskInfo.SketchBreakRate+taskInfo.ScriptBreakRate)/100)
				if settleAmount <= 0 {
					settleAmount = 0.0
				}
				// 服务商实际所得
				realServiceCharge := taskInfo.ServiceCharge * (1.0 - float64(taskInfo.LinkBreakRate+taskInfo.DataBreakRate+dataDefaultRate+taskInfo.ScriptBreakRate)/100)
				if realServiceCharge <= 0 {
					realServiceCharge = 0.0
				}
				// 企业实际支付
				realPayment := settleAmount + realServiceCharge
				if realPayment <= 0 {
					realPayment = 0.0
				}
				db3 := GetReadDB(context.Background())
				err2 = db3.Model(gorm_model.YoungeeTaskInfo{}).Where("task_id = ?", submitTaskNeedModId).Updates(
					map[string]interface{}{
						"data_missing_status": 1,
						"cur_default_type":    7,
						"sketch_break_rate":   dataDefaultRate,
						"settle_amount":       settleAmount,
						"err_break_rate":      dataErrRate,
						"real_payment":        realPayment,
						"real_service_charge": realServiceCharge,
					}).Error
				if err2 != nil {
					return err2
				}
				err = CreateTaskLog(context.Background(), submitTaskNeedModId, "数据逾期")
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateTaskLog error,err:%+v", err)
				}
				err = CreateMessageByTaskId(context.Background(), 24, 4, submitTaskNeedModId)
				if err != nil {
					log.WithContext(context.Background()).Errorf("[operate db] call CreateMessageByTaskId error,err:%+v", err)
				}
				fmt.Println("创建已提交数据的数据违约记录")
			}
		}
	}
	return nil
}
