package api_proxy

import (
	"DataShare/util/gabs"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"strconv"
	"sync"
)

type CQGov struct{

}
var histance_gov *CQGov
var once_gov sync.Once
func GetInstance() *CQGov{
	once_gov.Do(func() {
		histance_gov = &CQGov{}
	})

	return histance_gov
}


//政务数据格式转换到资源数据格式
func GovDataFormatToResource(govData []byte)(map[string]interface{},[]byte,error) {

	govContainer,err := gabs.ParseJSON(govData)
	if err != nil {
		return nil,nil,err
	}
	//result obj
	resultObj1,err := govContainer.JSONPointer("/result")
	if err != nil {
		return nil,nil,errors.New(fmt.Sprintf("result field faield,err:%s", err.Error()))
	}
	if resultObj1 == nil {
		return nil,nil,errors.New("数据集是空的")
	}
	result:= resultObj1.String()
	mapResult := make(map[string]interface{},0)
	json.Unmarshal([]byte(result),&mapResult)

	//组装columns
	mapColumns := make([]map[string]interface{},0)
	children := govContainer.S("field").Children()
	for i:=0;i<len(children);i++ {
		child := children[i]
		column := make(map[string]interface{},0)
		field,_ := child.Search("name").Data().(string)
		isSearch,_ := child.Search("isSearch").Data().(string)
		isDisplay,_ := child.Search("isDisplay").Data().(string)
		name,_ := child.Search("remarks").Data().(string)
		column["field"] = field
		column["isSearch"] = isSearch
		column["isDisplay"] = isDisplay
		column["name"] = name
		mapColumns = append(mapColumns,column)
	}

	mapRet := make(map[string]interface{},0)

	code,_ := strconv.Atoi(mapResult["code"].(string))

	mapRet["code"] = code
	mapRet["page"] = mapResult["pageNo"]
	mapRet["size"] = mapResult["pageSize"]
	mapRet["total"] = mapResult["total"]
	mapRet["message"] = mapResult["message"]
	mapRet["columns"] = mapColumns
	mapRet["data"] = mapResult["result"]

	byteData,err := json.Marshal(&mapRet)
	return mapRet,byteData,err
}

func GovFormatTest() (string,error) {
	dir,err := os.Getwd()
	if err != nil {
		return "",err
	}
	info_body, err := os.ReadFile(dir+"/service_test.json")
	if err != nil {
		return "",err
	}

	_,data,err := GovDataFormatToResource(info_body)

	return string(data),err
}