package sharemanage

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

func ShareBillList(c *gin.Context) {
	req := &models.ShareBillListReq{}
	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))

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

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

func ShareBillCheck(c *gin.Context) {
	req := &struct {
		UserShareCardBillId uint32 `json:"user_share_card_bill_id"`
		CheckType           uint32 `json:"check_type"` // 1-审核失败 2-审核成功
		Remark              string `json:"remark"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	state := models.ShareCardBillStateInSendCard
	gameState := models.ShareCardStateInSendCard
	if req.CheckType == 1 {
		state = models.ShareCardBillStateAuditLose
		gameState = models.ShareCardStateAuditLose
	}
	var userShareCardBill models.UserShareCardBill
	err := orm.Eloquent.Table("user_share_card_bill").Where("id=?", req.UserShareCardBillId).Find(&userShareCardBill).Error
	if err != nil {
		logger.Errorf("user share card bill game err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	if userShareCardBill.State != models.ShareCardBillStateInCheck {
		logger.Error("state err:")
		app.Error(c, http.StatusInternalServerError, err, "共享单状态异常")
		return
	}

	begin := orm.Eloquent.Begin()
	err = begin.Table("user_share_card_bill").Where("id=?", req.UserShareCardBillId).Updates(&map[string]interface{}{
		"state":  state,
		"remark": req.Remark,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("update user share card bill err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	err = begin.Table("share_card_bill_game").Where("user_share_card_bill_id=?", req.UserShareCardBillId).Updates(&map[string]interface{}{
		"state": gameState,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("update share card bill game err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("commit err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	app.OK(c, nil, "操作成功")
	return
}

func ShareBillCardStorage(c *gin.Context) {
	req := &models.ShareBillCardStorageReq{}
	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))

	serialNumbers := make([]string, 0)
	for i, _ := range req.Cards {
		serialNumbers = append(serialNumbers, req.Cards[i].SerialNumber)
	}
	var gameGoods []models.GameCardGoods
	err := orm.Eloquent.Table("game_card_goods").Where("serial_number in (?)", serialNumbers).Find(&gameGoods).Error
	if err != nil && err != models.RecordNotFound {
		logger.Error("serial count err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "")
		return
	}
	if len(gameGoods) > 0 {
		serialString := ""
		for i, _ := range gameGoods {
			serialString += gameGoods[i].SerialNumber + " "
		}
		logger.Error("serial err")
		app.Error(c, http.StatusInternalServerError, err, serialString+"卡编号已存在")
		return
	}
	err = req.CardStorage()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		if err.Error() == "state err" {
			app.Error(c, http.StatusInternalServerError, err, "共享单状态异常")
			return
		}
		app.Error(c, http.StatusInternalServerError, err, "入库失败")
		return
	}

	ret := map[string]interface{}{}
	app.OK(c, ret, "入库成功")
}

func ShareBillInfo(c *gin.Context) {
	req := &struct {
		UserShareCardBillId uint32 `json:"user_share_card_bill_id"`
	}{}
	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))
	info, err := models.GetShareBillInfo(req.UserShareCardBillId)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

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

func UserShareCardList(c *gin.Context) {
	req := &models.UserShareCardListReq{}
	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))

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	var vmRecord models.ShareCardVmRecord
	err = orm.Eloquent.Table("share_card_vm_record").Where("provide_date=?", models.ZeroDateFormat(-1)).Find(&vmRecord).Error
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"yesterday_vm": vmRecord.ProvideVm,
		"total_vm":     vmRecord.TotalVm,
		"count":        count,
		"list":         list,
		"pageIndex":    req.Page,
		"pageSize":     req.PageSize,
	}
	app.OK(c, ret, "")
	return
}

func UserShareCardVmList(c *gin.Context) {
	req := &models.UserShareCardVmListReq{}
	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))

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

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

func ShareCardGameVmList(c *gin.Context) {
	req := &models.ShareCardGameVmListReq{}
	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))

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

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

func ShareCardUserVmList(c *gin.Context) {
	req := &models.ShareCardUserVmListReq{}
	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)
	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

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

func ShareCardRetrieveCardAudit(c *gin.Context) {
	req := &struct {
		ShareCardRetrieveId uint32 `json:"share_card_retrieve_id"`
		AuditType           uint32 `json:"audit_type"` // 1-审核失败 2-审核成功
		Remark              string `json:"remark"`
	}{}
	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))
	fmt.Println("ShareCardRetrieveId:", req.ShareCardRetrieveId)
	var shareCardRetrieve models.ShareCardRetrieve
	err := orm.Eloquent.Table("share_card_retrieve").Where("id=?", req.ShareCardRetrieveId).Find(&shareCardRetrieve).Error
	if err != nil {
		logger.Errorf("user share card bill game err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	fmt.Println("userShareCardBill:", shareCardRetrieve.ID, shareCardRetrieve.State)
	if shareCardRetrieve.State != models.RetrieveStateInCheck {
		logger.Error("state err:")
		app.Error(c, http.StatusInternalServerError, err, "共享单状态异常")
		return
	}

	auditMutex := models.ShareCardRetrieveCardAuditMutex("")
	auditMutex.Lock()
	defer auditMutex.Unlock()

	err = models.RetrieveCardAudit(req.ShareCardRetrieveId, req.AuditType, req.Remark)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	//list, count, err := req.List()
	//if err != nil {
	//	logger.Errorf("err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "查询失败")
	//	return
	//}
	//
	//ret := map[string]interface{}{
	//	"count":     count,
	//	"list":      list,
	//	"pageIndex": req.PageIndex,
	//	"pageSize":  req.PageSize,
	//}
	app.OK(c, nil, "操作成功")
	return
}

func ShareCardRetrieveCardDeliver(c *gin.Context) {
	req := &models.ShareCardRetrieveCardDeliverReq{}
	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))
	err, msg := req.Deliver()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		if msg == "" {
			msg = "操作失败"
		}
		app.Error(c, http.StatusInternalServerError, err, msg)
		return
	}
	//list, count, err := req.List()
	//if err != nil {
	//	logger.Errorf("err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "查询失败")
	//	return
	//}

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

func ShareCardRetrieveList(c *gin.Context) {
	req := &models.ShareCardRetrieveListReq{}
	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))

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

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

func ShareCardRetrieveCardInfo(c *gin.Context) {
	req := &struct {
		ShareCardRetrieveId uint32 `json:"share_card_retrieve_id"`
	}{}
	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))

	info, err := models.GetShareCardRetrieveInfo(req.ShareCardRetrieveId)
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, info, "")
	return
}

func CardIssueList(c *gin.Context) {
	req := &models.CardIssueListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

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

func CardIssueFeedbackInfo(c *gin.Context) {
	req := &struct {
		CardIssueFeedbackId uint32 `json:"card_issue_feedback_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	cardIssue, err := models.GetCardIssueFeedbackInfo(req.CardIssueFeedbackId)
	if err != nil {
		logger.Errorf("get card issue feedback info err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, cardIssue, "")
	return
}

func CardIssueCheck(c *gin.Context) {
	req := &struct {
		CardIssueFeedbackId uint32 `json:"card_issue_feedback_id"` // 卡问题反馈id
		StoreId             uint32 `json:"store_id"`               // 门店id
		SerialNumber        string `json:"serial_number"`          // 编号
		IsNormalFunction    uint32 `json:"is_normal_function"`     // 功能是否正常:1-是 2-否
		IsPackingIntact     uint32 `json:"is_packing_intact"`      // 包装是否完整:1-是 2-否
		IsCardBreakage      uint32 `json:"is_card_breakage"`       // 卡带是否破损:1-是 2-否
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	//data, _ := c.Get(jwtauth.JwtPayloadKey)
	//mapClaims := data.(jwtauth.MapClaims)
	//sysUid := ""
	//if v, ok := mapClaims["identity"]; ok {
	//	sysUid = v.(string)
	//}
	//fmt.Println("sysUid:", sysUid)

	var cardIssue models.CardIssueFeedback
	err := orm.Eloquent.Table("card_issue_feedback").Where("id=?", req.CardIssueFeedbackId).Find(&cardIssue).Error
	if err != nil {
		logger.Errorf("get card issue feedback info err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	if cardIssue.State != models.CardIssueStateFollowing {
		logger.Errorf("card issue feedback state err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "问题反馈单状态异常")
		return
	}
	if cardIssue.SerialNumber != req.SerialNumber {
		logger.Errorf("card issue serial number err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "检测的卡编号错误")
		return
	}
	if req.StoreId != cardIssue.StoreId {
		logger.Error("Store id err")
		app.Error(c, http.StatusInternalServerError, err, "操作的门店不正确")
		return
	}
	//data, _ := c.Get(jwtauth.JwtPayloadKey)
	//mapClaims := data.(jwtauth.MapClaims)
	//sysUid := float64(0)
	//if v, ok := mapClaims["identity"]; ok {
	//	sysUid = v.(float64)
	//}

	issueState := models.CardIssueStateInDeliver
	if cardIssue.ObtainType == models.ObtainTypeRentCard {
		issueState = models.CardIssueStateFollowed
	}
	begin := orm.Eloquent.Begin()
	err = begin.Table("card_issue_feedback").Where("id=?", req.CardIssueFeedbackId).Updates(map[string]interface{}{
		"is_normal_function": req.IsNormalFunction,
		"is_packing_intact":  req.IsPackingIntact,
		"is_card_breakage":   req.IsCardBreakage,
		"check_time":         time.Now(),
		"state":              issueState,
		//"check_sys_uid":      sysUid,		// TODO 店员账号
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("update card issue err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "检测的卡编号错误")
		return
	}
	if cardIssue.ObtainType == models.ObtainTypeRetrieveCard {
		functionState := 0
		status := 0
		if req.IsNormalFunction == 2 {
			functionState = 1
			status = models.GameCardGoodsStatusUnusual
		} else if req.IsNormalFunction == 1 {
			// TODO 卡功能正常入库
			sql := fmt.Sprintf(
				"UPDATE game_card_goods_stock SET rent_stock= rent_stock+1,total_stock=total_stock+1 WHERE store_id=%d AND game_card_id=%d;",
				cardIssue.StoreId, cardIssue.GameCardId)
			fmt.Println("sql:", sql)
			err = begin.Exec(sql).Error
			if err != nil {
				begin.Rollback()
				logger.Errorf("err:", logger.Field("err", err))
				app.Error(c, http.StatusInternalServerError, err, "操作失败")
				return
			}
			functionState = 2
			status = models.GameCardGoodsStatusStock
		} else {
			begin.Rollback()
			logger.Errorf("err:", logger.Field("err", err))
			app.Error(c, http.StatusInternalServerError, err, "未检测卡功能是否正常")
			return
		}

		err = begin.Table("game_card_goods").Where("serial_number=?", req.SerialNumber).Updates(map[string]interface{}{
			"function_state": functionState,
			"status":         status,
		}).Error
		if err != nil {
			begin.Rollback()
			app.Error(c, http.StatusInternalServerError, err, "操作失败")
			return
		}

	} else if cardIssue.ObtainType == models.ObtainTypeRentCard {
		// 检测有问题
		if req.IsNormalFunction == 2 {
			err = begin.Table("game_card_goods").Where("serial_number=?", req.SerialNumber).Updates(map[string]interface{}{
				"function_state": 1,
				"status":         models.GameCardGoodsStatusUnusual,
			}).Error
			if err != nil {
				begin.Rollback()
				app.Error(c, http.StatusInternalServerError, err, "操作失败")
				return
			}

			//  租卡已经减库存 不用在减库存
		} else {
			//  卡功能正常入库  入库校验 不添加库存

		}
	}

	//  检测卡入库  功能正常入库
	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("commit err")
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	// 卡的功能 正常
	//cardIssue, err := models.GetCardIssueFeedbackInfo(req.CardIssueFeedbackId)
	//if err != nil {
	//	logger.Errorf("get card issue feedback info err:",logger.Field("err",err))
	//	app.Error(c, http.StatusInternalServerError, err, "查询失败")
	//	return
	//}

	app.OK(c, nil, "操作成功")
	return
}

func CardIssueDeliver(c *gin.Context) {
	req := &struct {
		StoreId                 uint32 `json:"store_id"`
		CardIssueFeedbackId     uint32 `json:"card_issue_feedback_id"`
		DeliverExpressCompany   string `json:"deliver_express_company"`    // 发货物流公司
		DeliverExpressCompanyNo string `json:"deliver_express_company_no"` // 物流公司编号
		DeliverExpressNo        string `json:"deliver_express_no"`         // 发货物流单号
		ReissueSerialNumber     string `json:"reissue_serial_number"`      // 补发货编码
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	var cardIssue models.CardIssueFeedback
	err := orm.Eloquent.Table("card_issue_feedback").Where("id=?", req.CardIssueFeedbackId).Find(&cardIssue).Error
	if err != nil {
		logger.Errorf("get card issue feedback info err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	if cardIssue.State != models.CardIssueStateInDeliver {
		logger.Errorf("card issue feedback state err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "问题反馈单状态异常")
		return
	}
	var gameCardGoods models.GameCardGoods
	err = orm.Eloquent.Table("game_card_goods").Where("serial_number=?", req.ReissueSerialNumber).Find(&gameCardGoods).Error
	if err != nil {
		logger.Error("reissue serial number err")
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	if gameCardGoods.Status != 1 {
		logger.Error("game gard goods status err")
		app.Error(c, http.StatusInternalServerError, err, "游戏卡编码不正确")
		return
	}

	begin := orm.Eloquent.Begin()
	err = begin.Table("card_issue_feedback").Where("id=?", req.CardIssueFeedbackId).Updates(map[string]interface{}{
		"deliver_express_company":    req.DeliverExpressCompany,
		"deliver_express_no":         req.DeliverExpressNo,
		"deliver_time":               time.Now(),
		"reissue_serial_number":      gameCardGoods.SerialNumber,
		"reissue_game_card_goods_id": gameCardGoods.ID,
		"state":                      models.CardIssueStateCompleted,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("get card issue feedback info err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	sql := fmt.Sprintf("UPDATE game_card_goods_stock SET rent_stock= rent_stock-1,total_stock=total_stock-1 WHERE store_id=%d AND game_card_id=%d;", req.StoreId, gameCardGoods.GameCardId)
	fmt.Println("sql:", sql)
	err = begin.Exec(sql).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("update game card goods stock err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	err = begin.Table("game_card_goods").Where("id=?", gameCardGoods.ID).Updates(map[string]interface{}{
		"status": 6,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("get card issue feedback info err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("commit err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	if req.DeliverExpressCompanyNo != "" && req.DeliverExpressNo != "" {
		_, err = kuaidi.SubscribeExpressState(req.DeliverExpressCompanyNo, req.DeliverExpressNo)
		if err != nil {
			logger.Error("subscribe express state err:", logger.Field("err", err))
		}
	}
	app.OK(c, cardIssue, "")
	return
}

func ExpressStatePush(c *gin.Context) {
	all, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		logger.Error("read all err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	//var reqAll *url.Values
	//reqAll.Encode()
	unescape, err := url.ParseQuery(string(all))
	if err != nil {
		logger.Error("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	//fmt.Println("all:", string(unescape.Get("param")))
	var expressStatePushReq models.ExpressStatePushReq
	err = json.Unmarshal([]byte(unescape.Get("param")), &expressStatePushReq)
	if err != nil {
		logger.Error("unmarshal express state push req err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	models.TakeExpressStatePush(&expressStatePushReq)
	app.OK(c, nil, "")
	return
}

func IssueCardFunctionUnusualList(c *gin.Context) {
	req := &models.FunctionUnusualCardListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

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