package ctrl_v1

import (
	"gd_management_gateway/consts"
	"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_management"
	"encoding/json"
	"fmt"
	"os"
	"path"
	"strings"
	"time"

	"gd_management_gateway/common.in/httper"
	"gd_management_gateway/common.in/task"
	"gd_management_gateway/common.in/utils"
	"github.com/astaxie/beego"
	"github.com/tealeg/xlsx"
	"github.com/tidwall/gjson"
	"go.uber.org/zap"
)

// Operations about provider
type BaseProviderController struct {
	metadata interface{} // 中继元数据
	beego.Controller
	LogID string
}

// @Title 三方平台添加
// @Description 三方平台添加
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   body     body   rpc_apis.gd_management.ManagementAddProviderPlatformReq true "参数"
// @Success 200 	{object} params.param_v1_0.ManagementAddProviderPlatformResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform [post]
func (u *BaseProviderController) ManagementAddProviderPlatform() {
	u.LogID = fmt.Sprintf("ManagementAddProviderPlatform[%d]", time.Now().UnixNano())

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

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

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

// @Title 三方平台删除
// @Description 三方平台删除
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   provider_id    query   int64 true "三方平台id"
// @Success 200 	{object} params.param_v1_0.ManagementDelProviderPlatformResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform [delete]
func (u *BaseProviderController) ManagementDelProviderPlatform() {
	u.LogID = fmt.Sprintf("ManagementAddProviderPlatform[%d]", time.Now().UnixNano())

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

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

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

// @Title 三方平台修改
// @Description 三方平台修改
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   body    body   rpc_apis.gd_management.ManagementUpdateProviderPlatformReq true "参数"
// @Success 200 	{object} params.param_v1_0.ManagementUpdateProviderPlatformResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform [put]
func (u *BaseProviderController) ManagementUpdateProviderPlatform() {
	u.LogID = fmt.Sprintf("ManagementUpdateProviderPlatform[%d]", time.Now().UnixNano())

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

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

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

// @Title 三方平台列表获取
// @Description 三方平台列表获取
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   page_size    query   int false "页大小"
// @Param   page_number    query   int false "页数"
// @Param   search    query   string false "搜索字符串"
// @Param   is_all    query   bool false "是否全量返回"
// @Param   provider_api_id    query   int false ""
// @Success 200 	{object} params.param_v1_0.ManagementGetProviderPlatformListResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform [get]
func (u *BaseProviderController) ManagementGetProviderPlatformList() {
	u.LogID = fmt.Sprintf("ManagementGetProviderPlatformList[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetProviderPlatformListReq{}
		mreq.PageSize = req.PageSize
		mreq.PageNumber = req.PageNumber
		mreq.Search = req.Search
		mreq.IsAll = req.IsAll
		mreq.ProviderApiId = req.ProviderApiId
		mreply, err := rpc_apis.Management.ManagementGetProviderPlatformList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetProviderPlatformList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetProviderPlatformListResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = mreply
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

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

// @Title 三方平台api添加
// @Description 三方平台api添加
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   body    body   rpc_apis.gd_management.ManagementAddProviderApiReq true "参数"
// @Success 200 	{object} params.param_v1_0.ManagementAddProviderApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform_api [post]
func (u *BaseProviderController) ManagementAddProviderApi() {
	u.LogID = fmt.Sprintf("ManagementAddProviderApi[%d]", time.Now().UnixNano())

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

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

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

// @Title 三方平台API删除
// @Description 三方平台API删除
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   provider_api_id    query   int64 true "三方api id"
// @Success 200 	{object} params.param_v1_0.ManagementDelProviderApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform_api [delete]
func (u *BaseProviderController) ManagementDelProviderApi() {
	u.LogID = fmt.Sprintf("ManagementDelProviderApi[%d]", time.Now().UnixNano())

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

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

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

// @Title 三方平台API更新
// @Description 三方平台API更新
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   body    body   rpc_apis.gd_management.ManagementUpdateProviderApiReq true "参数"
// @Success 200 	{object} params.param_v1_0.ManagementUpdateProviderApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform_api [put]
func (u *BaseProviderController) ManagementUpdateProviderApi() {
	u.LogID = fmt.Sprintf("ManagementUpdateProviderApi[%d]", time.Now().UnixNano())

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

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

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

// @Title 三方平台API列表
// @Description 三方平台API列表
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   page_size    query   int false "页大小"
// @Param   is_all       query   bool false ""
// @Param   page_number    query   int false "页数"
// @Param   provider_id    query   int64 true "平台id"
// @Success 200 	{object} params.param_v1_0.ManagementGetProviderApiListResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_platform_api [get]
func (u *BaseProviderController) ManagementGetProviderApiList() {
	u.LogID = fmt.Sprintf("ManagementGetProviderApiList[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetProviderApiListReq{}
		mreq.PageNumber = req.PageNumber
		mreq.PageSize = req.PageSize
		mreq.ProviderId = req.ProviderId
		mreq.IsAll = req.IsAll
		mreply, err := rpc_apis.Management.ManagementGetProviderApiList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetProviderApiList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetProviderApiListResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = mreply
		httper.JSON(u.Ctx, resp, u.LogID)
		return nil
	}

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

// @Title 获取所有三方平台API
// @Description 获取所有三方平台API
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   provider_id    query   int64 false "provider id"
// @Success 200 	{object}  params.param_v1_0.ManagementGetAllProviderApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_all_platform_api [get]
func (u *BaseProviderController) ManagementGetAllProviderApi() {
	u.LogID = fmt.Sprintf("ManagementGetProviderApi[%d]", time.Now().UnixNano())

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

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

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

// @Title 数据源调用
// @Description 数据源调用
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param	api_name    	formData	string	true 		"接口名称"
// @Param	provider_api_id    	formData	int	true 		"接口id"
// @Param	thirdparty_host    	formData	string	true 		"请求地址"
// @Param	thirdparty_router    	formData	string	true 		"请求路由"
// @Param	platform_code    	formData	string	true 		"平台码"
// @Success 200 	{object}  params.param_v1_0.ManagementTryProviderApiResp "响应信息"
// @Failure 500 	服务器错误
// @router /try [post]
func (u *BaseProviderController) ManagementTryProviderApi() {
	u.LogID = fmt.Sprintf("ManagementGetProviderApi[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		f, h, err := u.GetFile("file") //获取上传的文件
		defer f.Close()

		if err != nil || h.Size <= 0 {
			return errors.FileErr
		}
		if h.Size > consts.FileMaxSize {
			return errors.FileSizeErr
		}

		ext := path.Ext(h.Filename)

		//验证后缀名是否符合要求
		AllowExtMap := map[string]bool{
			".xlsx": true,
		}
		if _, ok := AllowExtMap[ext]; !ok {
			return errors.ExtErr
		}

		//创建目录
		uploadDir := "static/upload/try_provider_api/" + time.Now().Format("2006/01/02/")
		err = os.MkdirAll(uploadDir, 0777)
		if err != nil {
			return errors.SystemError
		}
		//创建权限
		os.Chmod("static/upload/", 0777)
		os.Chmod("static/upload/try_provider_api", 0777)
		os.Chmod("static/upload/try_provider_api/"+time.Now().Format("2006"), 0777)
		os.Chmod("static/upload/try_provider_api/"+time.Now().Format("2006/01"), 0777)
		os.Chmod("static/upload/try_provider_api/"+time.Now().Format("2006/01/02/"), 0777)

		fpath := uploadDir + h.Filename
		err = u.SaveToFile("file", fpath)
		if err != nil {
			return errors.SystemError
		}

		// 创建一个任务
		taskReq := gd_management.TryApiTaskAddReq{
			Type:      2,
			FileName:  h.Filename,
			ApiName:   req.ApiName,
			ApiHost:   req.ThirdPartyHost,
			ApiRouter: req.ThirdPartyRouter,
			Status:    0,
		}

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

		// 读取xlsx内数据
		var (
			data = make([]map[string]string, 0)

			rowResult = make([]string, 0)
		)

		excelFile, _ := xlsx.OpenFile(fpath)
		for _, sheet := range excelFile.Sheets {
			for i, row := range sheet.Rows {
				rowMap := make(map[string]string, 0)
				if i == 0 {
					//表头
					for _, cell := range row.Cells {
						rowResult = append(rowResult, cell.Value)
						if _, ok := rowMap[cell.Value]; !ok {
							rowMap[cell.Value] = ""
						}
					}
				} else {
					for k, cell := range row.Cells {
						if strings.TrimSpace(cell.Value) == "" {
							continue
						}
						key := rowResult[k]
						rowMap[key] = strings.TrimSpace(cell.Value)
					}
					data = append(data, rowMap)
				}
			}
		}

		//异步请求微服务调用数据源
		go func() {
			var (
				status      int
				downloadDir string
				dpath       string
				tail        string
			)
			req := gd_management.ProviderBatchRequestReq{
				ApiId:            req.ProviderApiId,
				ApiName:          req.ApiName,
				ThirdPartyHost:   req.ThirdPartyHost,
				ThirdPartyRouter: req.ThirdPartyRouter,
				PlatformCode:     req.PlatformCode,
			}

			for _, v := range data {
				s, _ := json.Marshal(v)
				req.Param = append(req.Param, string(s))
			}

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

				status = -1
			} else {
				var (
					sheet *xlsx.Sheet
					row   *xlsx.Row
					cell  *xlsx.Cell
				)

				file := xlsx.NewFile()
				sheet, _ = file.AddSheet("Sheet1")

				//成功写入一个xlsx
				for k, v := range reply.List {
					if k == 0 {
						//写入表头
						row = sheet.AddRow()
						for _, i := range rowResult {
							cell = row.AddCell()
							cell.Value = i
						}
						cell = row.AddCell()
						cell.Value = "response"
					}
					row = sheet.AddRow()
					for _, i := range rowResult {
						cell = row.AddCell()
						cell.Value = gjson.GetBytes([]byte(v.Param), i).String()
					}
					cell = row.AddCell()
					cell.Value = v.Response
				}

				downloadDir = "static/download/try_provider_api/" + time.Now().Format("2006/01/02/")
				err = os.MkdirAll(downloadDir, 0777)
				if err != nil {
					status = -1
				} else {
					//创建权限
					os.Chmod("static/download/", 0777)
					os.Chmod("static/download/try_provider_api", 0777)
					os.Chmod("static/download/try_provider_api/"+time.Now().Format("2006"), 0777)
					os.Chmod("static/download/try_provider_api/"+time.Now().Format("2006/01"), 0777)
					os.Chmod("static/download/try_provider_api/"+time.Now().Format("2006/01/02/"), 0777)

					tail = "task-" + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
					dpath = downloadDir + tail
					file.Save(dpath)
					if true {
						utils.OssUploadFile(dpath, tail)
					}
					status = 1
				}
			}
			host := ""
			if strings.Contains(ServerIp, "0.0.0.0") == false {
				host = "http://" + ServerIp + ":" + ServerPort
			} else if strings.Contains(u.Ctx.Request.Host, ":") == false {
				host = u.Ctx.Request.URL.Scheme + u.Ctx.Request.Host
			}

			//根据task_id修改task状态
			taskReq := gd_management.TryApiTaskUpdateReq{
				Id:           taskReply.Id,
				Status:       status,
				DownloadFile: host + "/" + dpath,
			}
			if true {
				taskReq.DownloadFile = getOssFileUrl(tail)
			}

			_, err = rpc_apis.Management.TryApiTaskUpdate(utils.NewContextFromBeegoCtx(u.Ctx), &taskReq)
			if err != nil {
				l.Error("rpc",
					zap.String("call", "TryApiTaskUpdate"),
					zap.String("args", utils.MarshalJsonString(req)),
					zap.String("error", err.Error()))
				return
			}
		}()

		resp := param_v1_0.ManagementTryProviderApiResp{
			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 获取数据查询任务信息列表
// @Description 获取数据查询任务信息列表
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   type    query   int64 true "类型"
// @Param   page_size    query   int64 false "页大小"
// @Param   page_number    query   int64 false "页号"
// @Success 200 	{object}  params.param_v1_0.TryApiTaskListResp "响应信息"
// @Failure 500 	服务器错误
// @router /try_api_task [get]
func (u *BaseProviderController) TryApiTaskList() {
	u.LogID = fmt.Sprintf("TryApiTaskList[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.GetTryApiTaskListReq{
			Type:       req.Type,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		}
		mreply, err := rpc_apis.Management.GetTryApiTaskList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetTryApiTaskList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.TryApiTaskListResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
			Data: gd_management.GetTryApiTaskListReply{
				PageNumber: 0,
				Total:      0,
				PageSize:   0,
				List:       make([]gd_management.GetTryApiTaskList, 0),
			},
		}

		resp.Data = mreply
		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 base api waring threshold
// @Description 设置数据源告警阀值
// @Param   token    header   string true "token"
// @Param   uid    header   string true "uid"
// @Param   provider_api_id  path int64 true ""
// @Param   body  body param_v1_0.ManagementSetProviderThresholdBody true ""
// @Success 200 	{object} params.param_v1_0.ManagementSetProviderThresholdResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_threshold/:provider_api_id [put]
func (u *BaseProviderController) ManagementSetProviderThreshold() {
	u.LogID = fmt.Sprintf("ManagementSetProviderThreshold[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.ManagementSetProviderThresholdReq{}
		mreq.ProviderApiId = req.ProviderApiId
		mreq.ThresholdFailRate = req.Body.ThresholdFailRate
		mreq.ThresholdNorecordRate = req.Body.ThresholdNorecordRate
		mreq.ThresholdTimeout = req.Body.ThresholdTimeout
		mreq.WarningEnable = req.Body.WarningEnable

		_, err := rpc_apis.Management.ManagementSetProviderThreshold(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementSetProviderThreshold"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementSetProviderThresholdResp{
			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 provider merchant api list
// @Description 数据源关联的商户api列表
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   provider_api_id    query   int64 true "平台id"
// @Success 200 	{object} params.param_v1_0.ManagementGetProviderMerchantApiListResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_merchant_api [get]
func (u *BaseProviderController) ManagementGetProviderMerchantApiList() {
	u.LogID = fmt.Sprintf("ManagementGetProviderApiList[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetProviderMerchantApiListReq{}
		mreq.ProviderApiId = req.ProviderApiId
		mreply, err := rpc_apis.Management.ManagementGetProviderMerchantApiList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetProviderApiList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetProviderMerchantApiListResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.ProviderMerchantApiList = mreply.ProviderMerchantApiList
		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 provider api hystrix
// @Description 数据源熔断信息
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   provider_api_code    query   string true "平台code"
// @Success 200 	{object} params.param_v1_0.GetProviderApiHystrixResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_api_hystrix [get]
func (u *BaseProviderController) Hystrix() {
	u.LogID = fmt.Sprintf("Hystrix[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.GetProviderApiHystrixReq{
			ProviderApiCode: req.ProviderApiCode,
		}
		mreply, err := rpc_apis.Management.GetProviderApiHystrix(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "GetProviderApiHystrix"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.GetProviderApiHystrixResp{
			SimpleResp: param_base.SimpleResp{
				Code: 0,
				Msg:  "SUCCESS",
			},
		}
		resp.Data = mreply
		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 provider api hystrix
// @Description 数据源熔断信息
// @Param   token    header   string true "token"
// @Param   uid    header   int64 true "admin id"
// @Param   body     body   params.param_v1_0.UpdateProviderApiHystrixBody true "参数"
// @Success 200 	{object} params.param_v1_0.UpdateProviderApiHystrixResp "响应信息"
// @Failure 500 	服务器错误
// @router /provider_api_hystrix [put]
func (u *BaseProviderController) UpdateHystrix() {
	u.LogID = fmt.Sprintf("Hystrix[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.UpdateProviderApiHystrixReq{
			ID                     :req.Body.ID,
			ProviderApiName        :req.Body.ProviderApiName,
			ProviderApiCode        :req.Body.ProviderApiCode,
			MaxConcurrentRequests  :req.Body.MaxConcurrentRequests,
			RequestVolumeThreshold :req.Body.RequestVolumeThreshold,
			SleepWindow            :req.Body.SleepWindow,
			ErrorPercentThreshold  :req.Body.ErrorPercentThreshold,
			Period                 :req.Body.Period,
			IsOn                   :req.Body.IsOn,
		}
		_, err := rpc_apis.Management.UpdateProviderApiHystrix(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "UpdateProviderApiHystrix"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.UpdateProviderApiHystrixResp{
			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,
	)
}
