package ordermanage

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/logger"
	"go-admin/tools/app"
	"net/http"
)

// OrderList 查询租赁订单列表
// @Summary 查询租赁订单列表
// @Tags 租卡系统-订单管理
// @Produce json
// @Accept json
// @Param request body models.OrderListReq true "查询租赁订单列表"
// @Success 200 {object} app.Response "{"code": 200, "data": { "total": 4, "pageIndex":0, "total_page":10, "list":{} }}"
// @Router /api/v1/order/list [post]
func OrderList(c *gin.Context) {
	req := &models.OrderListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	reqJson, _ := json.Marshal(req)
	fmt.Println("reqJson:", string(reqJson))

	//data, _ := c.Get(jwtauth.JwtPayloadKey)
	//mapClaims := data.(jwtauth.MapClaims)
	//sysUid := float64(0)
	//if v, ok := mapClaims["identity"]; ok {
	//	sysUid = v.(float64)
	//}
	//fmt.Println("sysUid:", sysUid)
	//var suser models.SysUser
	//err := orm.Eloquent.Table("sys_user").Where("user_id", fmt.Sprintf("%.0f", sysUid)).Find(&suser).Error
	//if err != nil {
	//
	//}

	list, count, _, err := req.List(0, c)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"total":     count,
		"list":      list,
		"pageIndex": req.Page,
		"pageSize":  req.PageSize,
	}
	app.OK(c, ret, "")
}

func OrderInfo(c *gin.Context) {
	req := struct {
		OrderId uint32 `json:"order_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	order := &models.Order{}
	order.ID = req.OrderId
	ret, err := order.Info()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	app.OK(c, ret, "")
}

func DeliverGoods(c *gin.Context) {
	m := models.Order{}
	if c.ShouldBindJSON(&m) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	if m.DeliverShopperCode != "" && !models.CheckCode(m.DeliverShopperCode) {
		app.Error(c, http.StatusBadRequest, errors.New("deliver_shopper_code err"), "店员码错误")
		return
	}

	// 更新卡的状态
	if len(m.GameCardSerialNumbers) == 0 {
		logger.Errorf("err:")
		msg := "发货卡编码不能为空"
		app.Error(c, http.StatusInternalServerError, errors.New("GameCardSerialNumber null"), msg)
		return
	}
	err, msg := m.Deliver()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		if msg == "" {
			msg = "更新失败"
		}
		app.Error(c, http.StatusInternalServerError, err, msg)
		return
	}
	app.OK(c, nil, "")
}

func RevertGoods(c *gin.Context) {
	order := &models.Order{}
	//req := struct {
	//	SerialNumber string    `json:"serial_number" ` // 编号
	//}{}
	if c.ShouldBindJSON(order) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	if order.PhoneExt != "" && len(order.PhoneExt) != 4 {
		app.Error(c, http.StatusBadRequest, errors.New("手机尾号填写有误（4位数字）"),
			"手机尾号填写有误（4位数字）")
		return
	}

	if order.OverdueFlag == 1 { // 检查用户会员是否过期
		var orderInfo models.Order
		err := orm.Eloquent.Table("order").Where("id", order.ID).Find(&orderInfo).Error
		if err != nil {
			app.Error(c, http.StatusBadRequest, err, err.Error())
			return
		}

		userInfo, err := models.GetUserInfoByUid(uint32(orderInfo.Uid))
		if err != nil {
			app.Error(c, http.StatusBadRequest, err, err.Error())
			return
		}

		if userInfo.MemberLevel == 2 || userInfo.MemberLevel == 3 || userInfo.MemberLevel == 4 ||
			userInfo.MemberLevel == 5 {
			app.Error(c, http.StatusBadRequest, errors.New("该用户会员还未过期，不能选择超期处理"),
				"该用户会员还未过期，不能选择超期处理")
			return
		}
	}

	if order.RevertShopperCode != "" && !models.CheckCode(order.RevertShopperCode) {
		app.Error(c, http.StatusBadRequest, errors.New("order revert shopper code err"), "店员码错误")
		return
	}

	err := order.Revert()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}
	app.OK(c, nil, "")
}

func ExpressCompanyList(c *gin.Context) {
	company := &models.ExpressCompany{}
	list, err := company.List()
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	app.OK(c, list, "")
	return
}

func OrderDel(c *gin.Context) {
	req := struct {
		OrderId uint32 `json:"order_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	order := &models.Order{}
	order.ID = req.OrderId
	err := order.Del()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	app.OK(c, nil, "")
}

func OrderRefund(c *gin.Context) {
	req := struct {
		OrderId uint32 `json:"order_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	order := &models.Order{}
	order.ID = req.OrderId
	err := order.Refund()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	app.OK(c, nil, "")
}

func ExpressNoList(c *gin.Context) {
	req := struct {
		ExpressNo string `json:"express_no"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	info := models.ExpressNoInfo{
		Store: new(models.Store),
	}
	// 还卡 共享卡 问题卡
	var orderCard models.OrderCard
	err := orm.Eloquent.Table("order_card").Where("revert_express_no=?", req.ExpressNo).Find(&orderCard).Error
	if orderCard.RevertExpressNo == req.ExpressNo {
		info.StoreId = uint32(orderCard.StoreId)
		info.ExpressNo = orderCard.RevertExpressNo
		info.ExpressCompanyNo = orderCard.RevertExpressCompanyNo
		info.ExpressCompany = orderCard.RevertExpressCompany
		info.OperationType = models.OperationTypeRevertRentCard
		info.CorrelationId = orderCard.OrderId
		info.SetStore()
		app.OK(c, info, "")
		return
	}
	var shareCardBill models.UserShareCardBill
	err = orm.Eloquent.Table("user_share_card_bill").Where("express_no=?", req.ExpressNo).Find(&shareCardBill).Error
	if shareCardBill.ExpressNo == req.ExpressNo {
		info.StoreId = shareCardBill.StoreId
		info.ExpressNo = shareCardBill.ExpressNo
		info.ExpressCompanyNo = shareCardBill.ExpressCompanyNo
		info.ExpressCompany = shareCardBill.ExpressCompany
		info.OperationType = models.OperationTypeUserShareCard
		info.CorrelationId = shareCardBill.ID
		info.SetStore()
		app.OK(c, info, "")
		return
	}
	var cardIssue models.CardIssueFeedback
	err = orm.Eloquent.Table("card_issue_feedback").Where("express_no=?", req.ExpressNo).Find(&cardIssue).Error
	if cardIssue.ExpressNo == req.ExpressNo {
		info.StoreId = cardIssue.StoreId
		info.ExpressNo = cardIssue.ExpressNo
		info.ExpressCompanyNo = cardIssue.ExpressCompanyNo
		info.ExpressCompany = cardIssue.ExpressCompany
		info.OperationType = models.OperationTypeIssueCard
		info.CorrelationId = cardIssue.ID
		info.SetStore()
		app.OK(c, info, "")
		return
	}
	//if info.OperationType == "" {
	//
	//}
	logger.Errorf("express no err:")
	app.Error(c, http.StatusInternalServerError, err, "查询失败")
	return
	//app.OK(c, nil, "")
}

// FundRecordList 查询财务统计列表
// @Summary 查询财务统计列表
// @Tags 财务管理
// @Produce json
// @Accept json
// @Param request body models.FundRecordListReq true "查询财务统计列表模型"
// @Success 200 {object} models.FundRecordListResp
// @Router /api/v1/order/fund_record/list [post]
func FundRecordList(c *gin.Context) {
	req := &models.FundRecordListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, exportUrl, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := models.FundRecordListResp{
		Total:     count,
		List:      list,
		PageIndex: req.Page,
		PageSize:  req.PageSize,
		ExportUrl: exportUrl,
	}
	app.OK(c, ret, "")
}

// OrderListExport 导出订单列表
// @Summary 导出订单列表
// @Tags 订单管理
// @Produce json
// @Accept json
// @Param request body models.OrderListReq true "导出订单列表模型"
// @Success 200 {object} app.Response "{"code": 200, "data": { "export_url": "" }}"
// @Router /api/v1/order/list_export [post]
func OrderListExport(c *gin.Context) {
	req := &models.OrderListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	reqJson, _ := json.Marshal(req)
	fmt.Println("reqJson:", string(reqJson))

	_, _, filePath, err := req.List(1, c)
	if err != nil {
		logger.Errorf("OrderListExport err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "导出失败")
		return
	}

	ret := map[string]interface{}{
		"export_url": filePath,
	}

	app.OK(c, ret, "")
}
