package controllers

import (
	"encoding/json"
	"fmt"
	"git.rosy.net.cn/jx-callback/business/model"
	"github.com/astaxie/beego/server/web"
	"io/ioutil"
	"os"
	"regexp"
)

type KnowUploadController struct {
	web.Controller
}

func (ue *KnowUploadController) SnsUploadImg() {
	//callResult := &CallResult{}
	//var files []*multipart.FileHeader
	//if c.Ctx.Request.MultipartForm != nil {
	//	if c.Ctx.Request.MultipartForm.File != nil {
	//		if len(c.Ctx.Request.MultipartForm.File) > 0 {
	//			files = c.Ctx.Request.MultipartForm.File["userfiles"]
	//		}
	//	}
	//}
	//isThumb, _ := c.GetBool("isThumb")
	//callResult.Code = model.ErrCodeGeneralFailed
	//callResult.Desc = "请上传正确文件！"
	//if len(files) > 0 {
	//	if retVal, err := knowledge.SNSUploadImg(nil, files, isThumb); err == nil {
	//		data, _ := json.Marshal(retVal)
	//		callResult.Data = string(data)
	//		callResult.Code = model.ErrCodeSuccess
	//	}
	//}
	//c.Data["jsonp"] = callResult
	//c.ServeJSONP()
	err := ue.Ctx.Request.ParseForm()
	if err != nil {
		fmt.Fprintf(ue.Ctx.ResponseWriter, "解析参数失败: %v", err)
		return
	}

	op := ue.Ctx.Request.Form.Get("action")

	switch op {
	case "config":
		file, err := os.Open("./conf/config.json")
		if err != nil {
			fmt.Fprintf(ue.Ctx.ResponseWriter, "打开文件错误 : %v", err)
			return
		}
		defer file.Close()
		fd, err := ioutil.ReadAll(file)
		if err != nil {
			fmt.Fprintf(ue.Ctx.ResponseWriter, "读取文件失败 : %v", err)
			return
		}

		src := string(fd)
		re, _ := regexp.Compile(`\/\*[\S\s]+?\*\/`) // 匹配里面的注释
		src = re.ReplaceAllString(src, "")
		tt := []byte(src)
		var r interface{}
		err = json.Unmarshal(tt, &r) //这个byte要解码
		if err != nil {
			fmt.Fprintf(ue.Ctx.ResponseWriter, "json decode failed %v", err)
			return
		}

		tt, err = json.Marshal(r)
		if err != nil {
			fmt.Fprintf(ue.Ctx.ResponseWriter, "json encode failed $v", err)
			return
		}
		ue.Data["json"] = string(tt)
		ue.ServeJSON()
		//fmt.Fprint(ue.Ctx.ResponseWriter, string(tt))
	// 上传图片的功能
	case "uploadimage":
		err := ue.Ctx.Request.ParseForm()
		if err != nil {
			fmt.Fprintf(ue.Ctx.ResponseWriter, "uploadimage parseform fail : %v", err)
			return
		}
		fmt.Println("打印所有的请求 : ", ue.Ctx.Request.PostForm)
		fmt.Println("打印 upfile :", ue.Ctx.Request.PostForm.Get("upfile"))
		ue.Data["json"] = &CallResult{
			Data: "success",
			Code: model.ErrCodeSuccess,
		}
		ue.ServeJSON()
	default:
		fmt.Fprint(ue.Ctx.ResponseWriter, `{"msg":"请求地址错误"}`)
	}
}
