package dao

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"time"
	"youngee_b_api/app/entity"
	"youngee_b_api/app/vo"
)

type ProjectDAO struct{}

// 根据projectId获取project信息
func (d ProjectDAO) GetProjectById(projectId string) (*entity.Project, error) {
	var project entity.Project
	err := Db.Where("project_id = ?", projectId).First(&project).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &project, err
}

// 根据projectId获取违约状态id
func (d ProjectDAO) GetAutoDefaultId(projectId string) (*int64, error) {
	var autoDefaultId int64
	err := Db.Model(&entity.Project{}).Where("project_id = ?", projectId).Select("auto_default_id").Find(&autoDefaultId).Error
	if err != nil {
		return nil, nil
	}
	return &autoDefaultId, nil
}

// 根据enterpriseId查询指定某天的所有带货数据
func (d ProjectDAO) GetProjectListOfDay(enterpriseId string, date time.Time) ([]entity.Project, error) {
	var projects []entity.Project
	// 构建查询
	query := Db.Model(&entity.Project{})
	if enterpriseId != "" {
		query = query.Where("enterprise_id = ?", enterpriseId)
	}
	// 将日期部分提取出来进行匹配
	query = query.Where("DATE(created_at) = ?", date.Format("2006-01-02"))
	err := query.Find(&projects).Error
	return projects, err
}

// 创建种草任务
func (d ProjectDAO) CreateProject(project entity.Project) error {
	err := Db.Omit("auto_fail_at", "auto_script_break_at", "auto_sketch_break_at", "pay_at", "pass_at", "finish_at", "submit_at").Create(&project).Error
	if err != nil {
		return err
	}
	return nil
}

// 更新种草任务
func (d ProjectDAO) UpdateProject(project entity.Project) error {
	err := Db.Model(&entity.Project{}).Where("project_id = ?", project.ProjectId).Updates(project).Error
	if err != nil {
		return err
	}
	return nil
}

// 更新开票状态字段
func (d ProjectDAO) UpdateInvoiceStatus(projectIDs []string) error {
	err := Db.Debug().Model(&entity.Project{}).Where("project_id IN ?", projectIDs).Updates(entity.Project{InvoiceStatus: 1}).Error
	if err != nil {
		return err
	}
	return nil
}

// 获取种草任务列表
func (d ProjectDAO) GetProjectPreviews(param *vo.ProjectSearchParam) ([]vo.ReProjectTaskPreview, int64, error) {
	var reProjectTaskPreviews []vo.ReProjectTaskPreview
	var projects []entity.Project
	var total int64
	query := Db.Model(&entity.Project{})
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reProjectTaskPreviews, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.ProjectType != 0 {
		query = query.Where("project_type = ?", param.ProjectType)
	}
	if param.ProjectPlatform != 0 {
		query = query.Where("project_platform = ?", param.ProjectPlatform)
	}
	if param.ProjectStatus != 0 {
		query = query.Where("project_status = ?", param.ProjectStatus)
	} else {
		query = query.Where("project_status not in ?", []int{1, 3})
	}
	if param.ProjectForm != 0 {
		query = query.Where("project_form = ?", param.ProjectForm)
	}
	if param.ContentType != 0 {
		query = query.Where("content_type = ?", param.ContentType)
	}
	if param.Others != "" {
		query = query.Where("enterprise_id = ? or project_id = ? or project_name LIKE ?", param.Others, param.Others, "%"+param.Others+"%")
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, project_id, project_platform, project_status, estimated_cost, need_pay, project_form, content_type, need_review, need_quality, need_calculate, before_delivery_num, delivery_num, after_delivery_num, product_id, tools")
	offset := (param.Page - 1) * param.PageSize
	if param.Order == 1 {
		if err := query.Order("created_at asc").Offset(offset).Limit(param.PageSize).Find(&projects).Error; err != nil {
			return nil, 0, err
		}
	} else {
		if err := query.Order("created_at desc").Offset(offset).Limit(param.PageSize).Find(&projects).Error; err != nil {
			return nil, 0, err
		}
	}
	for _, project := range projects {
		// 获取种草待筛选达人数
		projectId := project.ProjectId
		needFilter := ProjectTaskInfoDao{}.CountByTaskStage(projectId, 1)

		reProjectTaskPreview := vo.ReProjectTaskPreview{
			EnterpriseId:    project.EnterpriseID,
			SubAccountId:    project.SubAccountId,
			ProjectId:       project.ProjectId,
			ProjectPlatform: project.ProjectPlatform,
			ProjectStatus:   project.ProjectStatus,
			ProjectForm:     project.ProjectForm,
			ContentType:     project.ContentType,
			NeedReview:      project.NeedReview,
			NeedQuality:     project.NeedQuality,
			NeedCalculate:   project.NeedCalculate,
			ProductId:       project.ProductID,
			Tools:           project.Tools,
			NeedDelivery:    project.BeforeDeliveryNum,
			NeedReceive:     project.DeliveryNum,
			Received:        project.AfterDeliveryNum,
			NeedFilter:      needFilter,
		}
		if project.ProjectStatus < 6 {
			reProjectTaskPreview.EstimatedCost = project.EstimatedCost
		} else {
			reProjectTaskPreview.EstimatedCost = project.NeedPay
		}
		reProjectTaskPreviews = append(reProjectTaskPreviews, reProjectTaskPreview)
	}

	return reProjectTaskPreviews, total, nil
}

// 删除种草任务
func (d ProjectDAO) DeleteProject(projectId string) (*string, error) {
	if projectId == "" {
		return &projectId, nil
	}
	err := Db.Model(&entity.Project{}).Where("project_id = ?", projectId).Delete(&entity.Project{}).Error
	if err != nil {
		return nil, err
	}
	return &projectId, nil
}

// 获取草稿箱——种草任务列表
func (d ProjectDAO) GetProjectDraftList(param *vo.ProjectDraftParam) ([]vo.ReProjectTaskPreview, int64, error) {
	var reProjectTaskPreviews []vo.ReProjectTaskPreview
	var projects []entity.Project
	var total int64
	query := Db.Model(&entity.Project{}).Where("project_status = ?", 1)
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reProjectTaskPreviews, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.ProjectType != 0 {
		query = query.Where("project_type = ?", param.ProjectType)
	}
	if param.ProjectPlatform != 0 {
		query = query.Where("project_platform = ?", param.ProjectPlatform)
	}
	if param.Others != "" {
		query = query.Where("enterprise_id = ? or project_id = ? or project_name LIKE ?", param.Others, param.Others, "%"+param.Others+"%")
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, project_id, project_platform, project_type, created_at, product_id")
	offset := (param.Page - 1) * param.PageSize
	if err := query.Order("created_at asc").Offset(offset).Limit(param.PageSize).Find(&projects).Error; err != nil {
		return nil, 0, err
	}
	for _, project := range projects {
		reProjectTaskPreview := vo.ReProjectTaskPreview{
			EnterpriseId:    project.EnterpriseID,
			SubAccountId:    project.SubAccountId,
			ProjectId:       project.ProjectId,
			ProjectPlatform: project.ProjectPlatform,
			ProjectType:     project.ProjectType,
			CreatedAt:       project.CreatedAt.Format("2006-01-02 15:04:05"),
			ProductId:       project.ProductID,
		}
		reProjectTaskPreviews = append(reProjectTaskPreviews, reProjectTaskPreview)
	}

	return reProjectTaskPreviews, total, nil
}

// 获取公开种草中全部指定状态值的项目
func (d ProjectDAO) GetProjectList(value int64, fieldName string) ([]*entity.Project, error) {
	var projectInfos []*entity.Project
	err := Db.Model(entity.Project{}).Where(fmt.Sprintf("%s = ? ", fieldName), value).Find(&projectInfos).Error
	if err != nil {
		return nil, err
	}
	return projectInfos, nil
}

// 违约管理——违约公开种草任务列表
func (d ProjectDAO) GetProjectPublicList(param *vo.DefaultSearchParam) ([]vo.ReTaskDefaultPublic, int64, error) {
	var reTaskDefaultPublics []vo.ReTaskDefaultPublic
	var projects []entity.Project
	var total int64
	query := Db.Model(&entity.Project{}).Where("project_type = ?", 1)
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reTaskDefaultPublics, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.Platform != 0 {
		query = query.Where("project_platform = ?", param.Platform)
	}
	if param.TaskId != "" {
		query = query.Where("project_id = ?", param.TaskId)
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, project_id, project_platform, project_form, content_type, product_id")
	offset := (param.Page - 1) * param.PageSize
	if err := query.Order("created_at asc").Offset(offset).Limit(param.PageSize).Find(&projects).Error; err != nil {
		return nil, 0, err
	}
	for _, project := range projects {
		reTaskDefaultPublic := vo.ReTaskDefaultPublic{
			EnterpriseId: project.EnterpriseID,
			SubAccountId: project.SubAccountId,
			TaskId:       project.ProjectId,
			Platform:     project.ProjectPlatform,
			TaskForm:     project.ProjectForm,
			ContentType:  project.ContentType,
			TaskType:     1,
			ProductId:    project.ProductID,
		}
		reTaskDefaultPublics = append(reTaskDefaultPublics, reTaskDefaultPublic)
	}

	return reTaskDefaultPublics, total, nil
}

// 违约管理——违约定向种草任务列表
func (d ProjectDAO) GetProjectTargetList(param *vo.DefaultSearchParam) ([]vo.ReTaskDefaultTarget, int64, error) {
	var reTaskDefaultTargets []vo.ReTaskDefaultTarget
	var projects []entity.Project
	var total int64
	query := Db.Model(&entity.Project{}).Where("project_type = ?", 2)
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reTaskDefaultTargets, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.Platform != 0 {
		query = query.Where("project_platform = ?", param.Platform)
	}
	if param.TaskId != "" {
		query = query.Where("project_id = ?", param.TaskId)
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, project_id, project_platform, tools, content_type, product_id")
	offset := (param.Page - 1) * param.PageSize
	if err := query.Order("created_at asc").Offset(offset).Limit(param.PageSize).Find(&projects).Error; err != nil {
		return nil, 0, err
	}
	for _, project := range projects {
		reTaskDefaultPublic := vo.ReTaskDefaultTarget{
			EnterpriseId: project.EnterpriseID,
			SubAccountId: project.SubAccountId,
			TaskId:       project.ProjectId,
			Platform:     project.ProjectPlatform,
			Tools:        project.Tools,
			ContentType:  project.ContentType,
			TaskType:     1,
			ProductId:    project.ProductID,
		}
		reTaskDefaultTargets = append(reTaskDefaultTargets, reTaskDefaultPublic)
	}

	return reTaskDefaultTargets, total, nil
}

// 获取品牌种草冻结中的任务
func (d ProjectDAO) GetProjectFrozenList(enterpriseId string) ([]*entity.Project, error) {
	var projects []*entity.Project
	query := Db.Debug().Model(entity.Project{})
	query.Select("project_id, product_id, enterprise_id, sub_account_id, project_platform, payment_amount, pay_at") // 冻结金额：payment_amount
	err := query.Where(fmt.Sprintf("enterprise_id = ? AND project_type = ? AND (project_status between 7 and 8) "), enterpriseId, 1).Find(&projects).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return projects, nil
		} else {
			return nil, err
		}
	}
	return projects, nil
}

// 获取品牌种草冻结解除的任务
func (d ProjectDAO) GetProjectFrozenCancelList(enterpriseId string) ([]*entity.Project, error) {
	var projects []*entity.Project
	query := Db.Debug().Model(entity.Project{})
	query.Select("project_id, product_id, enterprise_id, sub_account_id, project_platform, settlement_amount, pay_at") // 解冻金额：settlement_amount
	err := query.Where(fmt.Sprintf("enterprise_id = ? AND project_type = ? AND (project_status between 9 and 10) "), enterpriseId, 1).Find(&projects).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return projects, nil
		} else {
			return nil, err
		}
	}
	return projects, nil
}

// 获取品牌种草账单列表
func (d ProjectDAO) GetBillProjectPreviews(param *vo.ProjectSearchParam) ([]vo.ReBillProjectTaskPreview, int64, error) {
	var reBillProjectTaskPreviews []vo.ReBillProjectTaskPreview
	var projects []entity.Project
	var total int64
	query := Db.Model(&entity.Project{})
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reBillProjectTaskPreviews, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.ProjectType != 0 {
		query = query.Where("project_type = ?", param.ProjectType)
	}
	if param.ProjectPlatform != 0 {
		query = query.Where("project_platform = ?", param.ProjectPlatform)
	}
	if param.ProjectStatus != 0 {
		query = query.Where("project_status = ?", param.ProjectStatus)
	}
	if param.Others != "" {
		query = query.Where("enterprise_id = ? or project_id = ? or project_name LIKE ?", param.Others, param.Others, "%"+param.Others+"%")
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, project_id, project_platform, project_status, estimated_cost, need_pay, project_form, content_type, product_id, settlement_amount")
	offset := (param.Page - 1) * param.PageSize
	if err := query.Order("created_at asc").Offset(offset).Limit(param.PageSize).Find(&projects).Error; err != nil {
		return nil, 0, err
	}
	for _, project := range projects {
		reBillProjectTaskPreview := vo.ReBillProjectTaskPreview{
			EnterpriseId:    project.EnterpriseID,
			SubAccountId:    project.SubAccountId,
			ProjectId:       project.ProjectId,
			ProjectPlatform: project.ProjectPlatform,
			ProjectStatus:   project.ProjectStatus,
			ProjectForm:     project.ProjectForm,
			ContentType:     project.ContentType,
			ProductId:       project.ProductID,
			EstimatedCost:   project.EstimatedCost,    // 应付金额
			CashAmount:      project.SettlementAmount, //实际结算金额
		}
		if project.ProjectStatus < 6 {
			reBillProjectTaskPreview.EstimatedCost = project.EstimatedCost
		} else {
			reBillProjectTaskPreview.EstimatedCost = project.NeedPay
		}
		reBillProjectTaskPreviews = append(reBillProjectTaskPreviews, reBillProjectTaskPreview)
	}

	return reBillProjectTaskPreviews, total, nil
}

// 种草任务待办
func (d ProjectDAO) GetProjectToDo(enterpriseId string, subAccountId int64, platform int64, taskType int64) (map[string]int64, error) {
	resultMap := make(map[string]int64)
	var needReview int64 // 待审核
	var needPay int64
	var needProcess int64
	var needCheck int64     // 初稿待审
	var needQuality int64   // 链接待审
	var needCalculate int64 // 待结算
	var projectInfos []entity.Project
	//query := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
	if subAccountId == 0 {
		// 待审核、待支付、达人未处理、初稿待审、链接待审、待结算
		query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		query1.Where("project_status = ?", 2).Count(&needReview)
		query2 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		query2.Debug().Where("project_status = ?", 6).Count(&needPay)
		query3 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		err := query3.Where("project_status = ?", 8).Select("project_id").Find(&projectInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needProcess = 0
			} else {
				return resultMap, err
			}
		} else if len(projectInfos) > 0 {
			var projectIDs []string
			for _, info := range projectInfos {
				projectIDs = append(projectIDs, info.ProjectId)
			}
			if len(projectIDs) > 0 {
				err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_status = ?", projectIDs, 1).Count(&needProcess).Error // task_status=1待选
				if err1 != nil {
					needProcess = 0
				}
			}
		}
		query4 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		err1 := query4.Select("need_review, need_quality, need_calculate").Find(&projectInfos).Error
		if err1 != nil {
			return resultMap, err1
		} else if len(projectInfos) > 0 {
			for _, info := range projectInfos {
				needCheck += info.NeedReview
				needQuality += info.NeedQuality
				needCalculate += info.NeedCalculate
			}
		}
	} else {
		// 待审核、待支付、达人未处理、初稿待审、链接待审、待结算
		query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		query1.Where("sub_account_id = ? and project_status = ?", subAccountId, 2).Count(&needReview)
		query2 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		query2.Where("sub_account_id = ? and project_status = ?", subAccountId, 6).Count(&needPay)
		query3 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		err := query3.Where("sub_account_id = ? and project_status = ?", subAccountId, 8).Select("project_id").Find(&projectInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needProcess = 0
			} else {
				return resultMap, err
			}
		} else {
			var projectIDs []string
			for _, info := range projectInfos {
				projectIDs = append(projectIDs, info.ProjectId)
			}
			if len(projectIDs) > 0 {
				err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_status = ?", projectIDs, 1).Count(&needProcess).Error // task_status=1待选
				if err1 != nil {
					needProcess = 0
				}
			}
		}
		query4 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		err1 := query4.Select("need_review, need_quality, need_calculate").Find(&projectInfos).Error
		if err1 != nil {
			return resultMap, err1
		} else if len(projectInfos) > 0 {
			for _, info := range projectInfos {
				needCheck += info.NeedReview
				needQuality += info.NeedQuality
				needCalculate += info.NeedCalculate
			}
		}
	}
	resultMap["needReview"] = needReview
	resultMap["needPay"] = needPay
	resultMap["needProcess"] = needProcess
	resultMap["needCheck"] = needCheck
	resultMap["needQuality"] = needQuality
	resultMap["needCalculate"] = needCalculate

	return resultMap, nil
}

// 寄样物流任务待办
func (d ProjectDAO) GetLogisticsToDo(enterpriseId string, subAccountId int64, platform int64) (map[string]int64, error) {
	resultMap := make(map[string]int64)
	var needDelivery int64
	var needReceive int64
	var projectInfos []entity.Project
	//query := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
	if subAccountId == 0 {
		// 待发货、待签收
		query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_form = ?", enterpriseId, platform, 1)
		err := query1.Where("project_status = ?", 8).Select("project_id").Find(&projectInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needDelivery = 0
				needReceive = 0
			} else {
				return resultMap, err
			}
		} else if len(projectInfos) > 0 {
			var projectIDs []string
			for _, info := range projectInfos {
				projectIDs = append(projectIDs, info.ProjectId)
			}
			if len(projectIDs) > 0 {
				err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 4).Count(&needDelivery).Error // task_stage=4待发货
				if err1 != nil {
					needDelivery = 0
				}
				err2 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 5).Count(&needReceive).Error // task_stage=5已发货
				if err2 != nil {
					needReceive = 0
				}
			}
		}
	} else {
		// 待发货、待签收
		query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_form = ?", enterpriseId, platform, 1)
		err := query1.Where("sub_account_id = ? and project_status = ?", subAccountId, 8).Select("project_id").Find(&projectInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needDelivery = 0
				needReceive = 0
			} else {
				return resultMap, err
			}
		} else {
			var projectIDs []string
			for _, info := range projectInfos {
				projectIDs = append(projectIDs, info.ProjectId)
			}
			if len(projectIDs) > 0 {
				err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 4).Count(&needDelivery).Error // task_stage=4待发货
				if err1 != nil {
					needDelivery = 0
				}
				err2 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 5).Count(&needReceive).Error // task_stage=5已发货
				if err2 != nil {
					needReceive = 0
				}
			}
		}
	}
	resultMap["needDelivery"] = needDelivery
	resultMap["needReceive"] = needReceive

	return resultMap, nil
}

// 违约管理任务待办
func (d ProjectDAO) GetDefaultToDo(enterpriseId string, subAccountId int64, platform int64, taskType int64) (map[string]int64, error) {
	resultMap := make(map[string]int64)
	var noSketch int64      // 未传初稿
	var noWork int64        // 未发作品
	var noData int64        // 未传数据
	var cooperateOver int64 // 终止合作
	var projectInfos []entity.Project
	//query := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
	if subAccountId == 0 {
		// 未传初稿、未发作品、未传数据、终止合作
		query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		err := query1.Where("project_status >= ?", 8).Select("project_id").Find(&projectInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				noSketch = 0
				noWork = 0
				noData = 0
				cooperateOver = 0
			} else {
				return resultMap, err
			}
		} else if len(projectInfos) > 0 {
			var projectIDs []string
			for _, info := range projectInfos {
				projectIDs = append(projectIDs, info.ProjectId)
			}
			if len(projectIDs) > 0 {
				err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 4).Count(&noSketch).Error // cur_default_type=4 初稿未上传违约
				if err1 != nil {
					noSketch = 0
				}
				err2 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 6).Count(&noWork).Error // cur_default_type=6 链接未上传违约
				if err2 != nil {
					noWork = 0
				}
				err3 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 8).Count(&noData).Error // cur_default_type=8 数据未上传违约
				if err3 != nil {
					noData = 0
				}
				err4 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 10).Count(&cooperateOver).Error // cur_default_type=10 解约
				if err4 != nil {
					cooperateOver = 0
				}
			}
		}
	} else {
		// 未传初稿、未发作品、未传数据、终止合作
		query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
		err := query1.Where("sub_account_id = ? and project_status >= ?", subAccountId, 8).Select("project_id").Find(&projectInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				noSketch = 0
				noWork = 0
				noData = 0
				cooperateOver = 0
			} else {
				return resultMap, err
			}
		} else if len(projectInfos) > 0 {
			var projectIDs []string
			for _, info := range projectInfos {
				projectIDs = append(projectIDs, info.ProjectId)
			}
			if len(projectIDs) > 0 {
				err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 4).Count(&noSketch).Error // cur_default_type=4 初稿未上传违约
				if err1 != nil {
					noSketch = 0
				}
				err2 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 6).Count(&noWork).Error // cur_default_type=6 链接未上传违约
				if err2 != nil {
					noWork = 0
				}
				err3 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 8).Count(&noData).Error // cur_default_type=8 数据未上传违约
				if err3 != nil {
					noData = 0
				}
				err4 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and cur_default_type = ?", projectIDs, 10).Count(&cooperateOver).Error // cur_default_type=10 解约
				if err4 != nil {
					cooperateOver = 0
				}
			}
		}
	}
	resultMap["noSketch"] = noSketch
	resultMap["noWork"] = noWork
	resultMap["noData"] = noData
	resultMap["cooperateOver"] = cooperateOver

	return resultMap, nil
}

// 获取指定商家已结案的指定开票状态数据
func (d ProjectDAO) GetProjectFinished(enterpriseId string, invoiceStatus int64) (float64, error) {
	var projectAmount float64
	err := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_status = ? and invoice_status = ?", enterpriseId, 10, invoiceStatus).Select("COALESCE(SUM(settlement_amount), 0)").Find(&projectAmount).Error
	if err != nil {
		return 0, err
	}
	return projectAmount, err
}

// 寄样物流任务待办
func (d ProjectDAO) GetTaskInviteToDo(enterpriseId string, subAccountId int64, platform int64) (map[string]int64, error) {
	resultMap := make(map[string]int64)
	var availInvitationNum int64
	var invitingNum int64
	var cooperatingNum int64
	//var projectInfos []entity.Project
	////query := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_type = ?", enterpriseId, platform, taskType)
	//if subAccountId == 0 {
	//	// 待发货、待签收
	//	query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_form = ?", enterpriseId, platform, 1)
	//	err := query1.Where("project_status = ?", 8).Select("project_id").Find(&projectInfos).Error
	//	if err != nil {
	//		if errors.Is(err, gorm.ErrRecordNotFound) {
	//			needDelivery = 0
	//			needReceive = 0
	//		} else {
	//			return resultMap, err
	//		}
	//	} else if len(projectInfos) > 0 {
	//		var projectIDs []string
	//		for _, info := range projectInfos {
	//			projectIDs = append(projectIDs, info.ProjectId)
	//		}
	//		if len(projectIDs) > 0 {
	//			err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 4).Count(&needDelivery).Error // task_stage=4待发货
	//			if err1 != nil {
	//				needDelivery = 0
	//			}
	//			err2 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 5).Count(&needReceive).Error // task_stage=5已发货
	//			if err2 != nil {
	//				needReceive = 0
	//			}
	//		}
	//	}
	//} else {
	//	// 待发货、待签收
	//	query1 := Db.Model(&entity.Project{}).Where("enterprise_id = ? and project_platform = ? and project_form = ?", enterpriseId, platform, 1)
	//	err := query1.Where("sub_account_id = ? and project_status = ?", subAccountId, 8).Select("project_id").Find(&projectInfos).Error
	//	if err != nil {
	//		if errors.Is(err, gorm.ErrRecordNotFound) {
	//			needDelivery = 0
	//			needReceive = 0
	//		} else {
	//			return resultMap, err
	//		}
	//	} else {
	//		var projectIDs []string
	//		for _, info := range projectInfos {
	//			projectIDs = append(projectIDs, info.ProjectId)
	//		}
	//		if len(projectIDs) > 0 {
	//			err1 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 4).Count(&needDelivery).Error // task_stage=4待发货
	//			if err1 != nil {
	//				needDelivery = 0
	//			}
	//			err2 := Db.Model(&entity.ProjectTaskInfo{}).Where("project_id in ? and task_stage = ?", projectIDs, 5).Count(&needReceive).Error // task_stage=5已发货
	//			if err2 != nil {
	//				needReceive = 0
	//			}
	//		}
	//	}
	//}
	resultMap["availInvitationNum"] = availInvitationNum
	resultMap["invitingNum"] = invitingNum
	resultMap["cooperatingNum"] = cooperatingNum

	return resultMap, nil
}
