package order

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

// 用户持卡表 CygxOrderUserCard 结构体对应 cygx_order_user_card 数据表
type CygxOrderUserCard struct {
	UserCardId       int       `orm:"column(user_card_id);pk";comment:"订单id"`
	OrderCode        string    `comment:"订单编号"`
	UserId           int       `comment:"用户ID"`
	Mobile           string    `comment:"手机号"`
	Email            string    `comment:"邮箱"`
	CompanyId        int       `comment:"公司ID"`
	CompanyName      string    `comment:"公司名称"`
	RealName         string    `comment:"用户实际名称"`
	SellerName       string    `comment:"所属销售"`
	CreateTime       time.Time `comment:"创建时间"`
	ModifyTime       time.Time `comment:"修改时间"`
	RegisterPlatform int       `comment:"来源"`
	CardType         string    `comment:"会员卡类型"`
	StartDate        time.Time `comment:"开始时间"`
	EndDate          time.Time `comment:"结束时间"`
	IsSuspend        int       `comment:"是否暂停"`
}

// 用户持卡日志表 CygxOrderUserCardLog 结构体对应 cygx_order_user_card_log 数据表
type CygxOrderUserCardLog struct {
	UserCardId       int       `orm:"column(user_card_log_id);pk";comment:"订单id"`
	OrderCode        string    `comment:"订单编号"`
	UserId           int       `comment:"用户ID"`
	Mobile           string    `comment:"手机号"`
	Email            string    `comment:"邮箱"`
	CompanyId        int       `comment:"公司ID"`
	CompanyName      string    `comment:"公司名称"`
	RealName         string    `comment:"用户实际名称"`
	SellerName       string    `comment:"所属销售"`
	CreateTime       time.Time `comment:"创建时间"`
	ModifyTime       time.Time `comment:"修改时间"`
	RegisterPlatform int       `comment:"来源"`
	CardType         string    `comment:"会员卡类型"`
	StartDate        time.Time `comment:"开始时间"`
	EndDate          time.Time `comment:"结束时间"`
	IsSuspend        int       `comment:"是否暂停"`
}

// 添加
func AddCygxOrderUserCard(item *CygxOrderUserCard, itemOrder *CygxOrder) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()

	itemOrderAction := new(CygxOrderAction)

	switch itemOrder.TradeType {
	case "JSAPI":
		itemOrderAction.Action = "公众号支付"
	case "NATIVE":
		itemOrderAction.Action = "扫码支付"
	case "App":
		itemOrderAction.Action = "App支付"
	case "MICROPAY":
		itemOrderAction.Action = "付款码支付"
	case "MWEB":
		itemOrderAction.Action = "H5支付"
	case "FACEPAY":
		itemOrderAction.Action = "刷脸支付"
	}
	itemOrderAction.OrderStatus = 2
	itemOrderAction.OrderStatusText = "已支付"
	itemOrderAction.OrderCode = item.OrderCode
	itemOrderAction.UserId = item.UserId
	itemOrderAction.Mobile = item.Mobile
	itemOrderAction.Email = item.Email
	itemOrderAction.CompanyId = item.CompanyId
	itemOrderAction.CompanyName = item.CompanyName
	itemOrderAction.RealName = item.RealName
	itemOrderAction.SellerName = item.SellerName
	itemOrderAction.CreateTime = time.Now()
	itemOrderAction.ModifyTime = time.Now()
	itemOrderAction.RegisterPlatform = item.RegisterPlatform

	updateParams := make(map[string]interface{})
	updateParams["PayTime"] = itemOrder.PayTime
	updateParams["PayMoney"] = itemOrder.PayMoney
	updateParams["OrderStatus"] = itemOrder.OrderStatus
	updateParams["OutTradeCode"] = itemOrder.OutTradeCode
	updateParams["ModifyTime"] = item.ModifyTime
	updateParams["StartDate"] = item.StartDate
	updateParams["EndDate"] = item.EndDate
	updateParams["PaymentType"] = 1
	updateParams["TradeType"] = itemOrder.TradeType
	ptrStructOrTableName := "cygx_order"
	whereParam := map[string]interface{}{"order_code": itemOrder.OrderCode}
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams) // 修改订单状态
	if err != nil {
		return
	}

	_, err = o.Insert(itemOrderAction) // 写入订单操作信息
	if err != nil {
		return
	}

	sql := ` DELETE FROM cygx_order_user_card  WHERE mobile=? ` // 删除原有的持卡信息
	_, err = o.Raw(sql, item.Mobile).Exec()
	if err != nil {
		return
	}

	itemLog := new(CygxOrderUserCardLog)
	itemLog.OrderCode = item.OrderCode
	itemLog.UserId = item.UserId
	itemLog.Mobile = item.Mobile
	itemLog.Email = item.Email
	itemLog.CompanyId = item.CompanyId
	itemLog.CompanyName = item.CompanyName
	itemLog.RealName = item.RealName
	itemLog.SellerName = item.SellerName
	itemLog.CreateTime = time.Now()
	itemLog.ModifyTime = time.Now()
	itemLog.RegisterPlatform = item.RegisterPlatform
	itemLog.CardType = item.CardType
	itemLog.StartDate = item.StartDate
	itemLog.EndDate = item.EndDate
	itemLog.IsSuspend = item.IsSuspend

	_, err = o.Insert(item) //写入用户持卡表
	if err != nil {
		return
	}

	_, err = o.Insert(itemLog) // 写入用户持卡日志表
	if err != nil {
		return
	}
	return
}

// 根据订单编号获取用户持卡详情
func GetCygxOrderUserCardDetailByOrderCode(orderCode string) (item *CygxOrderUserCard, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_order_user_card WHERE order_code = ? `
	err = o.Raw(sql, orderCode).QueryRow(&item)
	return
}

// 根据手机号获取用户持卡详情
func GetCygxOrderUserCardDetailByMobile(mobile string) (item *CygxOrderUserCard, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM cygx_order_user_card WHERE mobile = ? `
	err = o.Raw(sql, mobile).QueryRow(&item)
	return
}

// 获取数量
func GetCygxOrderUserCardCount(condition string, pars []interface{}) (count int, err error) {
	o := orm.NewOrm()
	sqlCount := ` SELECT COUNT(1) AS  count  FROM cygx_order_user_card WHERE   1= 1  ` + condition
	err = o.Raw(sqlCount, pars).QueryRow(&count)
	return
}

// 删除
func RemoveCygxOrderUserCard(item *CygxOrderUserCard, itemOrder *CygxOrder) (err error) {
	o, err := orm.NewOrm().Begin()
	if err != nil {
		return
	}
	defer func() {
		fmt.Println(err)
		if err == nil {
			o.Commit()
		} else {
			o.Rollback()
		}
	}()

	itemOrderAction := new(CygxOrderAction)

	itemOrderAction.Action = "退款成功"
	itemOrderAction.OrderStatus = 3
	itemOrderAction.OrderStatusText = "已退款"
	itemOrderAction.OrderCode = item.OrderCode
	itemOrderAction.UserId = item.UserId
	itemOrderAction.Mobile = item.Mobile
	itemOrderAction.Email = item.Email
	itemOrderAction.CompanyId = item.CompanyId
	itemOrderAction.CompanyName = item.CompanyName
	itemOrderAction.RealName = item.RealName
	itemOrderAction.SellerName = item.SellerName
	itemOrderAction.CreateTime = time.Now()
	itemOrderAction.ModifyTime = time.Now()
	itemOrderAction.RegisterPlatform = item.RegisterPlatform

	updateParams := make(map[string]interface{})
	updateParams["OrderStatus"] = itemOrder.OrderStatus
	updateParams["ModifyTime"] = item.ModifyTime
	ptrStructOrTableName := "cygx_order"
	whereParam := map[string]interface{}{"order_code": itemOrder.OrderCode}
	qs := o.QueryTable(ptrStructOrTableName)
	for expr, exprV := range whereParam {
		qs = qs.Filter(expr, exprV)
	}
	_, err = qs.Update(updateParams) // 修改订单状态
	if err != nil {
		return
	}

	_, err = o.Insert(itemOrderAction) // 写入订单操作信息
	if err != nil {
		return
	}

	//sql := ` DELETE FROM cygx_order_user_card  WHERE mobile=? ` // 删除原有的持卡信息 (退款之后不删除相关权益权限)
	//_, err = o.Raw(sql, item.Mobile).Exec()
	//if err != nil {
	//	return
	//}

	itemLog := new(CygxOrderUserCardLog)
	itemLog.OrderCode = item.OrderCode
	itemLog.UserId = item.UserId
	itemLog.Mobile = item.Mobile
	itemLog.Email = item.Email
	itemLog.CompanyId = item.CompanyId
	itemLog.CompanyName = item.CompanyName
	itemLog.RealName = item.RealName
	itemLog.SellerName = item.SellerName
	itemLog.CreateTime = time.Now()
	itemLog.ModifyTime = time.Now()
	itemLog.RegisterPlatform = item.RegisterPlatform
	itemLog.CardType = item.CardType
	itemLog.StartDate = item.StartDate
	itemLog.EndDate = item.EndDate
	itemLog.IsSuspend = 1

	_, err = o.Insert(itemLog) // 写入用户持卡日志表
	if err != nil {
		return
	}
	return
}
