package goods

import (
	"encoding/json"
	"errors"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/utils"
	"time"
)

// GetOrderList 获取商品订单
// 管理端 - 统计查询
func (c *GoodsController) GetOrderList() {
	caseID := c.GetString("caseid")
	if caseID == "" {
		c.ResponseError(errors.New("请选择有效案场"))
	}

	userType := c.GetString("usertype")
	status := c.GetString("status")
	orderStart := c.GetString("startdate")
	orderEnd := c.GetString("enddate")

	page, _ := c.GetInt("page")
	pagesize, _ := c.GetInt("pagesize")

	var orderDate []time.Time

	if orderStart != "" {
		t, err := time.Parse("20060102150405", orderStart)
		if err != nil {
			utils.LogError("接收时间参数失败: " + err.Error())
			c.ResponseError(errors.New("接收时间参数失败"))
		}

		orderDate = []time.Time{t}
	}

	if orderEnd != "" {
		t, err := time.Parse("20060102150405", orderEnd)
		if err != nil {
			utils.LogError("接收时间参数失败: " + err.Error())
			c.ResponseError(errors.New("接收时间参数失败"))
		}

		if orderDate == nil {
			orderDate = make([]time.Time, 0)
		}
		orderDate = append(orderDate, t)
	}

	list, total, err := c.serv.GetOrderList(caseID, userType, status, orderDate, page, pagesize)
	if err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON(map[string]interface{}{
		"list":     list,
		"pagesize": pagesize,
		"pagenum":  total,
		"page":     page,
	})
}

// GetOnlineOrder 获取在线订单
// 管理端 - 有 websocket 操作
func (c *GoodsController) GetOnlineOrder() {
	caseID := c.GetString("caseid")
	if caseID == "" {
		c.ResponseError(errors.New("请选择有效案场"))
	}

	list, err := c.serv.GetOnLineOrders(caseID)
	if err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON(map[string]interface{}{
		"list": list,
	})
}

// PostOrder 下单
// 微信端
func (c *GoodsController) PostOrder() {
	// 订单主信息
	info := c.GetString("info")
	if info == "" {
		c.ResponseError(errors.New("无有效订单信息"))
	}

	// 订单详情
	detail := c.GetString("detail")
	if detail == "" {
		c.ResponseError(errors.New("无有效订单详情信息"))
	}

	// 订单优惠券
	coupon := c.GetString("coupon")

	//
	var orderInfo model.TaGoodsOrders
	var orderDetail []model.TaGoodsOrdersDetail
	var orderCoupon []model.TaGoodsOrdersCoupon

	if err := json.Unmarshal([]byte(info), &orderInfo); err != nil {
		utils.LogError("下单转换JSON失败: " + err.Error())
		c.ResponseError(errors.New("下单数据格式不正确"))
	}

	if err := json.Unmarshal([]byte(detail), &orderDetail); err != nil {
		utils.LogError("下单详情转换JSON失败: " + err.Error())
		c.ResponseError(errors.New("详情数据格式不正确"))
	}

	if err := json.Unmarshal([]byte(coupon), &orderCoupon); err != nil {
		utils.LogError("下单优惠转换JSON失败: " + err.Error())
		c.ResponseError(errors.New("优惠数据格式不正确"))
	}

	if err := c.serv.Orders(&orderInfo, orderDetail, orderCoupon); err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON("ok")
}
