package services

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

func GetChartPermissionList() (list []*models.ChartPermission, err error) {
	var req GetChartPermissionReq
	data, err := getChartPermission(req)
	if err != nil {
		return
	}
	list = data.List
	return
}

type GetChartPermissionReq struct {
	ChartPermissionId int `json:"chart_permission_id"`
	ProductId         int `json:"product_id"`
}
type GetChartPermissionItem struct {
	List       []*models.ChartPermission
	ParentList []*models.ChartPermission
}
type GetChartPermissionResp struct {
	Code   int                    `json:"code" description:"状态码"`
	Msg    string                 `json:"msg" description:"提示信息"`
	Data   GetChartPermissionItem `json:"data" description:"返回数据"`
	ErrMsg string                 `json:"-" description:"错误信息，不用返回给前端，只是做日志记录"`
}

func getChartPermission(pars GetChartPermissionReq) (res GetChartPermissionItem, err error) {
	if utils.CrmEtaServerUrl == "" {
		return
	}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/list")
	if pars.ProductId == 0 {
		pars.ProductId = 1 //默认查ficc的品种
	}
	b, err := crmEtaPost(url, pars)
	if err != nil {
		err = fmt.Errorf("url:%s err: %s", url, err.Error())
		return
	}
	//result := new(models.ResultData)
	result := new(GetChartPermissionResp)
	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
	}
	res = result.Data
	return
}

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

type ChartPermissionAddReq struct {
	PermissionName string `description:"品种权限名称"`
	ParentId       int    `description:"父级ID"`
	Enabled        int    `description:"是否可用 0禁用， 1启用"` //启用，禁用操作会关联二级品种
	IsPublic       int    `description:"是否是公有权限1:公有权限，0私有权限"`
	ProductId      int
}

type ChartPermissionEditReq struct {
	ChartPermissionId   int    `description:"品种权限Id"` // 如果ID存在，则是更新操作，否则是新增操作
	PermissionName      string `description:"品种权限名称"`
	Enabled             int    `description:"是否可用 0禁用， 1启用"` //启用，禁用操作会关联二级品种
	IsPublic            int    `description:"是否是公有权限1:公有权限，0私有权限"`
	PublicPermissionIds []int  `description:"公有权限的ID列表"` //一级品种没有公有私有属性
}

type ChartPermissionMoveReq struct {
	ChartPermissionId int `description:"品种id"`
	//	ParentChartPermissionId int `description:"父级品种id"`
	PrevChartPermissionId int `description:"上一个兄弟节点品种id"`
	NextChartPermissionId int `description:"下一个兄弟节点品种id"`
}

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 AddChartPermission(pars *ChartPermissionAddReq) (err error, errMsg string) {
	if utils.CrmEtaServerUrl == "" {
		return
	}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/add")
	if pars.ProductId == 0 {
		pars.ProductId = 1 //默认新增ficc的品种
	}
	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
}

func EditChartPermission(pars *ChartPermissionEditReq) (err error, errMsg string) {
	if utils.CrmEtaServerUrl == "" {
		return
	}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/edit")
	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
}

func MoveChartPermission(pars *ChartPermissionMoveReq) (err error, errMsg string) {
	if utils.CrmEtaServerUrl == "" {
		return
	}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/move")
	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
}

// GetChartPermissionEnabledList 查询已启用的FICC权限列表
func GetChartPermissionEnabledList() (list []*company.PermissionSetList, err error) {
	var req GetChartPermissionReq
	data, err := getChartPermission(req)
	if err != nil {
		return
	}
	dataList := data.List
	//enabledList := make([]*models.ChartPermission, 0)
	parentList := make([]*models.ChartPermission, 0)
	enabledMap := make(map[int][]*company.PermissionSetItem)
	listMap := make(map[int]*models.ChartPermission)
	for _, v := range dataList {
		listMap[v.ChartPermissionId] = v
		if v.ParentId == 0 {
			parentList = append(parentList, v)
		}
		if v.Enabled == 1 && v.ParentId > 0 && v.PermissionType == 0 {
			//enabledList = append(enabledList, v)
			item := &company.PermissionSetItem{
				ChartPermissionId: v.ChartPermissionId,
				PermissionName:    v.PermissionName,
				PermissionType:    v.PermissionType,
			}

			enabledMap[v.ParentId] = append(enabledMap[v.ParentId], item)
		}
	}
	for _, v := range parentList {
		items, ok := enabledMap[v.ChartPermissionId]
		if !ok {
			continue
		}
		checkList := make([]int, 0)
		p := new(company.PermissionSetList)
		p.ClassifyName = v.PermissionName
		p.Items = items
		if v.PermissionName == "宏观经济" {
			checkList = append(checkList, 1)
		}
		p.CheckList = checkList
		list = append(list, p)
	}
	return
}

type EditClassifyPermissionReq struct {
	Keyword               string
	ChartPermissionIdList []int `description:"权限id数组"`
	NewKeyword            string
}

// GetClassifyChartPermission 获取报告分类已绑定的权限
func GetClassifyChartPermission(classifyName string) (list []*models.ChartPermissionSearchKeyWordMapping, err error) {
	if utils.CrmEtaServerUrl == "" {
		return
	}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/classify")
	var req ClassifyPermissionReq
	req.Keyword = classifyName
	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(GetClassifyChartPermissionResp)
	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
	}
	list = result.Data.List
	return
}

type ClassifyPermissionReq struct {
	Keyword string
}

type ClassifyPermissionList struct {
	List []*models.ChartPermissionSearchKeyWordMapping
}

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

// EditClassifyChartPermission 设置报告分类权限
func EditClassifyChartPermission(req EditClassifyPermissionReq) (err error) {
	if utils.CrmEtaServerUrl == "" {
		return
	}
	url := fmt.Sprint(utils.CrmEtaServerUrl, "/api/crm/chart_permission/classify/edit")
	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
}
