package services

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

type ChartPermissionResp struct {
	Code   int    `json:"code" description:"状态码"`
	Msg    string `json:"msg" description:"提示信息"`
	ErrMsg string `json:"-" description:"错误信息，不用返回给前端，只是做日志记录"`
}

func crmEtaPost(url string, pars interface{}) (respBody []byte, err error) {
	params, e := json.Marshal(pars)
	if e != nil {
		err = fmt.Errorf("data json marshal err: %s", e.Error())
		return
	}

	body := ioutil.NopCloser(strings.NewReader(string(params)))
	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), utils.CrmEtaServerDes3Key)
	}
	respBody = b
	return
}

func ChartFiccPermissionSync() (err error, errMsg string) {
	defer func() {
		if err != nil {
			utils.FileLog.Info("同步品种权限数据失败, Err: " + err.Error() + errMsg)
			alarm_msg.SendAlarmMsg("同步品种权限数据失败，Err："+err.Error(), 3)
		}
	}()
	if utils.CrmEtaServerUrl == "" {
		return
	}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/sync")
	pars := make(map[string]interface{})
	b, err := crmEtaPost(url, pars)
	if err != nil {
		errMsg = "同步品种失败"
		err = fmt.Errorf("url:%s err: %s", url, err.Error())
		return
	}
	//result := new(models.ResultData)
	result := new(ChartPermissionResp)
	if e := json.Unmarshal(b, &result); e != nil {
		errMsg = "同步品种失败"
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	utils.FileLog.Info("%s", string(b))
	if result.Code != 200 {
		err = fmt.Errorf("result: %s, err: %s", string(b), result.ErrMsg)
		errMsg = result.Msg
		return
	}
	return
}

type EditClassifyPermissionReq struct {
	Keyword    string
	ClassifyId int
}

// EditClassifyChartPermissionSync 设置报告分类权限
func EditClassifyChartPermissionSync(keyword string, classifyId int) (err error) {
	defer func() {
		if err != nil {
			utils.FileLog.Info("同步设置报告分类权限失败, Err: " + err.Error())
			alarm_msg.SendAlarmMsg("同步设置报告分类权限失败，Err："+err.Error(), 3)
		}
	}()
	if utils.CrmEtaServerUrl == "" {
		return
	}
	req := &EditClassifyPermissionReq{Keyword: keyword, ClassifyId: classifyId}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/classify/sync")
	b, err := crmEtaPost(url, req)
	if err != nil {
		err = fmt.Errorf("url:%s err: %s", url, err.Error())
		return
	}
	//result := new(models.ResultData)
	result := new(ChartPermissionResp)
	if e := json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	utils.FileLog.Info("%s", string(b))
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	return
}

type EditReportPermissionSyncReq struct {
	ReportId           int64  `description:"报告id"`
	ClassifyNameSecond string `description:"二级分类名称"`
	ClassifyIdSecond   int    `description:"二级分类ID"`
}

// EditReportPermissionSync 设置报告权限
func EditReportPermissionSync(reportId int64, classifyIdSecond int) (err error) {
	defer func() {
		if err != nil {
			utils.FileLog.Info("同步设置报告权限失败, Err: " + err.Error())
			alarm_msg.SendAlarmMsg("同步设置报告权限失败，Err："+err.Error(), 3)
		}
	}()
	if utils.CrmEtaServerUrl == "" {
		return
	}
	req := &EditReportPermissionSyncReq{ReportId: reportId, ClassifyIdSecond: classifyIdSecond}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/report/sync")
	b, err := crmEtaPost(url, req)
	if err != nil {
		err = fmt.Errorf("url:%s err: %s", url, err.Error())
		return
	}
	//result := new(models.ResultData)
	result := new(ChartPermissionResp)
	if e := json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	utils.FileLog.Info("%s", string(b))
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	return
}

type EditKeywordPermissionSyncReq struct {
	NewKeyword string
	ClassifyId int
}

// EditKeywordPermissionSync 设置报告权限分类名称
func EditKeywordPermissionSync(newKeyword string, classifyId int) (err error) {
	defer func() {
		if err != nil {
			utils.FileLog.Info("同步设置报告权限分类名称失败, Err: " + err.Error())
			alarm_msg.SendAlarmMsg("同步设置报告权限分类名称失败，Err："+err.Error(), 3)
		}
	}()
	if utils.CrmEtaServerUrl == "" {
		return
	}
	req := &EditKeywordPermissionSyncReq{NewKeyword: newKeyword, ClassifyId: classifyId}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/keyword/sync")
	b, err := crmEtaPost(url, req)
	if err != nil {
		err = fmt.Errorf("url:%s err: %s", url, err.Error())
		return
	}
	//result := new(models.ResultData)
	result := new(ChartPermissionResp)
	if e := json.Unmarshal(b, &result); e != nil {
		err = fmt.Errorf("result unmarshal err: %s\nresult: %s", e.Error(), string(b))
		return
	}
	utils.FileLog.Info("%s", string(b))
	if result.Code != 200 {
		err = fmt.Errorf("result: %s", string(b))
		return
	}
	return
}
