package cygx

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"strconv"
	"time"
)

// 产品内测
type OrderController struct {
	controllers.BaseAuthController
}

// @Title 列表
// @Description 列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Param   AdminId   query   string  false       "销售ID "
// @Param   ShareId   query   string  false       "推荐人ID "
// @Param   PaymentType   query   string  false       "支付渠道  取值范围：1微信小程序，2微信扫码支付，3微信H5支付。 "
// @Param   OrderType   query   int  false       "订单类型 1：畅读卡订单，2：单场付费订单"
// @Param   OrderStatus   query   int  false       "订单状态,0:已取消、1:待支付、2:已支付、3:退款成功、4：退款处理中、5：退款异常、6：退款关闭"
// @Param   PaymentProject   query   string  false       "付款项目"
// @Param   UserCardType   query   string  false       "会员卡类型 ，日卡、月卡"
// @Param   OrderCode   query   string  false       "订单编号"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /order/list [get]
func (this *OrderController) OrderList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	resp := new(cygx.UserOrderListResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	orderType, _ := this.GetInt("OrderType", 1)
	orderStatus, _ := this.GetInt("OrderStatus", -1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	adminId := this.GetString("AdminId")
	shareId := this.GetString("ShareId")
	paymentType, _ := this.GetInt("PaymentType")
	orderCode := this.GetString("OrderCode")
	keyWord := this.GetString("KeyWord")
	paymentProject := this.GetString("PaymentProject")
	userCardType := this.GetString("UserCardType")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	if orderType > 0 { //订单类型 1：畅读卡订单，2：单场付费订单
		condition += `  AND order_type =   ? `
		pars = append(pars, orderType)
	}

	if startDate != "" && endDate != "" { //时间范围
		condition += ` 	AND create_time  BETWEEN ?   AND  ? `
		pars = append(pars, startDate+" 00:00:01", endDate+" 23:59:59")
	}

	if adminId != "" { //所属销售筛选
		condition += ` 	AND seller_id IN (` + adminId + `) `
	}

	if shareId != "" { //推荐人ID
		condition += ` 	AND share_id IN (` + shareId + `) `
	}

	if paymentType > 0 { // 支付渠道
		var tradeType string
		switch paymentType {
		case 1:
			tradeType = "JSAPI"
		case 2:
			tradeType = "NATIVE"
		case 3:
			tradeType = "MWEB"
		}
		condition += ` 	AND trade_type  = ?  `
		pars = append(pars, tradeType)
	}

	if orderStatus > -1 { //订单状态
		condition += ` 	AND order_status  = ?  `
		pars = append(pars, orderStatus)
	}

	if orderCode != "" { //订单编号
		orderCode = "%" + orderCode + "%"
		condition += ` 	AND order_code LIKE ? `
		pars = append(pars, orderCode)
	}

	if paymentProject != "" { //付款项目
		condition += ` 	AND goods_name =  ? `
		pars = append(pars, paymentProject)
	}

	if userCardType != "" { //日卡月卡， 前端不好区分这里用了两个字段
		condition += ` 	AND goods_name =  ? `
		pars = append(pars, userCardType)
	}

	if keyWord != "" { //用户姓名，手机号
		keyWord = "%" + keyWord + "%"
		condition += ` 	AND (mobile LIKE ?  OR  real_name LIKE ? ) `
		pars = append(pars, keyWord, keyWord)
	}

	total, err := cygx.GetCygxOrderCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY order_id  DESC "
	list, err := cygx.GetCygxOrderList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var mobiles []string
	for _, v := range list {
		mobiles = append(mobiles, v.Mobile)
	}
	inviteNameMap := cygxService.GetCygxUserBusinessCardMap(mobiles) // 根据手机号获取邀请人

	for _, v := range list {
		item := new(cygx.OrderListResp)
		item.OrderCode = v.OrderCode
		item.OrderMoney = v.OrderMoney
		item.SourceId = v.SourceId
		item.Source = v.Source
		item.SourceTitle = v.SourceTitle
		switch v.Source {
		case utils.CYGX_OBJ_ARTICLE: //文章详情
			item.HttpUrl = utils.CYGX_MFYX_URL + "/material/info/" + strconv.Itoa(v.SourceId)
		case utils.CYGX_OBJ_ACTIVITY: //活动详情
			item.HttpUrl = utils.CYGX_MFYX_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case utils.CYGX_OBJ_ACTIVITYVIDEO: //活动视频
			item.HttpUrl = utils.CYGX_MFYX_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case utils.CYGX_OBJ_ACTIVITYVOICE: //活动音频
			item.HttpUrl = utils.CYGX_MFYX_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case utils.CYGX_OBJ_YANXUANSPECIAL: //专栏详情
			item.HttpUrl = utils.CYGX_MFYX_URL + "/column/detail/" + strconv.Itoa(v.SourceId)
		}
		item.OrderStatus = v.OrderStatus

		switch item.OrderStatus {
		case 0:
			item.OrderStatusText = "已取消"
		case 1:
			item.OrderStatusText = "待支付"
		case 2:
			item.OrderStatusText = "已支付"
		case 3:
			item.OrderStatusText = "退款成功"
		case 4:
			item.OrderStatusText = "退款处理中"
		case 5:
			item.OrderStatusText = "退款异常"
		case 6:
			item.OrderStatusText = "退款关闭"
		}

		//TradeType        string    `comment:"交易类型，枚举值：JSAPI：公众号支付 、 NATIVE：扫码支付 、 App：App支付 、 MICROPAY：付款码支付 、 MWEB：H5支付 、 FACEPAY：刷脸支付"`
		switch v.TradeType {
		case "JSAPI":
			item.PaymentTypeText = "小程序"
		case "NATIVE":
			item.PaymentTypeText = "PC"
		case "MWEB":
			item.PaymentTypeText = "H5"
		}

		item.UserId = v.UserId
		item.RealName = v.RealName
		item.Mobile = v.Mobile
		item.Email = v.Email
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.SellerName = v.SellerName
		if v.ShareName != "" {
			item.InviteName = v.ShareName
		} else {
			item.InviteName = inviteNameMap[v.Mobile]
		}
		item.PaymentProject = v.GoodsName
		if v.OrderStatus != 0 && v.OrderStatus != 1 {
			item.PayTime = v.PayTime.Format(utils.FormatDateTime)
		}
		if orderType == 1 && v.OrderStatus != 0 && v.OrderStatus != 1 {
			if v.GoodsId == 1 {
				item.StartDate = v.StartDate.Format(utils.FormatDateTime)
				item.EndDate = v.EndDate.Format(utils.FormatDateTime)
			} else {
				item.StartDate = v.StartDate.Format(utils.FormatDate)
				item.EndDate = v.EndDate.Format(utils.FormatDate)
			}
		}
		item.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		resp.List = append(resp.List, item)
	}
	if len(resp.List) == 0 {
		resp.List = make([]*cygx.OrderListResp, 0)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 退款
// @Description 退款接口
// @Param	request	body cygx.UserRemarAddReq true "type json string"
// @Success 200 操作成功
// @router /order/refund [post]
func (this *UserController) OrderRefund() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.CygxOrderRefundReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	orderCode := req.OrderCode
	remark := req.Remark

	if remark == "" {
		br.Msg = "请填写退款原因"
		return
	}
	orderDetail, err := cygx.GetCygxOrderDetailByOrderCode(orderCode)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err:" + err.Error()
		return
	}
	if orderDetail.OrderStatus != 2 {
		br.Msg = "订单状态异常！"
		br.ErrMsg = "订单状态异常，orderCode:" + orderCode
		return
	}
	//订单状态,0:已取消、1:待支付、2:已支付、3:退款成功、4：退款处理中、5：退款异常、6：退款关闭
	statusCode, err := cygxService.RefundsApiService(orderDetail)
	var orderStatus int
	if statusCode == 200 && err == nil {
		orderStatus = 4
	} else {
		orderStatus = 5
	}
	item := new(cygx.CygxOrderRefund)
	item.OrderCode = orderCode
	item.RefundMoney = orderDetail.OrderMoney
	item.RefundWay = 1
	item.Remark = remark
	item.CreateTime = time.Now()
	item.RefundTime = time.Now()
	item.AdminId = sysUser.AdminId
	item.AdminName = sysUser.RealName
	err = cygx.AddCygxOrderRefund(item, orderStatus)
	if err != nil {
		br.Msg = "新增失败."
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "已提交退款，请到退款记录页面查看"
}

// @Title 退款记录列表
// @Description 退款记录列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Param   AdminId   query   string  false       "销售ID "
// @Param   ShareId   query   string  false       "推荐人ID "
// @Param   PaymentType   query   string  false       "支付渠道  取值范围：1微信小程序，2微信扫码支付，3微信H5支付。 "
// @Param   OrderType   query   int  false       "订单类型 1：畅读卡订单，2：单场付费订单"
// @Param   OrderStatus   query   int  false       "订单状态,0:已取消、1:待支付、2:已支付、3:退款成功、4：退款处理中、5：退款异常、6：退款关闭"
// @Param   PaymentProject   query   string  false       "付款项目"
// @Param   UserCardType   query   string  false       "会员卡类型 ，日卡、月卡"
// @Param   OrderCode   query   string  false       "订单编号"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /order/refund/list [get]
func (this *OrderController) OrderRefundList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	resp := new(cygx.UserOrderListResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	orderType, _ := this.GetInt("OrderType", 1)
	orderStatus, _ := this.GetInt("OrderStatus", -1)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	adminId := this.GetString("AdminId")
	shareId := this.GetString("ShareId")
	paymentType, _ := this.GetInt("PaymentType")
	orderCode := this.GetString("OrderCode")
	keyWord := this.GetString("KeyWord")
	paymentProject := this.GetString("PaymentProject")
	userCardType := this.GetString("UserCardType")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}
	condition += `  AND order_status  IN  (3,4,5,6) `
	if orderType > 0 { //订单类型 1：畅读卡订单，2：单场付费订单
		condition += `  AND order_type =   ? `
		pars = append(pars, orderType)
	}

	if startDate != "" && endDate != "" { //时间范围
		condition += ` 	AND create_time  BETWEEN ?   AND  ? `
		pars = append(pars, startDate+" 00:00:01", endDate+" 23:59:59")
	}

	if adminId != "" { //所属销售筛选
		condition += ` 	AND seller_id IN (` + adminId + `) `
	}

	if shareId != "" { //推荐人ID
		condition += ` 	AND share_id IN (` + shareId + `) `
	}

	if paymentType > 0 { // 支付渠道
		var tradeType string
		switch paymentType {
		case 1:
			tradeType = "JSAPI"
		case 2:
			tradeType = "NATIVE"
		case 3:
			tradeType = "MWEB"
		}
		condition += ` 	AND trade_type  = ?  `
		pars = append(pars, tradeType)
	}

	if orderStatus > -1 { //订单状态
		condition += ` 	AND order_status  = ?  `
		pars = append(pars, orderStatus)
	}

	if orderCode != "" { //订单编号
		orderCode = "%" + orderCode + "%"
		condition += ` 	AND order_code LIKE ? `
		pars = append(pars, orderCode)
	}

	if paymentProject != "" { //付款项目
		condition += ` 	AND goods_name =  ? `
		pars = append(pars, paymentProject)
	}

	if userCardType != "" { //日卡月卡， 前端不好区分这里用了两个字段
		condition += ` 	AND goods_name =  ? `
		pars = append(pars, userCardType)
	}

	if keyWord != "" { //用户姓名，手机号
		keyWord = "%" + keyWord + "%"
		condition += ` 	AND (mobile LIKE ?  OR  real_name LIKE ? ) `
		pars = append(pars, keyWord, keyWord)
	}

	total, err := cygx.GetCygxOrderCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY order_id  DESC "
	list, err := cygx.GetCygxOrderList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var mobiles []string
	for _, v := range list {
		mobiles = append(mobiles, v.Mobile)
	}
	inviteNameMap := cygxService.GetCygxUserBusinessCardMap(mobiles) // 根据手机号获取邀请人
	for _, v := range list {
		item := new(cygx.OrderListResp)
		item.OrderCode = v.OrderCode
		item.OrderMoney = v.OrderMoney
		item.SourceId = v.SourceId
		item.Source = v.Source
		item.SourceTitle = v.SourceTitle
		switch v.Source {
		case utils.CYGX_OBJ_ARTICLE: //文章详情
			item.HttpUrl = utils.CYGX_MFYX_URL + "/material/info/" + strconv.Itoa(v.SourceId)
		case utils.CYGX_OBJ_ACTIVITY: //活动详情
		case utils.CYGX_OBJ_ACTIVITYVIDEO: //活动视频
			item.HttpUrl = utils.CYGX_MFYX_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case utils.CYGX_OBJ_ACTIVITYVOICE: //活动音频
			item.HttpUrl = utils.CYGX_MFYX_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
			item.HttpUrl = utils.CYGX_MFYX_URL + "/activity/detail/" + strconv.Itoa(v.SourceId)
		case utils.CYGX_OBJ_YANXUANSPECIAL: //专栏详情
			item.HttpUrl = utils.CYGX_MFYX_URL + "/column/detail/" + strconv.Itoa(v.SourceId)
		}
		//OrderStatus      int       `comment:"订单状态,0:已取消、1:待支付、2:已支付、3:退款成功、4：退款处理中、5：退款异常、6：退款关闭"`
		item.OrderStatus = v.OrderStatus
		switch item.OrderStatus {
		case 3:
			item.OrderStatusText = "退款成功"
		case 4:
			item.OrderStatusText = "退款处理中"
		case 5:
			item.OrderStatusText = "退款异常"
		case 6:
			item.OrderStatusText = "退款关闭"
		}

		//TradeType        string    `comment:"交易类型，枚举值：JSAPI：公众号支付 、 NATIVE：扫码支付 、 App：App支付 、 MICROPAY：付款码支付 、 MWEB：H5支付 、 FACEPAY：刷脸支付"`
		switch v.TradeType {
		case "JSAPI":
			item.PaymentTypeText = "小程序"
		case "NATIVE":
			item.PaymentTypeText = "PC"
		case "MWEB":
			item.PaymentTypeText = "H5"
		}

		item.UserId = v.UserId
		item.RealName = v.RealName
		item.Mobile = v.Mobile
		item.Email = v.Email
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.SellerName = v.SellerName
		if v.ShareName != "" {
			item.InviteName = v.ShareName
		} else {
			item.InviteName = inviteNameMap[v.Mobile]
		}

		item.PaymentProject = v.GoodsName
		switch v.GoodsId {
		case 1:
			item.PaymentProject = "日卡"
		case 2:
			item.PaymentProject = "月卡"
		}

		item.RefundTime = v.RefundTime.Format(utils.FormatDateTime)
		item.RefundRemark = v.RefundRemark

		//if v.OrderStatus == 2 {
		item.PayTime = v.PayTime.Format(utils.FormatDateTime)
		//}
		if orderType == 1 {
			if v.GoodsId == 1 {
				item.StartDate = v.StartDate.Format(utils.FormatDateTime)
				item.EndDate = v.EndDate.Format(utils.FormatDateTime)
			} else {
				item.StartDate = v.StartDate.Format(utils.FormatDate)
				item.EndDate = v.EndDate.Format(utils.FormatDate)
			}
		}
		item.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		resp.List = append(resp.List, item)
	}
	if len(resp.List) == 0 {
		resp.List = make([]*cygx.OrderListResp, 0)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 退款撤销
// @Description 退款撤销接口
// @Param	request	body cygx.UserRemarAddReq true "type json string"
// @Success 200 操作成功
// @router /order/refund_revoke [post]
func (this *UserController) OrderRefundRevoke() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.CygxOrderRefundReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	orderCode := req.OrderCode
	orderDetail, err := cygx.GetCygxOrderDetailByOrderCode(orderCode)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败, Err:" + err.Error()
		return
	}
	if orderDetail.OrderStatus != 4 {
		br.Msg = "订单状态异常！"
		br.ErrMsg = "订单状态异常，orderCode:" + orderCode
		return
	}

	item := new(cygx.CygxOrderAction)
	item.Action = "关闭退款"
	item.OrderStatus = 6
	item.OrderStatusText = "关闭退款"
	item.OrderCode = orderDetail.OrderCode
	item.UserId = orderDetail.UserId
	item.RealName = orderDetail.RealName
	item.Mobile = orderDetail.Mobile
	item.Email = orderDetail.Email
	item.CompanyId = orderDetail.CompanyId
	item.CompanyName = orderDetail.CompanyName
	item.SellerName = orderDetail.SellerName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.AdminId = sysUser.AdminId
	item.AdminName = sysUser.RealName

	err = cygx.AddCygxOrderRefundRevoke(item)
	if err != nil {
		br.Msg = "新增失败."
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}
