package configs

import (
	"context"
	"encoding/json"
	"errors"
	"fusenapi/constants"
	"fusenapi/model/gmodel"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type WebSetTimeInfo struct {
	ProductDay        int64
	FactoryDeliverDay int64
	DeliverUpsDay     int64
	UpsTransDay       int64
}

type WebSetTimeInfoData struct {
	ProductDay        string `json:"product_day"`
	FactoryDeliverDay string `json:"factory_deliver_day"`
	DeliverUpsDay     string `json:"deliver_ups_day"`
	UpsTransDay       string `json:"ups_trans_day"`
}

func GetOrderTimeConfig(ctx context.Context, db *gorm.DB) (res WebSetTimeInfo, err error) {
	resData, err := gmodel.NewFsWebSetModel(db).FindValueByKey(ctx, string(constants.WEBSET_TIME_INFO))
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.ProductDay = int64(constants.ORDER_PRODUCT_DAY)
			res.FactoryDeliverDay = int64(constants.ORDER_FACTORY_DELIVER_DAY)
			res.DeliverUpsDay = int64(constants.ORDER_DELIVER_UPS_DAY)
			res.UpsTransDay = int64(constants.ORDER_UPS_TRANS_DAY)
			return res, nil
		}
		logx.Error(err)
		return res, err
	} else {
		var timeInfo WebSetTimeInfoData
		err = json.Unmarshal([]byte(*resData.Value), &timeInfo)
		if err != nil {
			logx.Error(err)
			return res, err
		}
		productDay, err := strconv.Atoi(timeInfo.ProductDay)
		if err != nil {
			logx.Error(err)
			return res, err
		}
		factoryDeliverDay, err := strconv.Atoi(timeInfo.FactoryDeliverDay)
		if err != nil {
			logx.Error(err)
			return res, err
		}
		deliverUpsDay, err := strconv.Atoi(timeInfo.DeliverUpsDay)
		if err != nil {
			logx.Error(err)
			return res, err
		}
		upsTransDay, err := strconv.Atoi(timeInfo.UpsTransDay)
		if err != nil {
			logx.Error(err)
			return res, err
		}
		res.ProductDay = int64(productDay)
		res.FactoryDeliverDay = int64(factoryDeliverDay)
		res.DeliverUpsDay = int64(deliverUpsDay)
		res.UpsTransDay = int64(upsTransDay)
	}

	return res, nil
}