package dao

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

type SelectionInfoDAO struct{}

func (d SelectionInfoDAO) GetSelectionInfoById(selectionId string) (*entity.SelectionInfo, error) {
	var selectionInfo entity.SelectionInfo
	err := Db.Where("selection_id = ?", selectionId).First(&selectionInfo).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &selectionInfo, err
}

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

// 创建带货任务
func (d SelectionInfoDAO) CreateSelectionInfo(selectionInfo entity.SelectionInfo) error {
	err := Db.Omit("submit_at", "pass_at", "pay_at", "finish_at", "auto_fail_at").Create(&selectionInfo).Error
	if err != nil {
		return err
	}
	return nil
}

// 更新带货任务
func (d SelectionInfoDAO) UpdateSelectionInfo(selectionInfo entity.SelectionInfo) error {
	err := Db.Debug().Model(&entity.SelectionInfo{}).Where("selection_id = ?", selectionInfo.SelectionID).Updates(selectionInfo).Error
	if err != nil {
		return err
	}
	return nil
}

// 更新开票状态字段
func (d SelectionInfoDAO) UpdateInvoiceStatus(selectionIDs []string) error {
	err := Db.Model(&entity.SelectionInfo{}).Where("selection_id IN ?", selectionIDs).Updates(entity.SelectionInfo{InvoiceStatus: 1}).Error
	return err
}

// 获取带货任务列表
func (d SelectionInfoDAO) GetSelectionPreviews(param *vo.SelectionSearchParam) ([]vo.ReSelectionTaskPreview, int64, error) {
	var reSelectionTaskPreviews []vo.ReSelectionTaskPreview
	var selectionInfos []entity.SelectionInfo
	var total int64
	query := Db.Model(&entity.SelectionInfo{})
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reSelectionTaskPreviews, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.SelectionPlatform != 0 {
		query = query.Where("platform = ?", param.SelectionPlatform)
	}
	if param.SelectionStatus != 0 {
		query = query.Where("selection_status = ?", param.SelectionStatus)
	} else {
		query = query.Where("selection_status not in ?", []int{1, 3, 5})
	}
	// sample_mode 1、2、3分别表示免费领样(有领样策略)、垫付领样(3.0不用)、不提供样品(无领样策略)
	if param.FreeFlag == 1 {
		query = query.Where("sample_mode = ?", 1)
	} else if param.FreeFlag == 2 {
		query = query.Where("sample_mode = ?", 3)
	}
	// task_mode  1、2分别表示悬赏任务(有悬赏策略)、纯佣带货(无悬赏策略)
	if param.RewardFlag == 1 {
		query = query.Where("task_mode = ?", 1)
	} else if param.RewardFlag == 2 {
		query = query.Where("task_mode = ?", 2)
	}
	if param.Others != "" {
		query = query.Where("enterprise_id = ? or selection_id = ? or selection_name LIKE ?", param.Others, param.Others, "%"+param.Others+"%")
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, selection_id, platform, selection_status, created_at, task_ddl, sample_num, enroll_num, choose_num, product_id, estimated_cost")
	offset := (param.Page - 1) * param.PageSize
	if param.Order == 1 {
		if err := query.Order("selection_status desc").Order("task_ddl asc").Offset(offset).Limit(param.PageSize).Find(&selectionInfos).Error; err != nil {
			return nil, 0, err
		}
	} else {
		if err := query.Order("selection_status asc").Order("task_ddl desc").Offset(offset).Limit(param.PageSize).Find(&selectionInfos).Error; err != nil {
			return nil, 0, err
		}
	}

	for _, selectionInfo := range selectionInfos {
		reSelectionTaskPreview := vo.ReSelectionTaskPreview{
			EnterpriseId:      selectionInfo.EnterpriseID,
			SubAccountId:      selectionInfo.SubAccountId,
			SelectionId:       selectionInfo.SelectionID,
			SelectionPlatform: selectionInfo.Platform,
			SelectionStatus:   selectionInfo.SelectionStatus,
			CreatedAt:         selectionInfo.CreatedAt.Format("2006-01-02 15:04:05"),
			TaskDdl:           selectionInfo.TaskDdl.Format("2006-01-02 15:04:05"),
			SampleNum:         selectionInfo.SampleNum,
			EnrollNum:         selectionInfo.EnrollNum,
			ChooseNum:         selectionInfo.ChooseNum,
			ProductId:         selectionInfo.ProductID,
			Reward:            selectionInfo.EstimatedCost,
		}
		reSelectionTaskPreviews = append(reSelectionTaskPreviews, reSelectionTaskPreview)
	}

	return reSelectionTaskPreviews, total, nil
}

// 删除带货任务
func (d SelectionInfoDAO) DeleteSelection(selectionId string) (*string, error) {
	if selectionId == "" {
		return &selectionId, nil
	}
	err := Db.Model(&entity.SelectionInfo{}).Where("selection_id = ?", selectionId).Delete(&entity.SelectionInfo{}).Error
	if err != nil {
		return nil, err
	}
	return &selectionId, nil
}

// 获取草稿箱——电商带货任务列表
func (d SelectionInfoDAO) GetSelectionDraftList(param *vo.SelectionDraftParam) ([]vo.ReSelectionTaskPreview, int64, error) {
	var reSelectionTaskPreviews []vo.ReSelectionTaskPreview
	var selectionInfos []entity.SelectionInfo
	var total int64
	query := Db.Model(&entity.SelectionInfo{}).Where("selection_status = ?", 1)
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reSelectionTaskPreviews, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.SelectionPlatform != 0 {
		query = query.Where("platform = ?", param.SelectionPlatform)
	}
	if param.Others != "" {
		query = query.Where("enterprise_id = ? or selection_id = ? or selection_name LIKE ?", param.Others, param.Others, "%"+param.Others+"%")
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, selection_id, platform, created_at, product_id")
	offset := (param.Page - 1) * param.PageSize
	if err := query.Order("created_at asc").Offset(offset).Limit(param.PageSize).Find(&selectionInfos).Error; err != nil {
		return nil, 0, err
	}
	for _, selectionInfo := range selectionInfos {
		reSelectionTaskPreview := vo.ReSelectionTaskPreview{
			EnterpriseId:      selectionInfo.EnterpriseID,
			SubAccountId:      selectionInfo.SubAccountId,
			SelectionId:       selectionInfo.SelectionID,
			SelectionPlatform: selectionInfo.Platform,
			CreatedAt:         selectionInfo.CreatedAt.Format("2006-01-02 15:04:05"),
			ProductId:         selectionInfo.ProductID,
		}
		reSelectionTaskPreviews = append(reSelectionTaskPreviews, reSelectionTaskPreview)
	}

	return reSelectionTaskPreviews, total, nil
}

// 获取电商带货悬赏任务中全部指定状态值的项目
func (d SelectionInfoDAO) GetSelectionInfoList(value int64, fieldName string) ([]*entity.SelectionInfo, error) {
	var selectionInfos []*entity.SelectionInfo
	err := Db.Model(entity.SelectionInfo{}).Where(fmt.Sprintf("task_mode = ? AND %s = ? ", fieldName), 1, value).Find(&selectionInfos).Error
	if err != nil {
		return nil, err
	}
	return selectionInfos, nil
}

// 获取电商带货冻结中的任务
func (d SelectionInfoDAO) GetSelectionFrozenList(enterpriseId string) ([]*entity.SelectionInfo, error) {
	var selectionInfos []*entity.SelectionInfo
	query := Db.Debug().Model(entity.SelectionInfo{})
	query.Select("selection_id, product_id, enterprise_id, sub_account_id, platform, estimated_cost, pay_at") // 冻结金额：estimated_cost
	err := query.Where(fmt.Sprintf("enterprise_id = ? AND (selection_status between 5 and 6) "), enterpriseId).Find(&selectionInfos).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return selectionInfos, nil
		} else {
			return nil, err
		}
	}
	return selectionInfos, nil
}

// 获取电商带货冻结解除的任务
func (d SelectionInfoDAO) GetSelectionFrozenCancelList(enterpriseId string) ([]*entity.SelectionInfo, error) {
	var selectionInfos []*entity.SelectionInfo
	query := Db.Debug().Model(entity.SelectionInfo{})
	query.Select("selection_id, product_id, enterprise_id, sub_account_id, platform, settlement_amount, pay_at") // 解冻金额：settlement_amount
	err := query.Where(fmt.Sprintf("enterprise_id = ? AND (selection_status between 7 and 8) "), enterpriseId).Find(&selectionInfos).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return selectionInfos, nil
		} else {
			return nil, err
		}
	}
	return selectionInfos, nil
}

// 获取带货账单列表
func (d SelectionInfoDAO) GetBillSelectionPreviews(param *vo.SelectionSearchParam) ([]vo.ReBillSelectionTaskPreview, int64, error) {
	var reBillSelectionTaskPreviews []vo.ReBillSelectionTaskPreview
	var selectionInfos []entity.SelectionInfo
	var total int64
	query := Db.Model(&entity.SelectionInfo{})
	// 动态添加查询条件
	if param.SubAccountId == 0 {
		if param.EnterpriseId == "" {
			return reBillSelectionTaskPreviews, 0, errors.New("enterpriseId is empty")
		}
		query = query.Where("enterprise_id = ?", param.EnterpriseId)
	} else {
		query = query.Where("sub_account_id = ?", param.SubAccountId)
	}
	if param.SelectionPlatform != 0 {
		query = query.Where("platform = ?", param.SelectionPlatform)
	}
	if param.SelectionStatus != 0 {
		query = query.Where("selection_status = ?", param.SelectionStatus)
	}
	if param.Others != "" {
		query = query.Where("enterprise_id = ? or selection_id = ? or selection_name LIKE ?", param.Others, param.Others, "%"+param.Others+"%")
	}
	query.Count(&total)
	query = query.Select("enterprise_id, sub_account_id, selection_id, platform, selection_status, created_at, task_ddl, product_id, settlement_amount")
	offset := (param.Page - 1) * param.PageSize
	if err := query.Order("created_at asc").Offset(offset).Limit(param.PageSize).Find(&selectionInfos).Error; err != nil {
		return nil, 0, err
	}
	for _, selectionInfo := range selectionInfos {
		reBillSelectionTaskPreview := vo.ReBillSelectionTaskPreview{
			EnterpriseId:      selectionInfo.EnterpriseID,
			SubAccountId:      selectionInfo.SubAccountId,
			SelectionId:       selectionInfo.SelectionID,
			SelectionPlatform: selectionInfo.Platform,
			SelectionStatus:   selectionInfo.SelectionStatus,
			CreatedAt:         selectionInfo.CreatedAt.Format("2006-01-02 15:04:05"),
			TaskDdl:           selectionInfo.TaskDdl.Format("2006-01-02 15:04:05"),
			ProductId:         selectionInfo.ProductID,
			CashAmount:        selectionInfo.SettlementAmount,
		}
		reBillSelectionTaskPreviews = append(reBillSelectionTaskPreviews, reBillSelectionTaskPreview)
	}

	return reBillSelectionTaskPreviews, total, nil
}

// 电商带货任务待办
func (d SelectionInfoDAO) GetSelectionToDo(enterpriseId string, subAccountId int64, platform int64) (map[string]int64, error) {
	resultMap := make(map[string]int64)
	var needReview int64
	var needPay int64
	var needProcess int64
	var selectionInfos []entity.SelectionInfo
	//query := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
	if subAccountId == 0 {
		// 待审核、待支付、达人未处理
		query1 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		query1.Where("selection_status = ?", 2).Count(&needReview)
		query2 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		query2.Where("selection_status = ?", 4).Count(&needPay)
		query3 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		err := query3.Where("selection_status = ? and sample_mode = ?", 6, 1).Select("selection_id").Find(&selectionInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needProcess = 0
			} else {
				return resultMap, err
			}
		} else {
			var selectionIDs []string
			for _, info := range selectionInfos {
				selectionIDs = append(selectionIDs, info.SelectionID)
			}
			if len(selectionIDs) > 0 {
				err1 := Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id in ? and task_status = ?", selectionIDs, 1).Count(&needProcess).Error // task_status=1待选
				if err1 != nil {
					needProcess = 0
				}
			}
		}
	} else {
		// 待审核、待支付、达人未处理
		query1 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		query1.Where("sub_account_id = ? and selection_status = ?", subAccountId, 2).Count(&needReview)
		query2 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		query2.Where("sub_account_id = ? and selection_status = ?", subAccountId, 4).Count(&needPay)
		query3 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		err := query3.Where("sub_account_id = ? and selection_status = ? and sample_mode = ?", subAccountId, 6, 1).Select("selection_id").Find(&selectionInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needProcess = 0
			} else {
				return resultMap, err
			}
		} else {
			var selectionIDs []string
			for _, info := range selectionInfos {
				selectionIDs = append(selectionIDs, info.SelectionID)
			}
			if len(selectionIDs) > 0 {
				err1 := Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id in ? and task_status = ?", selectionIDs, 1).Count(&needProcess).Error // task_status=1待选
				if err1 != nil {
					needProcess = 0
				}
			}
		}
	}
	resultMap["needReview"] = needReview
	resultMap["needPay"] = needPay
	resultMap["needProcess"] = needProcess

	return resultMap, nil
}

// 寄样物流任务待办
func (d SelectionInfoDAO) GetLogisticsToDo(enterpriseId string, subAccountId int64, platform int64) (map[string]int64, error) {
	resultMap := make(map[string]int64)
	var needDelivery int64
	var needReceive int64
	var selectionInfos []entity.SelectionInfo
	//query := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
	if subAccountId == 0 {
		// 待发货、待签收
		query1 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		err := query1.Where("selection_status = ? and sample_mode = ?", 6, 1).Select("selection_id").Find(&selectionInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needDelivery = 0
				needReceive = 0
			} else {
				return resultMap, err
			}
		} else {
			var selectionIDs []string
			for _, info := range selectionInfos {
				selectionIDs = append(selectionIDs, info.SelectionID)
			}
			if len(selectionIDs) > 0 {
				err1 := Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id in ? and logistics_status = ?", selectionIDs, 1).Count(&needDelivery).Error // logistics_status=1待发货
				if err1 != nil {
					needDelivery = 0
				}
				err2 := Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id in ? and logistics_status = ?", selectionIDs, 2).Count(&needReceive).Error // logistics_status=2待签收
				if err2 != nil {
					needReceive = 0
				}
			}
		}
	} else {
		query1 := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and platform = ?", enterpriseId, platform)
		err := query1.Where("sub_account_id = ? and selection_status = ? and sample_mode = ?", subAccountId, 6, 1).Select("selection_id").Find(&selectionInfos).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				needDelivery = 0
				needReceive = 0
			} else {
				return resultMap, err
			}
		} else {
			var selectionIDs []string
			for _, info := range selectionInfos {
				selectionIDs = append(selectionIDs, info.SelectionID)
			}
			if len(selectionIDs) > 0 {
				err1 := Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id in ? and logistics_status = ?", selectionIDs, 1).Count(&needDelivery).Error // logistics_status=1待发货
				if err1 != nil {
					needDelivery = 0
				}
				err2 := Db.Model(&entity.SelectionTaskInfo{}).Where("selection_id in ? and logistics_status = ?", selectionIDs, 2).Count(&needReceive).Error // logistics_status=2待签收
				if err2 != nil {
					needReceive = 0
				}
			}
		}
	}
	resultMap["needDelivery"] = needDelivery
	resultMap["needReceive"] = needReceive

	return resultMap, nil
}

// 获取指定商家已结案的指定开票状态数据
func (d SelectionInfoDAO) GetSelectionFinished(enterpriseId string, invoiceStatus int64) (float64, error) {
	var selectionAmount float64
	err := Db.Model(&entity.SelectionInfo{}).Where("enterprise_id = ? and selection_status = ? and invoice_status = ?", enterpriseId, 8, invoiceStatus).Select("COALESCE(SUM(settlement_amount), 0)").Scan(&selectionAmount).Error
	if err != nil {
		return 0, err
	}
	return selectionAmount, err
}
