package ctrl_v1

import (
	"encoding/json"
	"fmt"
	"gd_management_gateway/errors"
	"gd_management_gateway/params/param_base"
	"gd_management_gateway/params/param_v1_0"
	"gd_management_gateway/rpc_apis"
	"gd_management_gateway/rpc_apis/gd_admin"
	"gd_management_gateway/rpc_apis/gd_management"
	"time"

	"gd_management_gateway/common.in/httper"
	"gd_management_gateway/common.in/task"
	"gd_management_gateway/common.in/utils"

	"go.uber.org/zap"

	"os"
	"strings"

	"github.com/astaxie/beego"
	"github.com/tiechui1994/gopdf"
	"github.com/tiechui1994/gopdf/core"
	"github.com/unidoc/unioffice/color"
	"github.com/unidoc/unioffice/document"
	"github.com/unidoc/unioffice/measurement"
	"github.com/unidoc/unioffice/schema/soo/wml"
)

// Operations about merchant api
type MerchantApiController struct {
	metadata interface{} // 中继元数据
	beego.Controller
	LogID string
}

// @Title get merchant data api
// @Description 获取商户用户数据api列表
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_id    query uint64   true "商户id"
// @Param   page_number    query int   true "当前页"
// @Param   is_all    query bool   true "是否返回merchant_data_api_quota所有数据"
// @Success 200 	{object} params.param_v1_0.ManagementGetMerchantDataApiListResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_data_api_list [get]
func (u *MerchantApiController) ManagementGetMerchantDataApiList() {
	u.LogID = fmt.Sprintf("ManagementGetMerchantDataApiList[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementGetMerchantDataApiListReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetMerchantDataApiListReq{}
		mreq.MerchantId = req.MerchantId
		mreq.PageNumber = req.PageNumber
		mreq.IsAll = req.IsAll

		reply, err := rpc_apis.Management.ManagementGetMerchantDataApiList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetMerchantDataApiList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetMerchantDataApiListResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = reply
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title get merchant data api by total
// @Description 获取商户用户数据api总天数列表
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_id    query uint64   true "商户id"
// @Param   page_number    query int   true "当前页"
// @Param   page_size    query int   false "当前页"
// @Param   is_all    query bool   true "是否返回所有数据"
// @Param   data_api_name query string false ""
// @Success 200 	{object} params.param_v1_0.ManagementGetMerchantDataApiListByTotalResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_data_api_list_by_total [get]
func (u *MerchantApiController) ManagementGetMerchantDataApiListByTotal() {
	u.LogID = fmt.Sprintf("ManagementGetMerchantDataApiListByTotal[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementGetMerchantDataApiListByTotalReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetMerchantDataApiListByTotalReq{}
		mreq.MerchantId = req.MerchantId
		mreq.PageNumber = req.PageNumber
		mreq.DataApiName = req.DataApiName
		mreq.IsAll = req.IsAll
		mreq.PageSize = req.PageSize

		reply, err := rpc_apis.Management.ManagementGetMerchantDataApiListByTotal(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetMerchantDataApiListByTotal"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetMerchantDataApiListByTotalResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = reply
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title get merchant data api
// @Description 获取商户用户数据api列表
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_id    query uint64   true "商户id"
// @Param   page_number    query int   true "当前页"
// @Param   page_size    query int   false "当前页"
// @Param   is_all    query bool   true "是否返回所有数据"
// @Param   data_api_name query string false ""
// @Success 200 	{object} params.param_v1_0.ManagementGetMerchantDataApiListByDayResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_data_api_list_by_day [get]
func (u *MerchantApiController) ManagementGetMerchantDataApiListByDay() {
	u.LogID = fmt.Sprintf("ManagementGetMerchantDataApiListByDay[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementGetMerchantDataApiListByDayReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetMerchantDataApiListByDayReq{}
		mreq.MerchantId = req.MerchantId
		mreq.PageNumber = req.PageNumber
		mreq.DataApiName = req.DataApiName
		mreq.PageSize = req.PageSize
		mreq.IsAll = req.IsAll

		reply, err := rpc_apis.Management.ManagementGetMerchantDataApiListByDay(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetMerchantDataApiListByDay"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetMerchantDataApiListByDayResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = reply
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title set merchant data api quota
// @Description 修改商户数据api配额
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param	merchant_id	path	int64	true	"商户id"
// @Param	body	body	params.param_v1_0.ManagementSetMerchantDataApiQuotaBody	true	""
// @Success 200 	{object} params.param_v1_0.ManagementSetMerchantDataApiQuotaResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_data_api_quota/:merchant_id [put]
func (u *MerchantApiController) ManagementSetMerchantDataApiQuota() {
	u.LogID = fmt.Sprintf("ManagementSetMerchantDataApiQuota[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementSetMerchantDataApiQuotaReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	// 记录用户行为日志
	AddActionLogTask := func() error {
		// 获取商户基本信息
		mreq := gd_management.GetMerchantInfoReq{
			Id: req.MerchantId,
		}

		info, err := rpc_apis.Management.GetMerchantInfo(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantInfo"),
				zap.String("args", utils.MarshalJsonString(mreq)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		// 获取修改前数据api内容
		rreq := gd_management.GetMerchantDataApiQuotaReq{
			Id: int64(req.Body.MerchantDataApiId),
		}

		reply, err := rpc_apis.Management.GetMerchantDataApiQuota(utils.NewContextFromBeegoCtx(u.Ctx), &rreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantDataApiQuota"),
				zap.String("args", utils.MarshalJsonString(rreq)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		// 格式化json数据
		beforeBytes, _ := json.Marshal(reply)
		contentBytes, _ := json.Marshal(req.Body)

		areq := gd_admin.AddActionLogReq{
			Uid:        req.Uid,
			Name:       info.MerchantName,
			Modules:    "商户数据API",
			Func:       "商户修改数据API配额",
			Before:     string(beforeBytes),
			Content:    string(contentBytes),
			ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		}
		err = AddActionLog(areq)
		if err != nil {
			return err
		}

		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementSetMerchantDataApiQuotaReq{
			MerchantDataApiId: req.Body.MerchantDataApiId,
			DayCount:          req.Body.DayCount,
			Count:             req.Body.Count,
			DayNumber:         req.Body.DayNumber,
		}

		_, err := rpc_apis.Management.ManagementSetMerchantDataApiQuota(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementSetMerchantDataApiQuota"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementSetMerchantDataApiQuotaResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, AddActionLogTask, handleDataTask,
	)
}

// @Title get merchant data api quota
// @Description 获取商户数据api配额
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_data_api_id    query uint64   true "商户id"
// @Success 200 	{object} params.param_v1_0.ManagementGetMerchantDataApiQuotaResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_data_api_quota [get]
func (u *MerchantApiController) ManagementGetMerchantDataApiQuota() {
	u.LogID = fmt.Sprintf("ManagementGetMerchantDataApiQuota[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementGetMerchantDataApiQuotaReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetMerchantDataApiQuotaReq{}
		mreq.MerchantDataApiId = req.MerchantDataApiId

		reply, err := rpc_apis.Management.ManagementGetMerchantDataApiQuota(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetMerchantDataApiQuota"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetMerchantDataApiQuotaResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = reply
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title get merchant base api list
// @Description 获取商户基础api列表
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_data_api_id    query uint64   true "商户id"
// @Success 200 	{object} params.param_v1_0.ManagementGetMerchantBaseApiListResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_base_api_list [get]
func (u *MerchantApiController) ManagementGetMerchantBaseApiList() {
	u.LogID = fmt.Sprintf("ManagementGetMerchantBaseApiList[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementGetMerchantBaseApiListReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetMerchantBaseApiListReq{}
		mreq.MerchantDataApiId = req.MerchantDataApiId

		reply, err := rpc_apis.Management.ManagementGetMerchantBaseApiList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetMerchantBaseApiList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetMerchantBaseApiListResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = reply

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title get merchant base api info
// @Description 获取商户基础api信息
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_child_api_id    query uint64   true "商户基础api id"
// @Success 200 	{object} params.param_v1_0.ManagementGetMerchantBaseApiInfoResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_base_api_info [get]
func (u *MerchantApiController) ManagementGetMerchantBaseApiInfo() {
	u.LogID = fmt.Sprintf("ManagementGetMerchantBaseApiInfo[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementGetMerchantBaseApiInfoReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetMerchantBaseApiInfoReq{}
		mreq.MerchantChildApiId = req.MerchantChildApiId

		reply, err := rpc_apis.Management.ManagementGetMerchantBaseApiInfo(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetMerchantBaseApiInfo"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetMerchantBaseApiInfoResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = reply

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title update merchant base api
// @Description 商户修改基础api
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param	merchant_id	path	int64	true	"商户id"
// @Param   update_info    body rpc_apis.gd_management.ManagementUpdateMerchantBaseApiReq   true "更新信息"
// @Success 200 	{object} params.param_v1_0.ManagementUpdateMerchantBaseApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_base_api/:merchant_id [put]
func (u *MerchantApiController) ManagementUpdateMerchantBaseApi() {
	u.LogID = fmt.Sprintf("ManagementUpdateMerchantBaseApi[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementUpdateMerchantBaseApiReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}
	// 记录用户行为日志
	AddActionLogTask := func() error {
		// 获取商户信息
		mreq := gd_management.GetMerchantInfoReq{
			Id: req.MerchantId,
		}

		info, err := rpc_apis.Management.GetMerchantInfo(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantInfo"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		// 获取商户基础api信息
		rreq := gd_management.ManagementGetMerchantBaseApiInfoReq{
			MerchantChildApiId: uint64(req.UpdateInfo.MerchantChildApiId),
		}

		reply, err := rpc_apis.Management.ManagementGetMerchantBaseApiInfo(utils.NewContextFromBeegoCtx(u.Ctx), &rreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantInfo"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		// 构建json
		beforeBytes, _ := json.Marshal(reply)
		contentBytes, _ := json.Marshal(req.UpdateInfo)

		// 记录行为日志
		areq := gd_admin.AddActionLogReq{
			Uid:        req.Uid,
			Name:       info.MerchantName,
			Modules:    "商户数据API",
			Func:       "商户修改基础api",
			Before:     string(beforeBytes),
			Content:    string(contentBytes),
			ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		}
		err = AddActionLog(areq)
		if err != nil {
			return err
		}

		return nil
	}

	handleDataTask := func() error {
		mreq := req.UpdateInfo
		_, err := rpc_apis.Management.ManagementUpdateMerchantBaseApi(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementUpdateMerchantBaseApi"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementUpdateMerchantBaseApiResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, AddActionLogTask, handleDataTask,
	)
}

// @Title add merchant data api
// @Description 后台管理对商户添加数据api
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param	body	body	params.param_v1_0.ManagementAddMerchantDataApiBody true ""
// @Success 200 	{object} params.param_v1_0.ManagementAddMerchantDataApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_data_api [post]
func (u *MerchantApiController) ManagementAddMerchantDataApi() {
	u.LogID = fmt.Sprintf("ManagementAddMerchantDataApi[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementAddMerchantDataApiReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementCreateDataApiOrderReq{
			MerchantId:  req.Body.MerchantId,
			ComboId:     req.Body.DataApiComboId,
			QueryTypeId: req.Body.QueryTypeId,
		}
		_, err := rpc_apis.Management.ManagementAddMerchantDataApiNew(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementAddMerchantDataApiNew"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		resp := param_v1_0.ManagementAddMerchantDataApiResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	AddActionLogTask := func() error {
		// 记录用户行为日志
		go func() {
			var name string
			// 获取商户信息
			rreq := gd_management.GetMerchantInfoReq{
				Id: req.Body.MerchantId,
			}

			reply, err := rpc_apis.Management.GetMerchantInfo(utils.NewContextFromBeegoCtx(u.Ctx), &rreq)
			if err != nil {
				l.Error("rpc",
					zap.String("call", "GetMerchantInfo"),
					zap.String("args", utils.MarshalJsonString(rreq)),
					zap.String("error", err.Error()))
			} else {
				name = reply.MerchantName
			}

			bytes, err := json.Marshal(req.Body)
			if err != nil {
				return
			}

			areq := gd_admin.AddActionLogReq{
				Uid:        req.Uid,
				Name:       name,
				Modules:    "用户管理",
				Func:       "添加数据API",
				Content:    string(bytes),
				ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
			}
			AddActionLog(areq)
		}()

		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask, AddActionLogTask,
	)
}

// @Title add merchant base api
// @Description 商户添加基础api
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   data    body params.param_v1_0.MerchantAddBaseApiReq   true ""
// @Success 200 	{object} params.param_v1_0.ManagementAddMerchantBaseApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_base_api [post]
func (u *MerchantApiController) ManagementAddMerchantBaseApi() {
	u.LogID = fmt.Sprintf("ManagementAddMerchantBaseApi[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementAddMerchantBaseApiReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementAddMerchantBaseApiReq{}
		mreq.MerchantDataApiId = req.Data.MerchantDataApiId
		mreq.BaseApiIds = req.Data.BaseApiIds

		_, err := rpc_apis.Management.ManagementAddMerchantBaseApi(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementAddMerchantBaseApi"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementAddMerchantBaseApiResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

const (
	TABLE_IG = "IPAexG"
	TABLE_MD = "MPBOLD"
	TABLE_MY = "微软雅黑"
)

var RequestParamCol = map[int]string{
	0: "字段名",
	1: "数据类型",
	2: "含义",
	3: "例子",
	4: "必填",
}

const (
	ErrFile    = 1
	FONT_MY    = "微软雅黑"
	FONT_MD    = "MPBOLD"
	DateFormat = "2006-01-02 15:04:05"
)

var (
	largeFont = core.Font{Family: FONT_MY, Size: 20}
	headFont  = core.Font{Family: FONT_MY, Size: 15}
	textFont  = core.Font{Family: FONT_MY, Size: 10}
)

var (
	PdfFont1File = "/etc/gd_management_gateway/mplus-1p-bold.ttf"
	PdfFont2File = "/etc/gd_management_gateway/microsoft.ttf"
)

type PdfController struct {
	Apis []gd_management.ApiParamStructInfo
	err  error
}

func ParseParams(report *core.Report, unitPtr *float64, params []gd_management.ParamStruct, isReqParse bool) {
	unit := *unitPtr
	lineSpace := 0.01 * unit
	lineHeight := 2 * unit
	lineHight := 1.9 * unit
	length := len(params)
	cellNumber := 5

	if !isReqParse {
		cellNumber = 4
	}
	for i := length - 1; i >= 0; i-- {
		ps := params[i]
		baseInfo := gopdf.NewDivWithWidth(80*unit, lineHight, lineSpace, report)
		baseInfo.SetMarign(core.Scope{Left: 4 * unit, Top: 1 * unit})
		baseInfo.SetFont(textFont).SetContent(fmt.Sprintf("%s:", ps.StructName)).GenerateAtomicCell()
		table := gopdf.NewTable(cellNumber, len(ps.Params)+1, 80*unit, lineHeight, report)
		table.SetMargin(core.Scope{20, 0, 0, 0})
		f1 := core.Font{Family: TABLE_MY, Size: 10}
		border := core.NewScope(0.5*unit, 0.5*unit, 0, 0)

		for i := 0; i < len(ps.Params)+1; i++ {
			cells := make([]*gopdf.TableCell, cellNumber)
			for j := 0; j < cellNumber; j++ {
				cells[j] = table.NewCell()
			}
			if i == 0 {
				for j := 0; j < cellNumber; j++ {
					s := RequestParamCol[j]
					w := table.GetColWidth(i, j)
					e := gopdf.NewTextCell(w, lineHeight, lineSpace, report)
					e.SetFont(f1)
					//e.SetBackColor("255,192,203")
					e.SetBorder(border)
					e.SetContent(s)
					cells[j].SetElement(e)
				}
				continue
			}

			for j := 0; j < cellNumber; j++ {
				s := ""
				if j == 0 {
					s = ps.Params[i-1].Name
				}
				if j == 1 {
					s = ps.Params[i-1].Type
				}

				if j == 2 {
					s = ps.Params[i-1].Mean
				}
				if j == 3 {
					s = ""
					if len([]byte(ps.Params[i-1].Example)) < 256 {
						s = ps.Params[i-1].Example
					}
				}

				if isReqParse {
					if j == 4 {
						if ps.Params[i-1].Required {
							s = "是"
						} else {
							s = "否"
						}
					}
				}

				w := table.GetColWidth(i, j)
				e := gopdf.NewTextCell(w, lineHeight, lineSpace, report)
				e.SetFont(f1)
				e.SetBorder(border)
				e.SetContent(s)
				cells[j].SetElement(e)
			}
		}

		table.GenerateAtomicCell()
		baseInfo = gopdf.NewDivWithWidth(80*unit, lineHight, lineSpace, report)
		baseInfo.SetMarign(core.Scope{Left: 4 * unit, Top: 1 * unit})
		baseInfo.SetFont(textFont).SetContent(fmt.Sprintf("\n\n")).GenerateAtomicCell()
	}
}

func ParseErrorList(report *core.Report, unitPtr *float64, list []gd_management.ErrorCode) {
	unit := *unitPtr
	lineSpace := 0.01 * unit
	lineHeight := 2 * unit
	lineHight := 1.9 * unit

	table := gopdf.NewTable(2, len(list)+1, 80*unit, lineHeight, report)
	table.SetMargin(core.Scope{20, 0, 0, 0})
	f1 := core.Font{Family: TABLE_MY, Size: 10}
	border := core.NewScope(0.5*unit, 0.5*unit, 0, 0)

	for i := 0; i < len(list)+1; i++ {
		cells := make([]*gopdf.TableCell, 2)
		for j := 0; j < 2; j++ {
			cells[j] = table.NewCell()
		}
		if i == 0 {
			for j := 0; j < 2; j++ {
				s := "code"
				if j == 1 {
					s = "message"
				}
				w := table.GetColWidth(i, j)
				e := gopdf.NewTextCell(w, lineHeight, lineSpace, report)
				e.SetFont(f1)
				//e.SetBackColor("255,192,203")
				e.SetBorder(border)
				e.SetContent(s)
				cells[j].SetElement(e)
			}
			continue
		}

		for j := 0; j < 2; j++ {
			s := ""
			if j == 0 {
				s = list[i-1].Code
			}
			if j == 1 {
				s = list[i-1].Msg
			}
			w := table.GetColWidth(i, j)
			e := gopdf.NewTextCell(w, lineHeight, lineSpace, report)
			e.SetFont(f1)
			e.SetBorder(border)
			e.SetContent(s)
			cells[j].SetElement(e)
		}
	}

	table.GenerateAtomicCell()
	baseInfo := gopdf.NewDivWithWidth(80*unit, lineHight, lineSpace, report)
	baseInfo.SetMarign(core.Scope{Left: 4 * unit, Top: 1 * unit})
	baseInfo.SetFont(textFont).SetContent(fmt.Sprintf("\n\n")).GenerateAtomicCell()
}

func pdfSetContent(report *core.Report, unit, lineSpace, lineHight float64, content string) {
	baseInfo := gopdf.NewDivWithWidth(80*unit, lineHight, lineSpace, report)
	baseInfo.SetMarign(core.Scope{Left: 4 * unit, Top: 1 * unit})
	baseInfo.SetFont(textFont).SetContent(content).GenerateAtomicCell()
}

func GetChinsesNumber(data int) string {
	ret := fmt.Sprintf("%d", data)
	switch data {
	case 1:
		ret = "一"
	case 2:
		ret = "二"
	case 3:
		ret = "三"
	case 4:
		ret = "四"
	case 5:
		ret = "五"
	case 6:
		ret = "六"
	case 7:
		ret = "七"
	case 8:
		ret = "八"
	case 9:
		ret = "九"
	case 10:
		ret = "十"
	}
	return ret
}
func (pc *PdfController) PdfExecutor(report *core.Report) {
	unit := report.GetUnit()
	lineSpace := 0.01 * unit
	lineHight := 1.9 * unit

	baseInfo := gopdf.NewDivWithWidth(80*unit, lineHight, lineSpace, report)
	baseInfo.SetMarign(core.Scope{Left: 4 * unit, Top: 1 * unit})
	baseInfo.SetFont(largeFont).SetContent(fmt.Sprintf("%s", "数据接口文档")).HorizontalCentered().GenerateAtomicCell()

	for i, v := range pc.Apis {
		if v.IsCrypto {
			pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%s %s【密文】【%s】)\n", GetChinsesNumber(i+1), v.ApiName, v.ApiMethod))
		} else {

			pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%s %s【明文】【%s】\n", GetChinsesNumber(i+1), v.ApiName, v.ApiMethod))
		}
		//pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%d.1 %s\n%s", i+1, "http方法", v.ApiMethod))
		pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%d.1 %s\n%s", i+1, "http路由", v.ApiRouter))
		pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%d.2 %s", i+1, "http 访问参数"))
		ParseParams(report, &unit, v.RequestParams, true)

		pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%d.3 %s", i+1, "响应参数"))
		ParseParams(report, &unit, v.ResponseParams, false)
		if v.JsonExample != "" {
			pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("json数据示例:\n%s", v.JsonExample))
		}

		if len(v.ErrorList) != 0 {
			pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%d.4 %s", i+1, "错误代码"))
			ParseErrorList(report, &unit, v.ErrorList)
			pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%d.5 %s\n", i+1, "补充说明"))
		} else {
			pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("%d.4 %s\n", i+1, "补充说明"))
		}

		if v.Comment != "" {
			pdfSetContent(report, unit, lineSpace, lineHight, fmt.Sprintf("\t\n%s", v.Comment))
		}

	}

}

func exportToWordParam(params []gd_management.ParamStruct, doc *document.Document, isReqParse bool) {
	length := len(params)
	cellNumber := 5
	if !isReqParse {
		cellNumber = 4
	}
	for i := length - 1; i >= 0; i-- {
		ps := params[i]
		doc.AddParagraph()
		// 表格名称
		para := doc.AddParagraph()
		para.SetStyle("Heading3")
		run := para.AddRun()
		run.Properties().SetBold(true)
		run.AddText(ps.StructName)

		table := doc.AddTable()
		// 4 inches wide
		table.Properties().SetWidth(5 * measurement.Inch)
		borders := table.Properties().Borders()
		// thin borders
		borders.SetAll(wml.ST_BorderSingle, color.Auto, measurement.Zero)
		for j := 0; j < len(ps.Params); j++ {
			if j == 0 {
				row := table.AddRow()
				for k := 0; k < cellNumber; k++ {
					cellName := RequestParamCol[k]
					cell := row.AddCell()
					if k == 1 {
						cell.Properties().SetColumnSpan(1)
					} else {
						cell.Properties().SetColumnSpan(2)
					}
					run := cell.AddParagraph().AddRun()
					run.AddText(cellName)
				}
			}
			row := table.AddRow()
			cell := row.AddCell()
			cell.Properties().SetColumnSpan(2)
			run := cell.AddParagraph().AddRun()
			run.AddText(ps.Params[j].Name)

			cell = row.AddCell()
			cell.Properties().SetColumnSpan(1)
			run = cell.AddParagraph().AddRun()
			run.AddText(ps.Params[j].Type)

			cell = row.AddCell()
			cell.Properties().SetColumnSpan(2)
			run = cell.AddParagraph().AddRun()
			run.AddText(ps.Params[j].Mean)

			cell = row.AddCell()
			cell.Properties().SetColumnSpan(2)
			run = cell.AddParagraph().AddRun()
			run.AddText(ps.Params[j].Example)

			if isReqParse {
				cell = row.AddCell()
				cell.Properties().SetColumnSpan(2)
				run = cell.AddParagraph().AddRun()
				if ps.Params[j].Required {
					run.AddText("是")
				} else {
					run.AddText("否")
				}

			}

		}
	}
}

func exportToWordErrorCode(list []gd_management.ErrorCode, doc *document.Document) {

	table := doc.AddTable()
	// 4 inches wide
	table.Properties().SetWidth(4 * measurement.Inch)
	borders := table.Properties().Borders()
	// thin borders
	borders.SetAll(wml.ST_BorderSingle, color.Auto, measurement.Zero)

	for i, v := range list {
		if i == 0 {
			row := table.AddRow()
			for j := 0; j < 2; j++ {
				cell := row.AddCell()
				cell.Properties().SetColumnSpan(2)
				run := cell.AddParagraph().AddRun()
				if j == 0 {
					run.AddText("code")
				} else {
					run.AddText("msg")
				}
			}
		}
		row := table.AddRow()
		cell := row.AddCell()
		cell.Properties().SetColumnSpan(2)
		run := cell.AddParagraph().AddRun()
		run.AddText(v.Code)

		cell = row.AddCell()
		cell.Properties().SetColumnSpan(2)
		run = cell.AddParagraph().AddRun()
		run.AddText(v.Msg)
	}

}

func setWordParagraph(doc *document.Document, pstyle string, ptext string, text string, tailParagraph bool) {
	para := doc.AddParagraph()
	para.SetStyle("pstyle")
	if pstyle == "Title" {
		para.Properties().SetAlignment(wml.ST_JcCenter)
	}
	run := para.AddRun()
	run.Properties().SetBold(true)
	run.AddText(ptext)
	if text != "" {
		para = doc.AddParagraph()
		para.Properties().SetFirstLineIndent(0.5 * measurement.Inch)
		run = para.AddRun()
		run.AddText(text)
	}
	if tailParagraph {
		doc.AddParagraph()
		doc.AddParagraph()
	}
}

func exportToWord(apiInfos []gd_management.ApiParamStructInfo, baseDir string, dataApiName string) (string, error) {
	filename := fmt.Sprintf("接口文档_%s.docx", dataApiName)
	fullpath := strings.TrimRight(baseDir, "/") + "/" + filename
	os.Remove(fullpath)

	doc := document.New()

	// 标题
	setWordParagraph(doc, "Title", "数据接口文档", "", true)

	for i, v := range apiInfos {
		// api名称
		ptext := fmt.Sprintf("%s: %s【密文】【%s】", GetChinsesNumber(i+1), v.ApiName, v.ApiMethod)
		if v.IsCrypto == false {
			ptext = fmt.Sprintf("%s: %s【明文】【%s】", GetChinsesNumber(i+1), v.ApiName, v.ApiMethod)
		}
		setWordParagraph(doc, "Heading", ptext, "", true)

		// 请求方式
		//setWordParagraph(doc, "Heading2", fmt.Sprintf("%d.1: 请求方式", i+1), v.ApiMethod, true)

		// 请求路由
		setWordParagraph(doc, "Heading2", fmt.Sprintf("%d.1: http路由", i+1), v.ApiRouter, true)

		// 请求参数
		setWordParagraph(doc, "Heading2", fmt.Sprintf("%d.2: http 访问参数", i+1), "", false)
		exportToWordParam(v.RequestParams, doc, true)
		doc.AddParagraph()
		doc.AddParagraph()

		// 响应参数
		setWordParagraph(doc, "Heading2", fmt.Sprintf("%d.3: 响应参数", i+1), "", false)
		exportToWordParam(v.ResponseParams, doc, false)
		if v.JsonExample != "" {
			v.JsonExample = strings.Replace(v.JsonExample, "\n", "\n\r", -1)
			doc.AddParagraph()
			setWordParagraph(doc, "Heading23", "  json数据示例", "", false)
			para := doc.AddParagraph()
			run := para.AddRun()
			run.AddText(fmt.Sprintf("%s", v.JsonExample))
		}
		doc.AddParagraph()
		doc.AddParagraph()

		// 错误码
		setWordParagraph(doc, "Heading2", fmt.Sprintf("%d.4 错误代码", i+1), "", false)
		exportToWordErrorCode(v.ErrorList, doc)
		doc.AddParagraph()
		doc.AddParagraph()

		// 备注
		setWordParagraph(doc, "Heading2", fmt.Sprintf("%d.5 补充说明", i+1), v.Comment, false)
	}
	err := doc.SaveToFile(fullpath)
	if err != nil {
		return filename, errors.FileOpenFailed
	}
	return filename, nil
}

func exportToPdf(apiInfos []gd_management.ApiParamStructInfo, baseDir string, dataApiName string) (string, error) {

	filename := fmt.Sprintf("接口文档_%s.pdf", dataApiName)
	fullpath := strings.TrimRight(baseDir, "/") + "/" + filename
	os.Remove(fullpath)
	r := core.CreateReport()
	font1 := core.FontMap{
		FontName: TABLE_MD,
		FileName: PdfFont1File,
	}
	font2 := core.FontMap{
		FontName: TABLE_MY,
		FileName: PdfFont2File,
	}
	r.SetFonts([]*core.FontMap{&font1, &font2})
	r.SetPage("A4", "mm", "P")
	pc := PdfController{}
	pc.Apis = apiInfos
	r.RegisterExecutor(core.Executor(pc.PdfExecutor), core.Detail)
	r.Execute(fullpath)

	if pc.err != nil {
		return "", pc.err
	}
	return filename, nil
}

// @Title export merchant base api file
// @Description 商户添加基础api
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_data_api_id    query int64   true ""
// @Param   file_type        query int false ""
// @Success 200 	{object} params.param_v1_0.ManagementExportMerchantBaseApiFileResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_api_file [get]
func (u *MerchantApiController) ManagementExportMerchantBaseApiFile() {
	u.LogID = fmt.Sprintf("ManagementExportMerchantBaseApiFile[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementExportMerchantBaseApiFileReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementConvertMerchantDataApiReq{}
		mreq.MerchantDataApiId = req.MerchantDataApiId

		reply, err := rpc_apis.Management.ManagementConvertMerchantDataApi(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementConvertMerchantDataApi"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		filename := ""
		if req.FileType == 0 {
			filename, err = exportToPdf(reply.Apis, beego.BConfig.WebConfig.StaticDir["/export"], reply.DataApiName)
		} else {
			filename, err = exportToWord(reply.Apis, beego.BConfig.WebConfig.StaticDir["/export"], reply.DataApiName)
		}
		if err != nil {
			return errors.ExportPdfFailed
		}
		resp := param_v1_0.ManagementExportMerchantBaseApiFileResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}

		resp.DownloadFile = "http://" + ServerIp + ":" + ServerPort + "/export/" + filename
		if true {
			fullpath := strings.TrimRight(beego.BConfig.WebConfig.StaticDir["/export"], "/") + "/" + filename
			utils.OssUploadFile(fullpath, filename)
			resp.DownloadFile = getOssFileUrl(filename)
		}
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title del merchant data api
// @Description 删除商户数据api
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_data_api_id    path uint64   true "商户数据api id"
// @Success 200 	{object} params.param_v1_0.ManagementDelMerchantDataApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /data_api/:merchant_data_api_id [delete]
func (u *MerchantApiController) ManagementDelMerchantDataApi() {
	u.LogID = fmt.Sprintf("ManagementDelMerchantDataApi[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementDelMerchantDataApiReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementDelMerchantDataApiReq{}
		mreq.MerchantDataApiId = req.MerchantDataApiId

		_, err := rpc_apis.Management.ManagementDelMerchantDataApi(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementDelMerchantDataApi"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementDelMerchantDataApiResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title get merchant base api list all
// @Description 获取商户所有基础api列表
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_id    query uint64   true "商户id"
// @Param   only_base_api    query bool   false "是否只返基础api"
// @Success 200 	{object} params.param_v1_0.ManagementGetMerchantBaseApiListAllResp "响应信息"
// @Failure 500 	服务器错误
// @router /merchant_base_api_list_all [get]
func (u *MerchantApiController) ManagementGetMerchantBaseApiListAll() {
	u.LogID = fmt.Sprintf("ManagementGetMerchantBaseApiListAll[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementGetMerchantBaseApiListAllReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetMerchantBaseApiListAllReq{}
		mreq.MerchantId = req.MerchantId
		mreq.OnlyBaseApi = req.OnlyBaseApi

		reply, err := rpc_apis.Management.ManagementGetMerchantBaseApiListAll(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetMerchantBaseApiListAll"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetMerchantBaseApiListAllResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = reply

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}

// @Title set user merchant day count limit
// @Description 设置总次数套餐每天调用上限
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param       merchant_id     path    int64   true    "商户id"
// @Param	body	body	params.param_v1_0.ManagementSetDayCountLimitBody	true	""
// @Success 200 	{object} params.param_v1_0.ManagementSetDayCountLimitResp "响应信息"
// @Failure 500 	服务器错误
// @router /day_count_limit/:merchant_id [put]
func (u *MerchantApiController) ManagementSetDayCountLimit() {
	u.LogID = fmt.Sprintf("ManagementSetDayCountLimit[%d]", time.Now().UnixNano())

	req := &param_v1_0.ManagementSetDayCountLimitReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	// 记录用户行为日志
	AddActionLogTask := func() error {
		// 获取商户基本信息
		mreq := gd_management.GetMerchantInfoReq{
			Id: req.MerchantId,
		}

		info, err := rpc_apis.Management.GetMerchantInfo(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantInfo"),
				zap.String("args", utils.MarshalJsonString(mreq)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		// TODO 增加获取老数据
		// 获取修改前数据api内容
		rreq := gd_management.GetMerchantDataApiQuotaReq{
			Id: int64(req.Body.MerchantDataApiId),
		}

		reply, err := rpc_apis.Management.GetMerchantDataApiQuota(utils.NewContextFromBeegoCtx(u.Ctx), &rreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantDataApiQuota"),
				zap.String("args", utils.MarshalJsonString(rreq)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		// 格式化json数据
		beforeBytes, _ := json.Marshal(reply)
		contentBytes, _ := json.Marshal(req.Body)

		areq := gd_admin.AddActionLogReq{
			Uid:        req.Uid,
			Name:       info.MerchantName,
			Modules:    "商户数据API",
			Func:       "商户修改数据API每日调用上限",
			Before:     string(beforeBytes),
			Content:    string(contentBytes),
			ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		}
		err = AddActionLog(areq)
		if err != nil {
			return err
		}

		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementSetDayCountLimitReq{
			MerchantDataApiId: req.Body.MerchantDataApiId,
			DayCount:          req.Body.DayCount,
			DayTotalCount:     req.Body.DayTotalCount,
		}

		_, err := rpc_apis.Management.ManagementSetDayCountLimit(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementSetDayCountLimit"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementSetDayCountLimitResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, AddActionLogTask, handleDataTask,
	)
}

// @Title 修改商户数据api配额-新接口
// @Description 修改商户数据api配额-新接口
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param	merchant_id	path	int64	true	"商户id"
// @Param	body	body	params.param_v1_0.UpdateManagementSetMerchantDataApiBody	true	""
// @Success 200 	{object} params.param_v1_0.UpdateManagementSetMerchantDataApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /quota/:merchant_id [put]
func (u *MerchantApiController) UpdateManagementSetMerchantDataApi() {
	u.LogID = fmt.Sprintf("UpdateManagementSetMerchantDataApi[%d]", time.Now().UnixNano())

	req := &param_v1_0.UpdateManagementSetMerchantDataApiReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	// 记录用户行为日志
	AddActionLogTask := func() error {
		// 获取商户基本信息
		mreq := gd_management.GetMerchantInfoReq{
			Id: req.MerchantId,
		}

		info, err := rpc_apis.Management.GetMerchantInfo(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantInfo"),
				zap.String("args", utils.MarshalJsonString(mreq)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		// 获取修改前数据api内容
		rreq := gd_management.GetMerchantDataApiQuotaReq{
			Id: int64(req.Body.MerchantDataApiId),
		}

		reply, err := rpc_apis.Management.GetMerchantDataApiQuota(utils.NewContextFromBeegoCtx(u.Ctx), &rreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetMerchantDataApiQuota"),
				zap.String("args", utils.MarshalJsonString(rreq)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		// 格式化json数据
		beforeBytes, _ := json.Marshal(reply)
		contentBytes, _ := json.Marshal(req.Body)

		areq := gd_admin.AddActionLogReq{
			Uid:        req.Uid,
			Name:       info.MerchantName,
			Modules:    "商户数据API",
			Func:       "商户修改数据API配额",
			Before:     string(beforeBytes),
			Content:    string(contentBytes),
			ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		}
		err = AddActionLog(areq)
		if err != nil {
			return err
		}

		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.UpdateMerchantDataApiReq{
			MerchantDataApiId:     req.Body.MerchantDataApiId,
			CountThresholds:       req.Body.CountThresholds,
			IpWhitelist:           req.Body.IpWhitelist,
			IpWhitelistEnable:     req.Body.IpWhitelistEnable,
			CountThresholdsEnable: req.Body.CountThresholdsEnable,
			DayTotalCount:         req.Body.DayTotalCount,
			TotalComboDayCount:    req.Body.TotalComboDayCount,
		}
		if req.Body.DayComboId > 0 {
			mreq.DayCount = int(req.Body.DayComboIncreaseCount)
			mreq.DayNumber = req.Body.DayComboIncreaseDays
			mreq.DayThresholds = req.Body.DayThresholds
			mreq.ComboId = req.Body.DayComboId
		} else if req.Body.TotalComboId > 0 {
			mreq.Count = int(req.Body.TotalComboIncreaseCount)
			mreq.ComboId = req.Body.TotalComboId
		} else {
			return errors.ArgsError
		}

		if _, err := rpc_apis.Management.UpdateMerchantDataApiQouta(utils.NewContextFromBeegoCtx(u.Ctx), &mreq); err != nil {
			l.Error("rpc",
				zap.String("call", "UpdateMerchantDataApiQouta"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		resp := param_v1_0.UpdateManagementSetMerchantDataApiResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, AddActionLogTask, handleDataTask,
	)
}

// @Title 修改商户数据api别名
// @Description 修改商户数据api别名
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param	body	body	params.param_v1_0.UpdateMerchantDataApiAliasBody	true	""
// @Success 200 	{object} params.param_v1_0.UpdateManagementSetMerchantDataApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /alias [put]
func (u *MerchantApiController) UpdateMerchantDataApiAlias() {
	u.LogID = fmt.Sprintf("UpdateMerchantDataApiAlias[%d]", time.Now().UnixNano())

	req := &param_v1_0.UpdateMerchantDataApiAliasReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.UpdateMerchantDataApiAliasReq{
			MerchantDataApiId: req.Body.MerchantDataApiId,
			Alias:             req.Body.Alias,
		}

		if _, err := rpc_apis.Management.UpdateMerchantDataApiAlias(utils.NewContextFromBeegoCtx(u.Ctx), &mreq); err != nil {
			l.Error("rpc",
				zap.String("call", "UpdateMerchantDataApiAlias"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}

		resp := param_v1_0.UpdateManagementSetMerchantDataApiResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}

		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

	// 执行以上定义的任务
	task.Do(&task.PanicRecover{
		Ctx:   u.Ctx,
		LogID: u.LogID}, u.Ctx,
		getParamsTask, handleDataTask,
	)
}
