package db

import (
	"context"
	"fmt"
	"reflect"
	"strings"
	"time"
	"youngee_b_api/consts"
	"youngee_b_api/model/common_model"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"
	"youngee_b_api/pack"
	"youngee_b_api/util"

	"github.com/issue9/conv"

	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

func CreateProject(ctx context.Context, projectInfo gorm_model.ProjectInfo) (*string, error) {
	db := GetWriteDB(ctx)
	err := db.Create(&projectInfo).Error
	if err != nil {
		return nil, err
	}
	return &projectInfo.ProjectID, nil
}
func UpdateProject(ctx context.Context, project gorm_model.ProjectInfo) (*string, error) {
	db := GetReadDB(ctx)
	err := db.Model(&project).Updates(project).Error
	if err != nil {
		return nil, err
	}
	return &project.ProjectID, nil
}

func DeleteProject(ctx context.Context, projectID string) (*string, error) {
	db := GetReadDB(ctx)
	err := db.Where("project_id = ?", projectID).Delete(&gorm_model.ProjectInfo{}).Error
	if err != nil {
		return nil, err
	}
	return &projectID, nil
}

func GetFullProjectList(ctx context.Context, pageSize, pageNum int32, condition *common_model.ProjectCondition) ([]*gorm_model.ProjectInfo, int64, error) {
	db := GetReadDB(ctx)

	// 根据带货任务状态过滤
	db = db.Debug().Model(gorm_model.ProjectInfo{}).Where("project_status = 4")

	// 根据Project条件过滤
	conditionType := reflect.TypeOf(condition).Elem()
	conditionValue := reflect.ValueOf(condition).Elem()
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if (tag == "project_id" || tag == "project_name") && !util.IsBlank(value) {
			db = db.Where(fmt.Sprintf("project_id like '%%%v%%' or project_name like '%%%v%%'", value.Interface(), value.Interface()))
		} else if tag == "updated_at" && value.Interface() != "0" {
			//db = db.Where(fmt.Sprintf("%s > ?", tag), value.Interface())
			db = db.Where(fmt.Sprintf("updated_at like '%s%%'", value.Interface()))
		} else if !util.IsBlank(value) && tag != "updated_at" {
			db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
		}
	}

	// 查询总数
	var total int64
	var fullProjects []*gorm_model.ProjectInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	// 查询该页数据
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("updated_at desc").Limit(int(limit)).Offset(int(offset)).Find(&fullProjects).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetFullProjectList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	return fullProjects, total, nil
}

func GetProjectDraftList(ctx context.Context, enterpriseID string, pageSize, pageNum int32, condition *common_model.ProjectCondition) ([]*gorm_model.ProjectInfo, int64, error) {
	db := GetReadDB(ctx)
	// 根据企业id过滤
	db = db.Debug().Model(gorm_model.ProjectInfo{}).Where("enterprise_id = ?", enterpriseID)
	// 根据Project条件过滤
	conditionType := reflect.TypeOf(condition).Elem()
	conditionValue := reflect.ValueOf(condition).Elem()
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if (tag == "project_id" || tag == "project_name") && !util.IsBlank(value) {
			db = db.Where(fmt.Sprintf("project_id like '%%%v%%' or project_name like '%%%v%%'", value.Interface(), value.Interface()))
		} else if tag == "updated_at" && value.Interface() != "0" {
			//db = db.Where(fmt.Sprintf("%s > ?", tag), value.Interface())
			db = db.Where(fmt.Sprintf("updated_at like '%s%%'", value.Interface()))
		} else if !util.IsBlank(value) && tag != "updated_at" {
			db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
		}
	}
	// 查询总数
	var total int64
	var projectDrafts []*gorm_model.ProjectInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectDraftList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	// 查询该页数据
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("updated_at desc").Limit(int(limit)).Offset(int(offset)).Find(&projectDrafts).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectDraftList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	return projectDrafts, total, nil
}

func GetProjectTaskList(ctx context.Context, projectID string, pageSize, pageNum int64, conditions *common_model.TaskConditions) ([]*http_model.ProjectTaskInfo, int64, error) {
	db := GetReadDB(ctx)
	// 查询task表信息
	db = db.Debug().Model(gorm_model.YoungeeTaskInfo{})
	// 根据Project条件过滤
	conditionType := reflect.TypeOf(conditions).Elem()
	conditionValue := reflect.ValueOf(conditions).Elem()
	var platform_nickname string = ""

	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if !util.IsBlank(value) && tag != "platform_nickname" {
			db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
		} else if tag == "platform_nickname" {
			platform_nickname = fmt.Sprintf("%v", value.Interface())
			continue
		}
	}

	var taskInfos []gorm_model.YoungeeTaskInfo
	db = db.Model(gorm_model.YoungeeTaskInfo{})
	// 查询总数
	var totalTask int64
	if err := db.Count(&totalTask).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	db.Order("task_id").Find(&taskInfos)

	// 查询该页数据
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0
	err := db.Order("task_id").Limit(int(limit)).Offset(int(offset)).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetProjectTaskList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

	var taskDatas []*http_model.ProjectTaskInfo
	var newTaskDatas []*http_model.ProjectTaskInfo
	taskDatas = pack.TaskAccountToTaskInfo(taskInfos)

	for _, v := range taskDatas {
		if platform_nickname == "" {
			newTaskDatas = append(newTaskDatas, v)
		} else if strings.Contains(v.PlatformNickname, platform_nickname) {
			newTaskDatas = append(newTaskDatas, v)
		} else if strings.Contains(v.TaskID, platform_nickname) {
			newTaskDatas = append(newTaskDatas, v)
		} else {
			totalTask--
		}
	}
	return newTaskDatas, totalTask, nil
}

func GetProjectDetail(ctx context.Context, projectID string) (*gorm_model.ProjectInfo, error) {
	db := GetReadDB(ctx)
	var ProjectDetail *gorm_model.ProjectInfo
	//fmt.Printf("项目ID：%+v", projectID)
	err := db.Where("project_id = ?", projectID).First(&ProjectDetail).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	//fmt.Printf("项目详情：%+v", ProjectDetail)
	return ProjectDetail, nil
}

func GetProjectPhoto(ctx context.Context, ProjectID string) ([]gorm_model.ProjectPhoto, error) {
	db := GetReadDB(ctx)
	ProjectPhoto := []gorm_model.ProjectPhoto{}
	err := db.Where("project_id=?", ProjectID).Find(&ProjectPhoto).Error
	if err != nil {
		return nil, err
	}
	return ProjectPhoto, nil
}

func GetRecruitStrategys(ctx context.Context, ProjectID string) ([]gorm_model.RecruitStrategy, error) {
	db := GetReadDB(ctx)
	RecruitStrategys := []gorm_model.RecruitStrategy{}
	err := db.Where("project_id=?", ProjectID).Find(&RecruitStrategys).Error
	if err != nil {
		return nil, err
	}
	return RecruitStrategys, nil
}

func UpdateProjectStatus(ctx context.Context, projectId string, status int64) error {
	db := GetReadDB(ctx)
	t := time.Now()
	err := db.Model(gorm_model.ProjectInfo{}).
		Where("project_id = ?", projectId).Updates(gorm_model.ProjectInfo{ProjectStatus: status, PayAt: &t}).Error
	if err != nil {
		log.Println("DB UpdateProjectStatus error :", err)
		return err
	}
	return nil
}

func GetFeeDetail(ctx context.Context, enterpriseID string, EndTime string) (*http_model.FeeDetailPreview, error) {
	db := GetReadDB(ctx)
	// 根据企业id过滤
	db = db.Debug().Model(gorm_model.ProjectInfo{}).Where("enterprise_id = ? AND project_status = 10", enterpriseID)
	if EndTime != "" {
		db = db.Where("updated_at like ?", EndTime+"%")
	}
	var projectInfos []gorm_model.ProjectInfo
	db = db.Order("updated_at desc").Find(&projectInfos)
	FeeDetailPreview := http_model.FeeDetailPreview{}
	for _, projectInfo := range projectInfos {
		FeeDetailData := new(http_model.FeeDetailData)
		FeeDetailData.ProjectID = projectInfo.ProjectID
		FeeDetailData.ProjectName = projectInfo.ProjectName
		FeeDetailData.ProjectType = consts.GetProjectType(projectInfo.ProjectType)
		FeeDetailData.Payment = conv.MustString(projectInfo.PaymentAmount, "")
		FeeDetailData.UpdatedAt = conv.MustString(projectInfo.UpdatedAt)[0:19]
		FeeDetailPreview.FeeDetailData = append(FeeDetailPreview.FeeDetailData, FeeDetailData)
	}
	return &FeeDetailPreview, nil
}

func SetProjectFinish(ctx context.Context, projectId string) error {
	db := GetReadDB(ctx)
	var finishedNum int64
	var unfinishedNum int64
	db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = 2 AND task_stage < 15", projectId).Count(&unfinishedNum)
	db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? and task_status = 2 and task_stage >= 15", projectId).Count(&finishedNum)
	if unfinishedNum == 0 && finishedNum != 0 {
		// 2. 释放企业账户因项目冻结的资金
		// 1） 计算剩余资金
		db1 := GetReadDB(ctx)
		var allPayment float64
		var realPayment float64
		err := db1.Model(gorm_model.YoungeeTaskInfo{}).
			Where("project_id = ? and task_status = 2 and task_stage >= 15", projectId).Pluck("COALESCE(SUM(all_payment), 0) as allPayment", &allPayment).Error
		if err != nil {
			log.Println("DB GetAutoCaseCloseTask error in data:", err)
			return err
		}
		err = db1.Model(gorm_model.YoungeeTaskInfo{}).Select("sum(real_payment) as realPayment").
			Where("project_id = ? and task_status = 2 and task_stage >= 15", projectId).Pluck("COALESCE(SUM(real_payment), 0) as realPayment", &realPayment).Error
		if err != nil {
			log.Println("DB GetAutoCaseCloseTask error in data:", err)
			return err
		}
		fmt.Println("企业应支付金额总计：", allPayment, "实际支付总计：", realPayment)
		db2 := GetReadDB(ctx)
		var enterpriseID int64
		db2.Model(gorm_model.ProjectInfo{}).Select("enterprise_id").Where("project_id = ?", projectId).Find(&enterpriseID)
		// 	2）. 释放剩余资金
		err = db1.Model(gorm_model.Enterprise{}).Where("enterprise_id = ?", enterpriseID).Updates(
			map[string]interface{}{
				"frozen_balance":    gorm.Expr("frozen_balance - ?", allPayment),
				"balance":           gorm.Expr("balance - ?", realPayment),
				"available_balance": gorm.Expr("available_balance + ?", allPayment-realPayment)}).Error
		if err != nil {
			log.Println("DB GetAutoCaseCloseTask error in data:", err)
			return err
		}

		// 1. 更新项目状态为已结束
		t := time.Now()
		err = db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectId).Updates(gorm_model.ProjectInfo{ProjectStatus: 10, PaymentAmount: realPayment, FinishAt: &t}).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Project db] Update ProjectInfo error,err:%+v", err)
			return err
		}
	}
	return nil
}

func SetSpecialProjectFinish(ctx context.Context, projectId string) error {
	db := GetReadDB(ctx)
	var finishedNum int64
	var unfinishedNum int64
	db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? AND task_status = 2 AND task_stage < 15", projectId).Count(&unfinishedNum)
	db.Model(gorm_model.YoungeeTaskInfo{}).Where("project_id = ? and task_status = 2 and task_stage >= 15", projectId).Count(&finishedNum)
	if unfinishedNum == 0 && finishedNum != 0 {
		// 1. 更新项目状态为已结束
		t := time.Now()
		err := db.Model(gorm_model.ProjectInfo{}).Where("project_id = ?", projectId).Updates(gorm_model.ProjectInfo{ProjectStatus: 10, FinishAt: &t}).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Project db] Update ProjectInfo error,err:%+v", err)
			return err
		}
	}
	return nil
}

func GetCreatingNumber(ctx context.Context, enterpriseID string) (*int64, error) {
	db := GetReadDB(ctx)
	var creatingNumber int64
	err := db.Model(gorm_model.ProjectInfo{}).Where("enterprise_id = ? and project_status = 1", enterpriseID).Count(&creatingNumber).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Project db] Update ProjectInfo error,err:%+v", err)
		return nil, err
	}
	return &creatingNumber, nil
}
