package services

import (
	"encoding/json"
	"fmt"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"io/ioutil"
	"net/http"
	"strings"
)

const (
	LoginAuthCodeSource = 1
)

// MiddleServerResultData 中间服务响应体
type MiddleServerResultData struct {
	Code   int         `json:"code" description:"状态码"`
	Msg    string      `json:"msg" description:"提示信息"`
	Data   interface{} `json:"data" description:"返回数据"`
	ErrMsg string      `json:"-" description:"错误信息，不用返回给前端，只是做日志记录"`
}

// GetLoginAuthCodeReq 获取登录编码请求体
type GetLoginAuthCodeReq struct {
	AdminName string `json:"admin_name" description:"用户名"`
	Source    int    `json:"source" description:"来源: 1-CRM; 2-ETA"`
}

// GetAuthCodeFromMiddleServer CRM_ETA服务-获取登录编码
func GetAuthCodeFromMiddleServer(adminName string) (authCode string, err error) {
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/auth/auth_code")
	param := GetLoginAuthCodeReq{
		Source:    LoginAuthCodeSource,
		AdminName: adminName,
	}
	data, e := json.Marshal(param)
	if e != nil {
		err = fmt.Errorf("data json marshal err: %s", e.Error())
		return
	}

	body := ioutil.NopCloser(strings.NewReader(string(data)))
	client := &http.Client{}
	req, e := http.NewRequest("POST", url, body)
	if e != nil {
		err = fmt.Errorf("http create request err: %s", e.Error())
		return
	}

	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", utils.CrmEtaAuthorization)
	resp, e := client.Do(req)
	if e != nil {
		err = fmt.Errorf("http client do err: %s", e.Error())
		return
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	b, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		err = fmt.Errorf("resp body read err: %s", e.Error())
		return
	}
	if len(b) == 0 {
		err = fmt.Errorf("resp body is empty")
		return
	}
	// 生产环境解密, 注意有个坑前后的双引号
	if utils.RunMode == "release" {
		str := string(b)
		str = strings.Trim(str, `"`)
		b = utils.DesBase64Decrypt([]byte(str))
	}

	result := new(MiddleServerResultData)
	if e = json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}

	code, ok := result.Data.(string)
	if !ok {
		err = fmt.Errorf("auth code empty")
		return
	}
	authCode = code
	return
}

// GetEtaTokenReq 获取Token请求体
type GetEtaTokenReq struct {
	AuthCode string `json:"auth_code"`
}

// GetEtaTokenDataResp 获取Token信息响应体
type GetEtaTokenDataResp struct {
	Code int             `json:"code" description:"状态码"`
	Msg  string          `json:"msg" description:"提示信息"`
	Data GetEtaTokenData `json:"data" description:"返回数据"`
}

// GetEtaTokenData Token数据
type GetEtaTokenData struct {
	Authorization   string `description:"Auth Token"`
	AdminName       string `description:"系统用户名称"`
	RealName        string `description:"系统用户姓名"`
	RoleName        string `description:"角色名称"`
	RoleTypeCode    string `description:"角色类型编码"`
	SysRoleTypeCode string `description:"角色类型编码"`
	AdminId         int    `description:"系统用户id"`
	ProductName     string `description:"产品名称：admin,ficc,权益"`
	Authority       int    `description:"管理权限，0：无，1：部门负责人，2：小组负责人,或者ficc销售主管，4:ficc销售组长"`
}

// CodeLoginFromMiddleServer 中间服务-编码登录
func CodeLoginFromMiddleServer(authCode string) (tokenResp GetEtaTokenData, err error) {
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/auth/crm_token")
	param := GetEtaTokenReq{
		AuthCode: authCode,
	}
	data, e := json.Marshal(param)
	if e != nil {
		err = fmt.Errorf("data json marshal err: %s", e.Error())
		return
	}

	body := ioutil.NopCloser(strings.NewReader(string(data)))
	client := &http.Client{}
	req, e := http.NewRequest("POST", url, body)
	if e != nil {
		err = fmt.Errorf("http create request err: %s", e.Error())
		return
	}

	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", utils.CrmEtaAuthorization)
	resp, e := client.Do(req)
	if e != nil {
		err = fmt.Errorf("http client do err: %s", e.Error())
		return
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	b, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		err = fmt.Errorf("resp body read err: %s", e.Error())
		return
	}
	if len(b) == 0 {
		err = fmt.Errorf("resp body is empty")
		return
	}
	// 生产环境解密, 注意有个坑前后的双引号
	if utils.RunMode == "release" {
		str := string(b)
		str = strings.Trim(str, `"`)
		b = utils.DesBase64Decrypt([]byte(str))
	}

	result := new(GetEtaTokenDataResp)
	if e = json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	tokenResp = result.Data
	return
}

// EtaTrialManualUserAddAuthReq 体验版用户添加手工权限
type EtaTrialManualUserAddAuthReq struct {
	AdminId   int    `json:"admin_id" description:"用户ID"`
	AdminName string `json:"admin_name" description:"用户名"`
}

// EtaTrialManualUserAddAuth CRM_ETA服务-体验版用户添加手工权限
func EtaTrialManualUserAddAuth(adminId int, adminName string) (err error) {
	// 体验版无测试环境
	//if utils.RunMode != "release" {
	//	return
	//}
	defer func() {
		if err != nil {
			alarm_msg.SendAlarmMsg(fmt.Sprintf("EtaTrialManualUserAddAuth, 新增试用客户手工录入权限失败, ErrMsg: %s", err.Error()), 3)
		}
	}()

	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/eta_trial/manual_user/add_auth")
	param := EtaTrialManualUserAddAuthReq{
		AdminId:   adminId,
		AdminName: adminName,
	}
	data, e := json.Marshal(param)
	if e != nil {
		err = fmt.Errorf("data json marshal err: %s", e.Error())
		return
	}

	body := ioutil.NopCloser(strings.NewReader(string(data)))
	client := &http.Client{}
	req, e := http.NewRequest("POST", url, body)
	if e != nil {
		err = fmt.Errorf("http create request err: %s", e.Error())
		return
	}

	contentType := "application/json;charset=utf-8"
	req.Header.Set("Content-Type", contentType)
	req.Header.Set("Authorization", utils.CrmEtaAuthorization)
	resp, e := client.Do(req)
	if e != nil {
		err = fmt.Errorf("http client do err: %s", e.Error())
		return
	}
	defer func() {
		_ = resp.Body.Close()
	}()
	b, e := ioutil.ReadAll(resp.Body)
	if e != nil {
		err = fmt.Errorf("resp body read err: %s", e.Error())
		return
	}
	if len(b) == 0 {
		err = fmt.Errorf("resp body is empty")
		return
	}
	// 生产环境解密, 注意有个坑前后的双引号
	if utils.RunMode == "release" {
		str := string(b)
		str = strings.Trim(str, `"`)
		b = utils.DesBase64Decrypt([]byte(str))
	}

	result := new(MiddleServerResultData)
	if e = json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	return
}
