package ctrl_v1

import (
	"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"
	"encoding/json"
	"fmt"
	"strconv"
	"time"

	"gd_management_gateway/common.in/httper"
	"gd_management_gateway/common.in/task"
	"gd_management_gateway/common.in/utils"
	"go.uber.org/zap"

	"github.com/astaxie/beego"
)

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

// @Title add user merchant
// @Description 添加用户商户
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   user_merchant    body   params.param_v1_0.UserMerchantInfo true "用户商户信息"
// @Success 200 	{object} params.param_v1_0.ManagementAddUserMerchantResp "响应信息"
// @Failure 500 	服务器错误
// @router /user_merchant [post]
func (u *UserMerchantController) ManagementAddUserMerchant() {
	u.LogID = fmt.Sprintf("ManagementAddUserMerchant[%d]", time.Now().UnixNano())

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

	handleDataTask := func() error {
		mreq := gd_management.ManagementAddUserMerchantReq{
			UserInfo:     req.UserMerchant.UserInfo,
			MerchantInfo: req.UserMerchant.MerchantInfo,
		}

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

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

	AddActionLogTask := func() error {
		// 记录用户行为日志
		go func() {
			bytes, err := json.Marshal(req.UserMerchant)
			if err != nil {
				return
			}

			areq := gd_admin.AddActionLogReq{
				Uid:        req.Uid,
				Name:       req.UserMerchant.UserInfo.Name,
				Modules:    "用户列表",
				Func:       "添加用户",
				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 update user merchant
// @Description 修改用户商户
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   merchant_id    query   string true "商户id"
// @Param   user_merchant    body   params.param_v1_0.UserMerchantInfo true "用户商户信息"
// @Success 200 	{object} params.param_v1_0.ManagementUpdateUserMerchantResp "响应信息"
// @Failure 500 	服务器错误
// @router /user_merchant [put]
func (u *UserMerchantController) ManagementUpdateUserMerchant() {
	u.LogID = fmt.Sprintf("ManagementUpdateUserMerchant[%d]", time.Now().UnixNano())

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

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

		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()))
			return errors.DataBaseError
		}

		bytes, _ := json.Marshal(req.UserMerchant)
		beforeBytes, _ := json.Marshal(reply)

		treq := gd_admin.AddActionLogReq{
			Uid:        req.Uid,
			Name:       req.UserMerchant.UserInfo.Name,
			Modules:    "用户列表",
			Func:       "修改商户信息",
			Before:     string(beforeBytes),
			Content:    string(bytes),
			ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		}

		err = AddActionLog(treq)
		if err != nil {
			return err
		}

		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementUpdateUserMerchantReq{}
		mreq.UserInfo = req.UserMerchant.UserInfo
		mreq.MerchantInfo = req.UserMerchant.MerchantInfo
		mreq.MerchantId = req.MerchantId

		_, err := rpc_apis.Management.ManagementUpdateUserMerchant(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementUpdateUserMerchant"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementUpdateUserMerchantResp{
			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 user merchant list
// @Description 获取用户商户列表
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   page_number    query   int false "当前页"
// @Param   is_all    query   bool false "当前页"
// @Param   api_ids    query   string false "base api ids"
// @Param   data_api_id    query   int64 false "data api id"
// @Success 200 	{object} params.param_v1_0.ManagementGetUserMerchantListResp "响应信息"
// @Failure 500 	服务器错误
// @router /user_merchant_list [get]
func (u *UserMerchantController) ManagementGetUserMerchantList() {
	u.LogID = fmt.Sprintf("ManagementGetUserMerchantList[%d]", time.Now().UnixNano())
	req := &param_v1_0.ManagementGetUserMerchantListReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetUserMerchantListReq{}
		mreq.PageNumber = req.PageNumber
		mreq.IsAll = req.IsAll
		mreq.ApiIds = req.ApiIds
		mreq.DataApiId = req.DataApiId
		reply, err := rpc_apis.Management.ManagementGetUserMerchantList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetUserMerchantList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetUserMerchantListResp{
			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 user merchant list new interface
// @Description 获取用户商户列表(新)
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   page_number    query   int false "当前页"
// @Param   is_all    query   bool false "是否获取全部"
// @Param   search    query   string false "搜索字符串"
// @Param   merchant_id    query   int64 false "商户id"
// @Param   data_api_id query string fasle "搜索产品"
// @Param   status_code query int fasle "产品状态"
// @Param   merchant_type query int fasle "商户类型"
// @Success 200 	{object} params.param_v1_0.ManagementGetUserMerchantListNewResp "响应信息"
// @Failure 500 	服务器错误
// @router /user_merchant_list_new [get]
func (u *UserMerchantController) ManagementGetUserMerchantListNew() {
	u.LogID = fmt.Sprintf("ManagementGetUserMerchantListNew[%d]", time.Now().UnixNano())
	req := &param_v1_0.ManagementGetUserMerchantListNewReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetUserMerchantListNewReq{}
		mreq.PageNumber = req.PageNumber
		mreq.IsAll = req.IsAll
		mreq.Search = req.Search
		mreq.DataApiId = req.DataApiId
		mreq.StatusCode = req.StatusCode
		mreq.MerchantId = req.MerchantId
		mreq.MerchantType = req.MerchantType
		reply, err := rpc_apis.Management.ManagementGetUserMerchantListNew(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetUserMerchantListNew"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetUserMerchantListNewResp{
			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 auth state
// @Description 设置认证状态
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param	body	body	params.param_v1_0.ManagementSetUserMerchantAuthStateBody	true	""
// @Success 200 	{object} params.param_v1_0.ManagementSetUserMerchantAuthStateResp "响应信息"
// @Failure 500 	服务器错误
// @router /user_merchant_auth_state [put]
func (u *UserMerchantController) ManagementSetUserMerchantAuthState() {
	u.LogID = fmt.Sprintf("ManagementSetUserMerchantAuthState[%d]", time.Now().UnixNano())

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

	// 记录用户行为日志
	AddActionLogTask := func() error {
		// 获取商户信息
		rreq := gd_management.GetMerchantInfoReq{
			Id: int64(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()))
			return errors.DataBaseError
		}

		areq := gd_admin.AddActionLogReq{
			Uid:        req.Uid,
			Name:       reply.MerchantName,
			Modules:    "用户管理",
			Func:       "设置认证状态",
			Before:     `{"auth_status":` + strconv.Itoa(reply.AuthStatus) + `}`,
			Content:    `{"auth_status"` + strconv.Itoa(req.Body.State) + `}`,
			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.ManagementSetUserMerchantAuthStateReq{
			MerchantId: req.Body.MerchantId,
			State:      req.Body.State,
		}

		_, err := rpc_apis.Management.ManagementSetUserMerchantAuthState(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementSetUserMerchantAuthState"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementSetUserMerchantAuthStateResp{
			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 获取待授权商户列表
// @Description 获取待授权商户列表
// @Param   token    header   string true "token"
// @Param   uid    header   string true "管理员id"
// @Param   page_number    query   int false "当前页"
// @Param   phone    query   string false "手机号"
// @Param   merchant_name    query   string false "商户名"
// @Param   merchant_id    query   int64 false "商户id"
// @Param   start_time query string fasle "开始时间"
// @Param   end_time query string fasle "结束时间"
// @Success 200 	{object} params.param_v1_0.ManagementGetUserMerchantAuthListResp "响应信息"
// @Failure 500 	服务器错误
// @router /user_merchant_auth_list [get]
func (u *UserMerchantController) ManagementGetUserMerchantAuthList() {
	u.LogID = fmt.Sprintf("ManagementGetUserMerchantAuthList[%d]", time.Now().UnixNano())
	req := &param_v1_0.ManagementGetUserMerchantAuthListReq{}
	getParamsTask := func() error {
		httper.FillRequireParams(u.Ctx, req, u.LogID)
		return nil
	}

	handleDataTask := func() error {
		mreq := gd_management.ManagementGetUserMerchantAuthListNewReq{}
		mreq.PageNumber = req.PageNumber
		mreq.MerchantId = req.MerchantId
		mreq.MerchantName = req.MerchantName
		mreq.Phone = req.Phone
		mreq.StartTime = req.StartTime
		mreq.EndTime = req.EndTime
		reply, err := rpc_apis.Management.ManagementGetUserMerchantAuthList(utils.NewContextFromBeegoCtx(u.Ctx), &mreq)
		if err != nil {
			l.Error("rpc",
				zap.String("call", "ManagementGetUserMerchantAuthList"),
				zap.String("args", utils.MarshalJsonString(req)),
				zap.String("error", err.Error()))
			return errors.ErrorTransform(err)
		}
		resp := param_v1_0.ManagementGetUserMerchantAuthListResp{
			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,
	)
}
