package goods

import (
	"errors"
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/utils"
	"strconv"
	"strings"
	"time"

	"github.com/yl10/kit/guid"
)

// GetOrdersByCases 获取案场订单列表
func (m *GoodsDAO) GetOrdersByCases() error {
	return nil
}

// SaveOrders 下单
func (m *GoodsDAO) SaveOrders(order *model.TaGoodsOrders) error {
	if order.UserId == "" {
		return errors.New("没有下单人信息")
	}

	caseID := order.CaseId
	if caseID == "" {
		return errors.New("没有指定案场")
	}

	caseInfo, err := m.getCaseByID(caseID)
	if err != nil {
		return err
	}

	order.OrdersId = guid.NewGUIDString()
	order.OrgId = caseInfo.OrgId
	order.CreateDate = time.Now().Local()
	order.Status = models.STATUS_NORMAL
	order.IsPay = models.BOOL_TRUE // 默认已支付
	order.CouponAmount = "0"

	// 当前订单号的随机方式 = 时间 + 个人ID
	order.OrdersNo = "G-" + time.Now().Local().Format("20060102150405") + "-" + strings.Join(utils.GUIID2IntString(order.UserId), "")

	if _, err := m.db.Insert(order); err != nil {
		utils.LogError("保存订单主记录失败: " + err.Error())

		return errors.New("保存订单主记录失败")
	}
	return nil
}

// SaveOrdersDetail 保存订单明细
func (m *GoodsDAO) SaveOrdersDetail(list []model.TaGoodsOrdersDetail, ordersID string) error {
	for inx := range list {
		list[inx].OrdersId = ordersID
	}

	if _, err := m.db.Insert(list); err != nil {
		utils.LogError("保存订单明细失败: " + err.Error())

		return errors.New("保存订单明细失败")
	}

	return nil
}

// SaveOrdersCoupon 保存订单优惠券
func (m *GoodsDAO) SaveOrdersCoupon(coupons []model.TaGoodsOrdersCoupon, order *model.TaGoodsOrders) error {
	if order.OrdersId == "" {
		return errors.New("内部错误, 订单事务顺序出错")
	}

	var couponAmount float64 = 0

	// 补充优惠券表字段
	for inx := range coupons {
		coupons[inx].OrdersCouponId = guid.NewGUIDString()
		coupons[inx].OrdersId = order.OrdersId
		coupons[inx].OrdersNo = order.OrdersNo
		coupons[inx].OrgId = order.OrgId
		coupons[inx].Status = models.STATUS_NORMAL
		coupons[inx].CreateDate = time.Now().Local()

		userAmount, _ := strconv.ParseFloat(coupons[inx].UsedAmount, 64)
		couponAmount += userAmount
	}

	// 反向更新 订单主表
	totalAmount, _ := strconv.ParseFloat(order.Amount, 64)

	order.CouponAmount = strconv.FormatFloat(couponAmount, 'f', -1, 32)
	order.ActualAmount = strconv.FormatFloat((totalAmount - couponAmount), 'f', -1, 32)

	if _, err := m.db.Insert(&coupons); err != nil {
		return err
	}

	if _, err := m.db.
		Where("orders_id=?", order.OrdersId).
		Cols([]string{"coupon_amount", "actual_amount"}...).
		Update(order); err != nil {
		return err
	}

	return nil
}

func (m *GoodsDAO) getCaseByID(caseID string) (*model.SysCase, error) {
	cs := new(model.SysCase)
	if _, err := m.db.Where("case_id=?", caseID).Get(cs); err != nil {
		return nil, err
	}

	return cs, nil
}

// GetOrdersByCaseID 获取订单列表
func (m *GoodsDAO) GetOrdersByCaseID(caseID, userType string, makeStatus []string, orderDate []time.Time, limit []int) ([]OrdersWithGoods, int64, error) {
	var orderList []OrdersWithGoods

	query := "select * from ta_goods_orders where case_id = ? and status = ?"

	// 制作状态
	if makeStatus != nil && len(makeStatus) > 0 {
		query += ` and make_status in ('` + strings.Join(makeStatus, "','") + `')`
	}

	// 用户类型
	if userType != "" {
		query += ` and user_type = '` + userType + `'`
	}

	// 订单起始时间
	if orderDate != nil && len(orderDate) > 0 {
		query += ` and DATE_FORMAT(create_date, '%Y-%m-%d %H:%i') >= '` + orderDate[0].Format("2006-01-02 15:04") + `'`

		if len(orderDate) > 1 {
			query += ` and DATE_FORMAT(create_date, '%Y-%m-%d %H:%i') <= '` + orderDate[1].Format("2006-01-02 15:04") + `'`
		}
	}

	query += " order by create_date asc"

	var cnt int64
	if limit != nil && len(limit) > 1 {
		var err error
		cnt, err = utils.NewPageNaviEngine(m.ctx).GetPageList(&orderList, query, limit, caseID, models.STATUS_NORMAL)
		if err != nil {
			return nil, 0, err
		}
	} else {
		if err := m.db.SQL(query, caseID, models.STATUS_NORMAL).Find(&orderList); err != nil {
			return nil, 0, err
		}
	}

	for i, o := range orderList {
		var details []model.TaGoodsOrdersDetail
		if err := m.db.Where("orders_id=?", o.OrdersId).Find(&details); err != nil {
			return nil, 0, err
		}

		orderList[i].Goods = details
	}

	return orderList, cnt, nil
}
