package db

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/issue9/conv"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"reflect"
	"strings"
	"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"
)

func CreateSelection(ctx context.Context, selectionInfo gorm_model.YounggeeSelectionInfo) error {
	db := GetWriteDB(ctx)
	err := db.Create(&selectionInfo).Error
	if err != nil {
		return err
	}
	return nil
}

func UpdateSelection(ctx context.Context, selectionInfo gorm_model.YounggeeSelectionInfo) error {
	db := GetWriteDB(ctx)
	whereCondition := gorm_model.YounggeeSelectionInfo{SelectionID: selectionInfo.SelectionID}
	err := db.Model(&gorm_model.YounggeeSelectionInfo{}).Where(whereCondition).Updates(selectionInfo).Error
	if err != nil {
		return err
	}
	return nil
}

func DeleteSelection(ctx context.Context, SelectionId string) error {
	db := GetReadDB(ctx)
	err := db.Where("selection_id = ?", SelectionId).Delete(&gorm_model.YounggeeSelectionInfo{}).Error
	if err != nil {
		return err
	}
	return nil
}

func GetSelectionById(ctx context.Context, selectionId string) (*gorm_model.YounggeeSelectionInfo, error) {
	db := GetWriteDB(ctx)
	selectionInfo := gorm_model.YounggeeSelectionInfo{}
	whereCondition := gorm_model.YounggeeSelectionInfo{SelectionID: selectionId}
	result := db.Where(&whereCondition).First(&selectionInfo)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, result.Error
		}
	}
	return &selectionInfo, nil
}

func GetSelectionByEnterpiseIdAndProductId(ctx context.Context, enterpriseId string, productId int) (*gorm_model.YounggeeSelectionInfo, error) {
	db := GetWriteDB(ctx)
	selectionInfo := gorm_model.YounggeeSelectionInfo{}
	whereCondition := gorm_model.YounggeeSelectionInfo{EnterpriseID: enterpriseId, ProductID: productId}
	result := db.Where(&whereCondition).First(&selectionInfo)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, result.Error
		}
	}
	return &selectionInfo, nil
}

func GetSelectionList(ctx context.Context, enterpriseID string, pageSize, pageNum int64, conditions *common_model.SelectionConditions) ([]*gorm_model.YounggeeSelectionInfo, int64, error) {
	db := GetReadDB(ctx)
	db = db.Debug().Model(gorm_model.YounggeeSelectionInfo{}).Where("enterprise_id = ?", enterpriseID)

	conditionType := reflect.TypeOf(conditions).Elem()
	conditionValue := reflect.ValueOf(conditions).Elem()
	fmt.Printf("状态内容：%v %v", conditionType, conditionValue)
	selectionStatus := ""
	searchValue := ""
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		fmt.Printf("Tag：%v %v", tag, field.Name)
		value := conditionValue.FieldByName(field.Name)
		if tag == "selection_status" {
			selectionStatus = fmt.Sprintf("%v", conv.MustInt(value.Interface()))
			db = db.Where("selection_status = ?", selectionStatus)
		} else if tag == "search_value" {
			searchValue = fmt.Sprintf("%v", value.Interface())
		} else if tag == "submit_at" && value.Interface() != "" {
			db = db.Where(fmt.Sprintf("submit_at like '%s%%'", value.Interface()))
		} else if tag == "task_ddl" && value.Interface() != "" {
			db = db.Where(fmt.Sprintf("task_ddl like '%s%%'", value.Interface()))
		} else if !util.IsBlank(value) && tag != "task_ddl" && tag != "submit_at" && tag != "search_value" {
			db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
		}
	}
	// 查询总数
	var total int64
	var selectionInfos []*gorm_model.YounggeeSelectionInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}
	// 查询该页数据
	limit := pageSize
	offset := pageSize * pageNum // assert pageNum start with 0\
	fmt.Printf("选品状态：%v", selectionStatus)
	if selectionStatus == "1" {
		err := db.Order("updated_at desc").Limit(int(limit)).Offset(int(offset)).Find(&selectionInfos).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
			return nil, 0, err
		}
	} else {
		err := db.Order("task_ddl desc").Limit(int(limit)).Offset(int(offset)).Find(&selectionInfos).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
			return nil, 0, err
		}
	}
	var newSelectionInfos []*gorm_model.YounggeeSelectionInfo
	for _, v := range selectionInfos {
		fmt.Printf("查询选品列表 %+v\n", v)
		if searchValue == "" {
			newSelectionInfos = append(newSelectionInfos, v)
		} else if strings.Contains(v.SelectionID, searchValue) {
			newSelectionInfos = append(newSelectionInfos, v)
		} else if strings.Contains(v.SelectionName, searchValue) {
			newSelectionInfos = append(newSelectionInfos, v)
		} else {
			total--
		}
	}
	return newSelectionInfos, total, nil
}

func GetSelectionBriefInfo(ctx context.Context, selectionId string) ([]*gorm_model.YounggeeSecBrief, error) {
	db := GetReadDB(ctx)
	var selectionBriefInfos []*gorm_model.YounggeeSecBrief
	err := db.Model(gorm_model.YounggeeSecBrief{}).Where("selection_id = ?", selectionId).Find(&selectionBriefInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSelectionBriefInfo] error query mysql, err:%+v", err)
		return nil, err
	}
	return selectionBriefInfos, nil
}

func GetSelectionExampleInfo(ctx context.Context, selectionId string) ([]*gorm_model.YounggeeSecExample, error) {
	db := GetReadDB(ctx)
	var selectionExampleInfos []*gorm_model.YounggeeSecExample
	err := db.Model(gorm_model.YounggeeSecExample{}).Where("selection_id = ?", selectionId).Find(&selectionExampleInfos).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[GetSelectionExampleInfo] error query, err:%+v", err)
		return nil, err
	}
	return selectionExampleInfos, nil
}

func PaySelection(ctx context.Context, enterpriseId string, payMoney float64, selectionId string) error {
	db := GetWriteDB(ctx)
	err := db.Transaction(func(tx *gorm.DB) error {
		// 1. 冻结账户余额
		whereCondition := gorm_model.Enterprise{
			EnterpriseID: enterpriseId,
		}
		updateData := map[string]interface{}{
			"frozen_balance":    gorm.Expr("frozen_balance + ?", payMoney),
			"available_balance": gorm.Expr("available_balance - ?", payMoney)}
		if err := tx.Model(gorm_model.Enterprise{}).Where(whereCondition).Updates(updateData).Error; err != nil {
			return err
		}

		// 2. 更新选品项目状态
		whereCondition1 := gorm_model.YounggeeSelectionInfo{SelectionID: selectionId, SelectionStatus: 4}
		updateData1 := gorm_model.YounggeeSelectionInfo{SelectionStatus: 6}
		if err := tx.Model(gorm_model.YounggeeSelectionInfo{}).Where(whereCondition1).Updates(updateData1).Error; err != nil {
			return err
		}

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

func CreateSecBrief(ctx context.Context, briefInfo gorm_model.YounggeeSecBrief) error {
	db := GetWriteDB(ctx)
	err := db.Create(&briefInfo).Error
	if err != nil {
		return err
	}
	return nil
}

func DeleteSecBriefBySelectionId(ctx context.Context, selectionId string) error {
	db := GetWriteDB(ctx)
	deleteCondition := gorm_model.YounggeeSecBrief{
		SelectionID: selectionId,
	}
	err := db.Where(deleteCondition).Delete(gorm_model.YounggeeSecBrief{}).Error
	if err != nil {
		return err
	}
	return nil
}

func CreateSecExample(ctx context.Context, ExampleInfo gorm_model.YounggeeSecExample) error {
	db := GetWriteDB(ctx)
	err := db.Create(&ExampleInfo).Error
	if err != nil {
		return err
	}
	return nil
}

func DeleteSecExampleBySelectionId(ctx context.Context, selectionId string) error {
	db := GetWriteDB(ctx)
	deleteCondition := gorm_model.YounggeeSecExample{
		SelectionID: selectionId,
	}
	err := db.Where(deleteCondition).Delete(gorm_model.YounggeeSecExample{}).Error
	if err != nil {
		return err
	}
	return nil
}

// 更新选品结算金额
func UpdateSelectionSettleMoney(ctx context.Context, selectionID string, payMoney float64) (bool, error) {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.YounggeeSelectionInfo{}).Where("selection_id", selectionID).
		Updates(map[string]interface{}{"settlement_amount": gorm.Expr("settlement_amount + ?", payMoney)}).Error
	if err != nil {
		return false, err
	}

	return true, nil
}

func GetSelectionInfoList(ctx context.Context, pageNum, pageSize int64, conditions http_model.SelectionSquareCondition) ([]*http_model.SelectionBriefInfo, int64, error) {
	db := GetReadDB(ctx)
	db = db.Debug().Model(gorm_model.YounggeeSelectionInfo{}).Where("selection_status>2")
	fmt.Println("conditions: ", conditions)

	conditionType := reflect.TypeOf(&conditions).Elem()
	conditionValue := reflect.ValueOf(&conditions).Elem()
	for i := 0; i < conditionType.NumField(); i++ {
		field := conditionType.Field(i)
		tag := field.Tag.Get("condition")
		value := conditionValue.FieldByName(field.Name)
		if tag == "product_type" {
			continue
		} else {
			if value.Interface().(int16) != 0 {
				db = db.Where(fmt.Sprintf("%s = ?", tag), value.Interface())
			}
		}
	}
	// 查询总数
	var total int64
	var selectionInfos []*gorm_model.YounggeeSelectionInfo
	if err := db.Count(&total).Error; err != nil {
		logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
		return nil, 0, err
	}

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

		tempList = selectionInfos
	} else {
		err := db.Order("task_ddl desc").Find(&selectionInfos).Error
		if err != nil {
			logrus.WithContext(ctx).Errorf("[GetSelectionList] error query mysql total, err:%+v", err)
			return nil, 0, err
		}
		total = 0
		var num int64 = 0
		//fmt.Println("offset: ", offset)
		for _, v := range selectionInfos {
			var p gorm_model.YounggeeProduct
			_ = json.Unmarshal([]byte(v.ProductSnap), &p)
			if p.ProductType == int64(conditions.ProductType) {
				total++
				//fmt.Println("total++", total)
				if total > offset && num < pageSize {
					//fmt.Println("num++", num)
					num++
					tempList = append(tempList, v)
				}
			}
		}
	}

	newSelectionInfos := pack.GormSelectionListToSelectionBriefInfoList(tempList)
	return newSelectionInfos, total, nil
}
