package api import ( "database/sql" "encoding/json" "fmt" "github.com/astaxie/beego/logs" "io/ioutil" "log" "math" "net/http" "os" "path" "regexp" "strconv" "strings" "time" "kpt.xdmy/apiserver/service" "github.com/360EntSecGroup-Skylar/excelize" "github.com/jmoiron/sqlx" "github.com/pkg/errors" // "github.com/360EntSecGroup-Skylar/excelize" "github.com/Anderson-Lu/gofasion/gofasion" "github.com/axetroy/go-fs" "github.com/gin-gonic/gin" "github.com/tealeg/xlsx" // "github.com/xormplus/xorm" "kpt.xdmy/apiserver/routers/restful" "kpt.xdmy/pkg/app" "kpt.xdmy/pkg/e" "kpt.xdmy/pkg/logging" "kpt.xdmy/pkg/setting" "kpt.xdmy/pkg/util" ) // @Summary 根据SQL执行得到数据集 // @Tags getData // @Accept json // @Produce json // @Param sql query string true "sql" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/getdata [POST] func GetData(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlstr := fsion.Get("sql").ValueStr() offset := fsion.Get("offset").ValueDefaultInt(0) pagecount := fsion.Get("pagecount").ValueDefaultInt(0) returntype := fsion.Get("returntype").ValueDefaultStr("map") queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) } else { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } func Testpartitions(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称 user := fsion.Get("user").ValueStr() //获取新数据库用户 passWord := fsion.Get("passWord").ValueStr() //获取新数据库名称 host := fsion.Get("host").ValueStr() //获取新数据库名称 port := fsion.Get("port").ValueStr() sqlstr := "SELECT sql FROM sql_new " var sqlname string err1 := restful.BasicList(sqlstr, nil, &sqlname) if err1 != nil { appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error()) } sqlstrs := strings.Split(sqlname, ";") //分割sql // sqlstrs := strings.Split(p["sql"].(string), ";") //分割sql connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql") mydb, err := sql.Open("mysql", connecting) //连接新连接 if err != nil { println("err1", err.Error()) } _, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库 if err != nil { println("err2", err.Error()) } mydb.Close() connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格 mydb, err = sql.Open("mysql", connecting) if err != nil { println("err3", err.Error()) } defer mydb.Close() if err == nil { mydb.SetMaxOpenConns(10) mydb.SetMaxIdleConns(10) } errmsg := "" if err == nil { //tx ,_ :=mydb.Begin() for _, sqlstr := range sqlstrs { //println("sqlstr---",sqlstr) if sqlstr == "" { continue } _, err = mydb.Exec(sqlstr) if err != nil { println("err4", err.Error()) errmsg = err.Error() } } } if errmsg == "" { appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName) } else { appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg) } } func TestData(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlstr := fsion.Get("sql").ValueStr() token := "" if tempv, exists := c.Get("jwt_username"); exists { token = tempv.(string) } appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token) } // GetDataByName // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags GetDataByName // @Accept json // @Produce json // @Param sqlname body string true "sqlname" // @Param offset body int true "offset" // @Param pagecount body int true "pagecount" // @Param returntype body string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/GetDataByName [POST] func GetDataByName(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() offset := fsion.Get("offset").ValueDefaultInt(0) pagecount := fsion.Get("pagecount").ValueDefaultInt(0) returntype := fsion.Get("returntype").ValueDefaultStr("map") getTotal := fsion.Get("getTotal").ValueStr() paramsTest := fsion.Get("parammaps") if sqlnamestr == "getBuyeCode" { pagecount = 9999 } fmt.Println(paramsTest.Get("partClass").ValueStr()) sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil) if sql != "" { s_params := make([]interface{}, 0) if fsion.HasKey("parammaps") { parammaps := fsion.Get("parammaps") if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" { logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr()) } paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } } } else if fsion.HasKey("params") { params := fsion.Get("params").Array() logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params) for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } if returntype == "xlsx" { var xlsxfile *xlsx.File xlsxfile, _ = restful.QueryByXlsx(sql, s_params) //c.File("c:/dd.xlsx") c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx") c.Header("Content-Transfer-Encoding", "binary") _ = xlsxfile.Write(c.Writer) } else { // queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx) queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params) if getTotal == "total3" { totalData := make(map[string]interface{}) queryData1 := queryData.(map[string]interface{}) totalData["total3"] = queryData1["total"] appG.Response(http.StatusOK, e.SUCCESS, totalData) return } if sqlnamestr == "getMenuByRole" { var list []interface{} data := make(map[string]interface{}) for _, item := range queryData.(map[string]interface{})["lists"].([]map[string]interface{}) { fmt.Println(item["menu_id"]) list = append(list, item["menu_id"]) } data["menu_id"] = list queryData.(map[string]interface{})["lists"] = data appG.Response(http.StatusOK, e.SUCCESS, queryData) return } else if sqlnamestr == "getRoleByUser" { var list []interface{} data := make(map[string]interface{}) for _, item := range queryData.(map[string]interface{})["lists"].([]map[string]interface{}) { fmt.Println(item["role_id"]) list = append(list, item["role_id"]) } data["role_id"] = list queryData.(map[string]interface{})["lists"] = data appG.Response(http.StatusOK, e.SUCCESS, queryData) return } else if sqlnamestr == "updateEQStartStop" { tx, err := restful.Dbs.Beginx() defer func() { switch { case err != nil: fmt.Println("__error:", err) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } }() parammaps := fsion.Get("parammaps") username, _ := c.Get("jwt_username") queryData, _ := getDataBySqlT("select maintenance from equipment where id = ? ", 0, 0, "", []interface{}{parammaps.Get("id").ValueStr()}) for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) { for _, maintenance := range strings.Split(value["maintenance"].(string), ",") { if parammaps.Get("SSPstatue").ValueStr() == "启用" { _, err := tx.Exec(` INSERT INTO wxworkmsg(DATE,userid,msg,formcode,TYPE,note)values(now(), ?,concat("设备启停通知:\n设备资产编号:",(select eqCode from equipment where id = ? ),"\n用途:",(select purpose from equipment where id = ? ),"\n由报修人",(select empname from emp where empcode = ? limit 1),"启用\n时间:",now()),(select eqCode from equipment where id = ? ),1,null)`, maintenance, parammaps.Get("id").ValueStr(), parammaps.Get("id").ValueStr(), username, parammaps.Get("id").ValueStr()) fmt.Println(err) } else { _, err := tx.Exec(` INSERT INTO wxworkmsg(DATE,userid,msg,formcode,TYPE,note)values(now(), ?,concat("设备启停通知:\n设备资产编号:",(select eqCode from equipment where id = ? ),"\n用途:",(select purpose from equipment where id = ? ),"\n由报修人",(select empname from emp where empcode = ? limit 1 ),"停机\n时间:",now()),(select eqCode from equipment where id = ? ),1,null)`, maintenance, parammaps.Get("id").ValueStr(), parammaps.Get("id").ValueStr(), username, parammaps.Get("id").ValueStr()) fmt.Println(err) } } } } else if sqlnamestr == "UkdoneRatePasture" { } if err != nil { logging.Error("GetDataByName err: ", err) msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) } else { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } } else { appG.Response(http.StatusOK, e.SUCCESS, nil) } defer c.Request.Body.Close() } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags GetDataByName // @Accept json // @Produce json // @Param sqlname body string true "sqlname" // @Param offset body int true "offset" // @Param pagecount body int true "pagecount" // @Param returntype body string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/GetDataByName [POST] func EasSync(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) typeIn := fsion.Get("typeIn").ValueDefaultInt(0) billCode := fsion.Get("billCode").ValueStr() logging.Error("EasSync date: ", typeIn, billCode) //typeInstr := fsion.Get("typeIn").ValueStr() //println(typeInstr,typeIn) // 用于判断备件干什么的和eas同步 err := util.EASBillSync(typeIn, billCode, "1") if err != nil { logging.Error("EasSync err: ", err) appG.Response(http.StatusOK, e.ERROR, err.Error()) } else { appG.Response(http.StatusOK, e.SUCCESS, "成功") } } func GetDataByNameOPEN(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() sqlnamestr = sqlnamestr + "OPEN" offset := fsion.Get("offset").ValueDefaultInt(0) pagecount := fsion.Get("pagecount").ValueDefaultInt(0) returntype := fsion.Get("returntype").ValueDefaultStr("map") sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil) //fmt.Println("sql========\n",sqlnamestr,sql) if sql != "" { s_params := make([]interface{}, 0) if fsion.HasKey("parammaps") { parammaps := fsion.Get("parammaps") if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" { logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr()) } paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } } } else if fsion.HasKey("params") { params := fsion.Get("params").Array() logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params) for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } if returntype == "xlsx" { var xlsxfile *xlsx.File xlsxfile, _ = restful.QueryByXlsx(sql, s_params) //c.File("c:/dd.xlsx") c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx") c.Header("Content-Transfer-Encoding", "binary") _ = xlsxfile.Write(c.Writer) } else { // queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx) queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params) if err != nil { logging.Error("GetDataByName err: ", err) msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) } else { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } } else { appG.Response(http.StatusOK, e.SUCCESS, nil) } } func geterrmsg(errstr string) (msgstr string) { var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字 rs := []rune(errstr) if len(rs) == 0 { msgstr = errstr return } if hzRegexp.MatchString(string(rs[0])) { msgstr = errstr return } if strings.Contains(errstr, "Duplicate entry") { strs := strings.Split(errstr, ` key '`) if len(strs) > 1 { if len(strs[len(strs)-1]) > 1 { errstr = "Duplicate entry :" + strs[len(strs)-1] } } } msg, err := restful.MapStrList("SELECT msg FROM err_msg where err = ? ", errstr) if err != nil { msgstr = errstr return } if msg == nil || len(msg) == 0 { var param []interface{} param = append(param, errstr, errstr) go func() { tx, err := restful.Dbs.Beginx() defer func() { switch { case err != nil: logging.Error("tx.Begin 事务启动失败__error:", err) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } if tx != nil { } }() _, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx) if err != nil { logging.Error("insert into err_msg(err,msg) err", err) } }() msgstr = errstr } else { msgstr = msg[0]["msg"] } return } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags GetDataByNameForm // @Accept json // @Produce json // @Param sqlname body json true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Param s formData json true "ss" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/GetDataByNameForm [POST] func GetDataByNameForm(c *gin.Context) { appG := app.Gin{C: c} //sqlnamestr := c.PostForm("measureNumber") //dataByte, _ := ioutil.ReadAll(c.Request.Body) //fsion := gofasion.NewFasion(string(dataByte)) //sqlnamestr := fsion.Get("name").ValueStr() //offset := fsion.Get("offset").ValueInt() //pagecount := fsion.Get("pagecount").ValueInt() //returntype := fsion.Get("returntype").ValueStr() //params := fsion.Get("params").Array() c.Request.ParseForm() params := c.Request.Form offset := 0 pageSize_ := 0 returntype := params.Get("page") if returntype == "" { returntype = "0" } if tempv, exists := c.Get("jwt_username"); exists { params.Set("JwtUserName", tempv.(string)) } else { params.Set("JwtUserName", "") } sqlnamestr := params.Get("name") logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr) s_params := make([]interface{}, 0) if returntype == "1" { pageNum, error := strconv.Atoi(params.Get("pageNum")) if error != nil { appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数") } pageSize, error := strconv.Atoi(params.Get("pageSize")) if error != nil { appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数") } pageSize_ = pageSize offset = pageNum } sql, p := restful.GetSqlByNameDB(sqlnamestr) paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { s_params = append(s_params, params.Get(strings.Trim(value, " "))) } } if sql != "" { if returntype == "xlsx" { var xlsxfile *xlsx.File xlsxfile, _ = restful.QueryByXlsx(sql, s_params) c.Header("Content-Type", "application/octet-stream") c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx") c.Header("Content-Transfer-Encoding", "binary") _ = xlsxfile.Write(c.Writer) } else { queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params) if err != nil { appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error()) } else { appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData) } } } else { appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口") } } // @Summary 递归获取所有 // @Tags menu // @Accept json // @Produce json // @Param Ton query string true "Ton" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Router /authdata/GetRoleMenus [GET] func GetRecuDataByName(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() parentidname := fsion.Get("idname").ValueStr() sql, p := restful.GetSqlByNameDB(sqlnamestr) params := make(map[string]interface{}) s_params := make([]interface{}, 0) if fsion.HasKey("params") { for _, v_params := range fsion.Get("params").Array() { s_params = append(s_params, v_params.ValueStr()) } params["params"] = s_params } else { jparams := fsion.Get("parammaps") paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { params[value] = tempv.(string) } else { params[value] = "" } } else { params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr() } } } } queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params")) logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) } appG.Response(http.StatusOK, e.SUCCESS, queryData) } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags GetDataByNames // @Accept json // @Produce json // @RequestBody sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/GetDataByNames [POST] func GetDataByNames(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlParams := fsion.Array() queryData := make(map[string]interface{}) for _, v := range sqlParams { fsion2 := gofasion.NewFasion(v.Json()) logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr) // p是sql表中的sql语句中的变量差数格式 sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr()) if sql == "" { errorm := make(map[string]interface{}) errorm["code"] = e.ERROR errorm["message"] = "sql没找到" queryData[fsion2.Get("name").ValueStr()] = errorm continue } else if sql != "" { offset := fsion2.Get("offset").ValueInt() pagecount := fsion2.Get("pagecount").ValueInt() returntype := fsion2.Get("returntype").ValueStr() // s_params 是用来存储sql中需要的参数 s_params := make([]interface{}, 0) // 这边是判断是传过来的是参数格式如果是map格式的是需要在apisql表中查询params字段 if fsion2.HasKey("parammaps") { parammaps := fsion2.Get("parammaps") paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } } } else if fsion2.HasKey("params") { params := fsion2.Get("params").Array() for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params) if err != nil { errorm := make(map[string]interface{}) errorm["code"] = e.ERROR errorm["message"] = err.Error() queryData[fsion2.Get("name").ValueStr()] = errorm logging.Error("GetDataByNames err: ", err) continue } else { queryData[fsion2.Get("name").ValueStr()] = queryData1 } } } appG.Response(http.StatusOK, e.SUCCESS, queryData) } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags PostDataByNameForm // @Accept json // @Produce json // @Param sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误朱红彬彬"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/PostDataByNameForm [POST] func PostDataByNameForm(c *gin.Context) { appG := app.Gin{C: c} c.Request.ParseForm() params := c.Request.Form sqlnamestr := params.Get("name") logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr) s_params := make([]interface{}, 0) sql, p := restful.GetSqlByNameDB(sqlnamestr) paramslist := strings.Split(p, ",") if len(paramslist) > 0 { for _, value := range paramslist { s_params = append(s_params, params.Get(strings.Trim(value, " "))) } } if sql != "" { queryData, err := execDataBySql(sql, s_params) if err != nil { appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error()) } else { appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData) } } else { appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口") } } func GetReportform(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() parammaps := fsion.Get("parammaps") logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps) queryData, _ := praseReportform(sqlnamestr, parammaps) appG.Response(http.StatusOK, e.SUCCESS, queryData) } func praseReportform(sqlnamestr string, parammaps *gofasion.Fasion) (queryData map[string]interface{}, err error) { switch sqlnamestr { case "getpSumNow", "getpSumNowWater", "getpSumNowElec", "getpSumNowDiesel": queryData, err = getpSumNow(sqlnamestr, parammaps) case "getPastureSumMonth", "getPastureSumMonthWater", "getPastureSumMonthElec", "getPastureSumMonthDiesel": queryData, err = getPastureSumMonth(sqlnamestr, parammaps) case "getPastureSumDayWater", "getPastureSumDayElec", "getPastureSumDayDiesel": queryData, err = getPastureSumDay(sqlnamestr, parammaps) case "getPastureSumDay": queryData, err = getPastureSumDay1(sqlnamestr, parammaps) case "geteqclassSumMonth", "geteqclassSumMonthWater", "geteqclassSumMonthElec", "geteqclassSumMonthDiesel": queryData, err = geteqclassSumMonth(sqlnamestr, parammaps) case "geteCowWaterList", "geteCowElecList", "geteCowDieselList", "geteCowMaintainList", "geteCowAllList": queryData, err = geteCow(sqlnamestr, parammaps) case "geteCowWaterMonthList", "geteCowElecMonthList", "geteCowDieselMonthList", "geteCowMaintainMonthList", "geteCowAllMonthList": queryData, err = geteCowMonth(sqlnamestr, parammaps) case "getEqRunSurveyListPasture": queryData, err = getEqRunSurveyListPasture(sqlnamestr, parammaps) case "geteqclassFeeSum", "geteqclassFeeSumPasture": queryData, err = geteqclassFeeSum(sqlnamestr, parammaps) case "getEqRunSurveyListDay": queryData, err = getEqRunSurveyListDay(sqlnamestr, parammaps) case "getReportEqCostYear": queryData, err = geteqCostYear(sqlnamestr, parammaps) case "getReportEqCostMonth": queryData, err = geteqCostMonth(sqlnamestr, parammaps) case "homepagePastureInfor": queryData, err = homepagePastureInfor(sqlnamestr, parammaps) case "homepageEqstatus": queryData, err = homepageEqstatus(sqlnamestr, parammaps) case "homepageEqRunstatueListPasture", "homepageEqRunstatueListEqclass": queryData, err = homepageEqRunstatue(sqlnamestr, parammaps) case "homepageFeeWX", "homepageFeeWater", "homepageFeeElec", "homepageFeeDiesel": queryData, err = homepageFee(sqlnamestr, parammaps) default: queryData, err = nil, nil } return } func homepageFee(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pastureName := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() pSumNow, err := restful.MapStrList(sqlNow, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName) if err != nil { log.Default().Printf("homepageFee queryx: %v", err) } typeStr := parammaps.Get(strings.Trim("type", " ")).ValueStr() list1s := make([]string, 1) list2s := make([]string, 1) list3s := make([]string, 1) list4s := make([]string, 1) list5s := make([]string, 1) list6s := make([]string, 1) list7s := make([]string, 1) list8s := make([]string, 1) list1s[0] = typeStr for _, value := range pSumNow { list2s[0] = value["monthBudget"] list3s[0] = value["sumPrice"] list4s[0] = value["monthBudgetL"] list5s[0] = value["sumPriceL"] list6s[0] = value["monthBudget"] list7s[0] = value["sumPrice"] list8s[0] = value["cowS"] } queryData["data1"] = list1s queryData["data2"] = list2s queryData["data3"] = list3s queryData["data4"] = list4s queryData["data5"] = list5s queryData["data6"] = list6s queryData["data7"] = list7s queryData["data8"] = list8s queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func homepageEqRunstatue(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pastureName := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() typeStr := parammaps.Get(strings.Trim("type", " ")).ValueStr() pSumNow, _ := restful.MapStrList(sqlNow, pastureName) list1s := make([]string, 0) list2s := make([]string, 0) list3s := make([]string, 1) list3s[0] = typeStr for _, value := range pSumNow { list1s = append(list1s, value["name"]) list2s = append(list2s, value["rate"]) } queryData["data1"] = list1s queryData["data2"] = list2s queryData["data3"] = list3s queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func homepageEqstatus(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pastureName := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() pSumNow, _ := restful.MapStrList(sqlNow, pastureName, pastureName) list1s := make([]string, 0) list2s := make([]string, 0) for _, value := range pSumNow { list1s = append(list1s, value["status"]) list2s = append(list2s, value["cou"]) } queryData["data1"] = list1s queryData["data2"] = list2s queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func homepagePastureInfor(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow) lolalists := make([]map[string]interface{}, 0) pasturelists := make([]map[string]interface{}, 0) lolalist := make(map[string]interface{}, 1) for _, value := range pSumNow { lola := make([]string, 0) pasturelist := make(map[string]interface{}, 1) lola = append(lola, value["longitude"]) lola = append(lola, value["latitude"]) lolalist[value["name"]] = lola pasturelist["name"] = value["name"] pasturelist["value"] = value["name"] pasturelists = append(pasturelists, pasturelist) } lolalists = append(lolalists, lolalist) queryData["data1"] = lolalists queryData["data2"] = pasturelists queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func geteqCostMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr() eqId := parammaps.Get(strings.Trim("eqId", " ")).ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow, receiveTime, eqId, receiveTime, receiveTime, eqId, receiveTime, receiveTime) chartData := make(map[string]interface{}) months := []string{} upkeepCost := []string{} repireCost := []string{} //lastTotal,nowTotal := 0,0 a := true month := "" for i := 1; i <= 12; i++ { if i < 10 { month = receiveTime + "-0" + strconv.Itoa(i) } else { month = receiveTime + "-" + strconv.Itoa(i) } months = append(months, month) for _, va := range pSumNow { if va["yearR"][5:] == month[5:] { upkeepCost = append(upkeepCost, va["Ucost"]) repireCost = append(repireCost, va["Rcost"]) a = false } } if a { upkeepCost = append(upkeepCost, "0") repireCost = append(repireCost, "0") } a = true } chartData["months"] = months chartData["upkeepCost"] = upkeepCost chartData["repireCost"] = repireCost queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func geteqCostYear(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) //receiveTime :=parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr() eqId := parammaps.Get(strings.Trim("eqId", " ")).ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow, eqId, eqId, eqId) //restful.M chartData := make(map[string]interface{}) year := []string{} upkeepCost := []string{} repireCost := []string{} for _, va := range pSumNow { year = append(year, va["yearR"]) upkeepCost = append(upkeepCost, va["Ucost"]) repireCost = append(repireCost, va["Rcost"]) } chartData["year"] = year chartData["upkeepCost"] = upkeepCost chartData["repireCost"] = repireCost queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func geteCowMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("year", " ")).ValueStr() pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() var pSumNow, pSumLast []map[string]string if sqlnamestr == "geteCowAllMonthList" { sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, receiveTime, receiveTime, receiveTime, receiveTime, receiveTime, pastureNames) tempTime, _ := strconv.Atoi(receiveTime) receiveTimetemp := strconv.Itoa(tempTime - 1) pSumLast, _ = restful.MapStrList(sqlNow, receiveTimetemp, receiveTimetemp, receiveTimetemp, receiveTimetemp, receiveTimetemp, receiveTimetemp, pastureNames) } else { sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, receiveTime, receiveTime, pastureNames) tempTime, _ := strconv.Atoi(receiveTime) receiveTimetemp := strconv.Itoa(tempTime - 1) pSumLast, _ = restful.MapStrList(sqlNow, receiveTimetemp, receiveTimetemp, receiveTimetemp, pastureNames) } chartData := make(map[string]interface{}) months := []string{} lastYear := []string{} nowYear := []string{} budgetYear := []string{} //lastTotal,nowTotal := 0,0 a, b := true, true month := "" for i := 1; i <= 12; i++ { if i < 10 { month = receiveTime + "-0" + strconv.Itoa(i) } else { month = receiveTime + "-" + strconv.Itoa(i) } months = append(months, month) for _, va := range pSumNow { if va["month"][5:] == month[5:] { nowYear = append(nowYear, va["psum"]) budgetYear = append(budgetYear, va["lsum"]) a = false } } for _, va := range pSumLast { if va["month"][5:] == month[5:] { lastYear = append(lastYear, va["psum"]) b = false } } if a { nowYear = append(nowYear, "0") budgetYear = append(budgetYear, "0") } if b { lastYear = append(lastYear, "0") } a = true b = true } chartData["months"] = months chartData["lastYear"] = lastYear chartData["nowYear"] = nowYear chartData["budgetYear"] = budgetYear queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func getEqRunSurveyListDay(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("praseTime", " ")).ValueStr() pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime) if pSumNow == nil { return nil, nil } typeName := make([]map[string]interface{}, 4) ma := make(map[string]interface{}) ma1 := make(map[string]interface{}) ma2 := make(map[string]interface{}) ma3 := make(map[string]interface{}) ma["name"] = "在用" ma["value"] = pSumNow[0]["eqUse"] typeName[0] = ma ma1["name"] = "闲置" ma1["value"] = pSumNow[0]["eqXZ"] typeName[1] = ma1 ma2["name"] = "报废" ma2["value"] = pSumNow[0]["eqBF"] typeName[2] = ma2 ma3["name"] = "封存" ma3["value"] = pSumNow[0]["eqFC"] typeName[3] = ma3 queryData["psm"] = typeName queryData["code"] = 0 queryData["total"] = pSumNow[0]["eqSum"] queryData["message"] = "ok" return queryData, nil } func getEqRunSurveyListPasture(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("praseTime", " ")).ValueStr() pastureNames, _ := restful.MapStrList("SELECT `name` FROM pasture order by sort") sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow, receiveTime) chartData := make(map[string]interface{}) pasture := []string{} eqUse := []string{} eqXZ := []string{} eqBF := []string{} eqFC := []string{} //lastTotal,nowTotal := 0,0 a := true for _, value := range pastureNames { pasture = append(pasture, value["name"]) for _, va := range pSumNow { if va["pastureName"] == value["name"] { eqUset, _ := strconv.Atoi(va["eqUse"]) eqSumt, _ := strconv.Atoi(va["eqSum"]) eqXZt, _ := strconv.Atoi(va["eqXZ"]) eqBFt, _ := strconv.Atoi(va["eqBF"]) eqFCt, _ := strconv.Atoi(va["eqFC"]) eqUsetem := float64(eqUset) / float64(eqSumt) * 100 eqXZtem := float64(eqXZt) / float64(eqSumt) * 100 eqBFtem := float64(eqBFt) / float64(eqSumt) * 100 eqFCtem := float64(eqFCt) / float64(eqSumt) * 100 eqUse = append(eqUse, strconv.FormatFloat(eqUsetem, 'f', 2, 64)) //eqSum = append(eqSum, va["eqSum"]) eqXZ = append(eqXZ, strconv.FormatFloat(eqXZtem, 'f', 2, 64)) eqBF = append(eqBF, strconv.FormatFloat(eqBFtem, 'f', 2, 64)) eqFC = append(eqFC, strconv.FormatFloat(eqFCtem, 'f', 2, 64)) a = false } } if a { eqUse = append(eqUse, "0") //eqSum = append(eqSum, "0") eqXZ = append(eqXZ, "0") eqBF = append(eqBF, "0") eqFC = append(eqFC, "0") } a = true } chartData["pastureName"] = pasture chartData["eqUseRate"] = eqUse //chartData["eqSum"] = eqSum chartData["eqXZRate"] = eqXZ chartData["eqBFRate"] = eqBF chartData["eqFCRate"] = eqFC queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func geteqclassFeeSum(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) year := parammaps.Get(strings.Trim("year", " ")).ValueStr() month := parammaps.Get(strings.Trim("month", " ")).ValueStr() eqClassName := parammaps.Get(strings.Trim("eqClassName", " ")).ValueStr() PastureName := parammaps.Get("PastureName").ValueStr() DepartmentName := parammaps.Get("DepartmentName").ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, err := restful.MapStrList(sqlNow, year, month, eqClassName, eqClassName, PastureName, PastureName, DepartmentName, DepartmentName) if len(pSumNow) == 0 { log.Default().Printf("geteqclassFeeSum result is empty") } fmt.Println(err) chartData := make(map[string]interface{}) eqUse := []string{} eqXZ := []string{} for _, va := range pSumNow { eqUse = append(eqUse, va["psum"]) eqXZ = append(eqXZ, va["typeName"]) } chartData["data1"] = eqUse chartData["data2"] = eqXZ queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func geteqclassSumMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr() pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() deptName := parammaps.Get(strings.Trim("deptName", " ")).ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime, deptName) if len(pSumNow) == 0 { log.Default().Printf("geteqclassSumMonth result is empty") } chartData := make(map[string]interface{}) typeName := []string{} eqCost := []string{} for _, va := range pSumNow { typeName = append(typeName, va["typeName"]) eqCost = append(eqCost, va["psum"]) } chartData["typeName"] = typeName chartData["eqCost"] = eqCost queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func getPastureSumDay(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr() pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime) if len(pSumNow) == 0 { log.Default().Printf("getPastureSumDay result is empty") } tempTime, _ := strconv.Atoi(receiveTime[:4]) receiveTimetemp := strconv.Itoa(tempTime-1) + receiveTime[4:] pSumLast, _ := restful.MapStrList(sqlNow, pastureNames, receiveTimetemp) chartData := make(map[string]interface{}) months := []string{} lastYear := []string{} nowYear := []string{} //lastTotal,nowTotal := 0,0 a, b := true, true month := "" dayCount := GetMonthCount(receiveTime) for i := 1; i <= dayCount; i++ { if i < 10 { month = receiveTime + "-0" + strconv.Itoa(i) } else { month = receiveTime + "-" + strconv.Itoa(i) } months = append(months, strconv.Itoa(i)) for _, va := range pSumNow { if va["month"][8:] == month[8:] { nowYear = append(nowYear, va["psum"]) a = false } } for _, va := range pSumLast { if va["month"][8:] == month[8:] { lastYear = append(lastYear, va["psum"]) b = false } } if a { if month[:] > time.Now().Format("2006-01-02") { nowYear = append(nowYear, "") } else { nowYear = append(nowYear, "0") } } if b { lastYear = append(lastYear, "0") } a = true b = true } chartData["day"] = months chartData["lastYear"] = lastYear chartData["nowYear"] = nowYear queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func getPastureSumDay1(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr() pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() departmentName := parammaps.Get(strings.Trim("departmentName", " ")).ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName) if len(pSumNow) == 0 { log.Default().Printf("getPastureSumDay1query is empty") } tempTime, _ := strconv.Atoi(receiveTime[:4]) receiveTimetemp := strconv.Itoa(tempTime-1) + receiveTime[4:] pSumLast, _ := restful.MapStrList(sqlNow, pastureNames, receiveTimetemp, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName) if len(pSumLast) == 0 { log.Default().Printf("getPastureSumDay1 query is empty") } chartData := make(map[string]interface{}) months := []string{} lastYear := []string{} nowYear := []string{} a, b := true, true month := "" for i := 1; i <= 12; i++ { if i < 10 { month = receiveTime[:4] + "-0" + strconv.Itoa(i) } else { month = receiveTime[:4] + "-" + strconv.Itoa(i) } months = append(months, month) for _, va := range pSumNow { if va["month"][5:7] == month[5:] { nowYear = append(nowYear, va["psum"]) a = false } } for _, va := range pSumLast { if va["month"][5:7] == month[5:] { lastYear = append(lastYear, va["psum"]) b = false } } if a { if month[:] > time.Now().Format("2006-01") { nowYear = append(nowYear, "") } else { nowYear = append(nowYear, "0") } } if b { lastYear = append(lastYear, "0") } a = true b = true } chartData["months"] = months chartData["lastYear"] = lastYear chartData["nowYear"] = nowYear queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func GetMonthCount(receiveTime string) (days int) { year, _ := strconv.Atoi(receiveTime[:4]) month, _ := strconv.Atoi(receiveTime[5:]) if month != 2 { if month == 4 || month == 6 || month == 9 || month == 11 { days = 30 } else { days = 31 } } else { if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 { days = 29 } else { days = 28 } } return } func getPastureSumMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr() pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr() departmentName := parammaps.Get(strings.Trim("departmentName", " ")).ValueStr() sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) var pSumNow []map[string]string if sqlnamestr == "getPastureSumMonth" { pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName) } else { pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, receiveTime) } tempTime, _ := strconv.Atoi(receiveTime) receiveTimetemp := strconv.Itoa(tempTime - 1) var pSumLast []map[string]string if sqlnamestr == "getPastureSumMonth" { pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, receiveTimetemp, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName) } else { pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, receiveTimetemp) } chartData := make(map[string]interface{}) months := []string{} lastYear := []string{} nowYear := []string{} //lastTotal,nowTotal := 0,0 a, b := true, true month := "" for i := 1; i <= 12; i++ { if i < 10 { month = receiveTime + "-0" + strconv.Itoa(i) } else { month = receiveTime + "-" + strconv.Itoa(i) } months = append(months, month) for _, va := range pSumNow { if va["month"][5:] == month[5:] { nowYear = append(nowYear, va["psum"]) a = false } } for _, va := range pSumLast { if va["month"][5:] == month[5:] { lastYear = append(lastYear, va["psum"]) b = false } } if a { if month[:] > time.Now().Format("2006-01") { nowYear = append(nowYear, "") } else { nowYear = append(nowYear, "0") } } if b { lastYear = append(lastYear, "0") } a = true b = true } chartData["months"] = months chartData["lastYear"] = lastYear chartData["nowYear"] = nowYear queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func geteCow(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("year", " ")).ValueStr() pastureNames, _ := restful.MapStrList("SELECT `name` FROM pasture where `name` <> '现代牧业' and vendor = 1 and" + " id not in(620,1238,1239,1240,1241,1242,1243,1244) order by sort ") var pSumNow, pSumLast []map[string]string rTime := "" if sqlnamestr == "geteCowAllList" { sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) if receiveTime == time.Now().Format("2006") { rTime = time.Now().Format("2006-01-02") } else { rTime = receiveTime + "-12-31" } pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime) if receiveTime == time.Now().Format("2006") { rTime = time.Now().AddDate(-1, 0, 0).Format("2006-01-02") } else { rTime = receiveTime + "-12-31" } receiveTimei, _ := strconv.Atoi(receiveTime) receiveTime = strconv.Itoa(receiveTimei - 1) pSumLast, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime) } else { sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) if receiveTime == time.Now().Format("2006") { rTime = time.Now().Format("2006-01-02") } else { rTime = receiveTime + "-12-31" } pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime) if receiveTime == time.Now().Format("2006") { rTime = time.Now().AddDate(-1, 0, 0).Format("2006-01-02") } else { rTime = receiveTime + "-12-31" } receiveTimei, _ := strconv.Atoi(receiveTime) receiveTime = strconv.Itoa(receiveTimei - 1) pSumLast, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime) } chartData := make(map[string]interface{}) pasture := []string{} lastYear := []string{} nowYear := []string{} budgetYear := []string{} //lastTotal,nowTotal := 0,0 //var pastureList []string for _, va := range pSumNow { b := true nowYear = append(nowYear, va["psum"]) budgetYear = append(budgetYear, va["lsum"]) fmt.Println(va["psum"]) for _, va1 := range pSumLast { if va1["name"] == va["name"] { lastYear = append(lastYear, va1["psum"]) b = false } } if b { lastYear = append(lastYear, "0.00") } pasture = append(pasture, va["name"]) //pastureList = append(pastureList, va["name"]) } for _, value := range pastureNames { a, b, exist := true, true, false for _, pasturename := range pasture { if value["name"] == pasturename { exist = true break } } if !exist { //for _, va := range pSumNow { // if va["name"] == value["name"] { // nowYear = append(nowYear, va["psum"]) // budgetYear = append(budgetYear, va["lsum"]) // a = false // } //} for _, va := range pSumLast { if va["name"] == value["name"] { lastYear = append(lastYear, va["psum"]) b = false } } if a { nowYear = append(nowYear, "0.0000") budgetYear = append(budgetYear, "0.0000") } if b { lastYear = append(lastYear, "0.0000") } pasture = append(pasture, value["name"]) } // //a = true //b = true } chartData["pasture"] = pasture chartData["lastYear"] = lastYear chartData["nowYear"] = nowYear chartData["budgetYear"] = budgetYear queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func getpSumNow(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) { queryData := make(map[string]interface{}) receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr() departmentName := parammaps.Get(strings.Trim("departmentName", " ")).ValueStr() center := parammaps.Get("center").ValueStr() pastureNames, _ := restful.MapStrList("SELECT `name` FROM pasture where `name` <> '现代牧业' and (center = ? or ? = '' ) order by sort", center, center) rTime := "" sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr) var pSumNow []map[string]string if sqlnamestr == "getpSumNow" { pSumNow, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, center, center) } else { pSumNow, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime, center, center) } //pSumNow, _ := restful.MapStrList(sqlNow, rTime, rTime, receiveTime,departmentName,departmentName,departmentName,departmentName,departmentName,departmentName) receiveTimei, _ := strconv.Atoi(receiveTime) if receiveTime == time.Now().Format("2006") { rTime = time.Now().AddDate(-1, 0, 0).Format("2006-01-02") } else { rTime = receiveTime + "-12-31" } receiveTime = strconv.Itoa(receiveTimei - 1) var pSumLast []map[string]string if sqlnamestr == "getpSumNow" { pSumLast, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, center, center) } else { pSumLast, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime) } //pSumLast, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime,departmentName,departmentName,departmentName,departmentName,departmentName,departmentName) chartData := make(map[string]interface{}) pasture := []string{} lastYear := []string{} nowYear := []string{} //lastTotal,nowTotal := 0,0 a, b := true, true for _, value := range pastureNames { pasture = append(pasture, value["name"]) for _, va := range pSumNow { if va["name"] == value["name"] { nowYear = append(nowYear, va["psum"]) a = false } } for _, va := range pSumLast { if va["name"] == value["name"] { lastYear = append(lastYear, va["psum"]) b = false } } if a { nowYear = append(nowYear, "0") } if b { lastYear = append(lastYear, "0") } a = true b = true } chartData["pasture"] = pasture chartData["lastYear"] = lastYear chartData["nowYear"] = nowYear queryData["chart_data"] = chartData queryData["code"] = 0 queryData["message"] = "ok" return queryData, nil } func GetUpkeepPlan(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() offset := fsion.Get("offset").ValueDefaultInt(0) pagecount := fsion.Get("pagecount").ValueDefaultInt(0) returntype := fsion.Get("returntype").ValueDefaultStr("map") month := fsion.Get("month").ValueDefaultStr("map") logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month) sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil) if sql != "" { s_params := make([]interface{}, 0) if fsion.HasKey("parammaps") { parammaps := fsion.Get("parammaps") paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } } } else if fsion.HasKey("params") { params := fsion.Get("params").Array() for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } if returntype == "xlsx" { var xlsxfile *xlsx.File xlsxfile, _ = restful.QueryByXlsx(sql, s_params) //c.File("c:/dd.xlsx") c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx") c.Header("Content-Transfer-Encoding", "binary") _ = xlsxfile.Write(c.Writer) } else { // queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx) queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) } else { for index, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) { if v, ok := value["id"]; ok { //month = "2020-03" seviceplans, _ := restful.MapStrList("SELECT seviceplan.* FROM seviceplan WHERE seviceplan.eqId = ? AND (seviceplan.month=? OR (SELECT COUNT(*) FROM bigupkeep WHERE seviceplanId = seviceplan.`id` AND plantime BETWEEN CONCAT(?,'-01') AND CONCAT(?,'-31'))>0) ", v, month, month, month) //获取保养计划 if seviceplans != nil { for _, va := range seviceplans { //根据保养计划获取保养单 //day,_ :=strconv.Atoi(va["day"]) bigupkeeps, _ := restful.MapStrList("SELECT * FROM bigupkeep where seviceplanId = ? and plantime between concat(?,'-01') and concat(?,'-31') ", va["id"], month, month) //获取保养计划中的保养单 //buk := make(map[string]map[string]string) for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中 jstr := "" if bu["plantime"][8:9] == "0" { jstr = "m" + bu["plantime"][9:] } else { jstr = "m" + bu["plantime"][8:] } if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Add(-24*time.Hour).Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2 queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"] } else { if bu["flowCompeleted"] >= "2" { queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"] } else { queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"] } } queryData.(map[string]interface{})["list"].([]map[string]interface{})[index]["month"] = va["month"] // 导出报表时,报表中需要显示月份 } } } } } appG.Response(http.StatusOK, e.SUCCESS, queryData) } } } else { appG.Response(http.StatusOK, e.SUCCESS, nil) } } func GetAccount(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() offset := fsion.Get("offset").ValueDefaultInt(0) pagecount := fsion.Get("pagecount").ValueDefaultInt(0) returntype := fsion.Get("returntype").ValueDefaultStr("map") sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil) //fmt.Println("sql========\n",sqlnamestr,sql) if sql != "" { s_params := make([]interface{}, 0) if fsion.HasKey("parammaps") { parammaps := fsion.Get("parammaps") if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" { logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr()) } paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } fmt.Println("params parse end") } } else if fsion.HasKey("params") { params := fsion.Get("params").Array() logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params) for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } if returntype == "xlsx" { var xlsxfile *xlsx.File xlsxfile, _ = restful.QueryByXlsx(sql, s_params) //c.File("c:/dd.xlsx") c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx") c.Header("Content-Transfer-Encoding", "binary") _ = xlsxfile.Write(c.Writer) } else { // queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx) queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params) if err != nil { logging.Error("GetDataByName err: ", err) msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) //appG.Response(http.StatusOK, e.ERROR, err.Error()) } else { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } } else { appG.Response(http.StatusOK, e.SUCCESS, nil) } } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags PostDataByName // @Accept json // @Produce json // @Param sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/PostDataByName [POST] func PostDataByName(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() parammaps := fsion.Get("parammaps") if sqlnamestr == "partsCharge" && parammaps.Get("statue").ValueInt() == 1 { //fmt.Println("jinlaile") defer func() { go util.EASBillSync(5, fsion.Get("parammaps").Get("id").ValueStr(), fsion.Get("parammaps").Get("statue").ValueStr()) }() //go CheckEASWebServiceParts(fsion.Get("parammaps").Get("statue").ValueStr(),fsion.Get("parammaps").Get("id").ValueStr()) } s_params := make([]interface{}, 0) tx, err := restful.Dbs.Beginx() defer func() { switch { case err != nil: fmt.Println("__error:", err) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } }() sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx) if sql != "" { if fsion.HasKey("parammaps") { parammaps := fsion.Get("parammaps") logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr()) paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } } } else if fsion.HasKey("params") { params := fsion.Get("params").Array() logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params) for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } queryData, err := execDataBySqlT(sql, s_params, tx) if err != nil { logging.Error("PostDataByName err: ", err) //appG.Response(http.StatusOK, e.ERROR, err.Error()) msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) } else { if sqlnamestr == "updateEQStartStop" { parammaps := fsion.Get("parammaps") username, _ := c.Get("jwt_username") queryData, _ := getDataBySqlT("select maintenance from equipment where id = ? ", 0, 0, "", []interface{}{parammaps.Get("id").ValueStr()}) for _, value := range queryData.(map[string]interface{})["list"].([]map[string]interface{}) { for _, maintenance := range strings.Split(value["maintenance"].(string), ",") { if parammaps.Get("SSPstatue").ValueStr() == "启用" { _, err := tx.Exec(` INSERT INTO wxworkmsg(DATE,userid,msg,formcode,TYPE,note)values(now(), ?,concat("设备启停通知:\n设备资产编号:",(select eqCode from equipment where id = ? ),"\n用途:",(select purpose from equipment where id = ? ),"\n由报修人",(select empname from emp where empcode = ? limit 1),"启用\n时间:",now()),(select eqCode from equipment where id = ? ),1,null)`, maintenance, parammaps.Get("id").ValueStr(), parammaps.Get("id").ValueStr(), username, parammaps.Get("id").ValueStr()) fmt.Println(err) } else { _, err := tx.Exec(` INSERT INTO wxworkmsg(DATE,userid,msg,formcode,TYPE,note)values(now(), ?,concat("设备启停通知:\n设备资产编号:",(select eqCode from equipment where id = ? ),"\n用途:",(select purpose from equipment where id = ? ),"\n由报修人",(select empname from emp where empcode = ? limit 1 ),"停机\n时间:",now()),(select eqCode from equipment where id = ? ),1,null)`, maintenance, parammaps.Get("id").ValueStr(), parammaps.Get("id").ValueStr(), username, parammaps.Get("id").ValueStr()) fmt.Println(err) } } } } else if restful.GetUserVendor(c.MustGet("jwt_username").(string)) == 1 && (sqlnamestr == "updateBigbuydetailStatu" || sqlnamestr == "shutDownBigrefunddetail") { err = service.NextProcurement(sqlnamestr, parammaps.Get("id").ValueStr(), tx) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) return } } appG.Response(http.StatusOK, e.SUCCESS, queryData) } } else { appG.Response(http.StatusOK, e.SUCCESS, nil) } } func PostThirdPartyData(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) tempval_ := make(map[string]interface{}) tempval := make([]map[string]interface{}, 0) err := json.Unmarshal(dataByte, &tempval_) logging.Info("PostThirdPartyData ", c.Keys, c.Request.RemoteAddr, tempval_["name"]) //logging.Info("PostThirdPartyData ", c.Keys, c.Request.RemoteAddr, tempval_["name"],tempval_) if err != nil { logging.Error("PostThirdPartyData Unmarshal error:", err) } else { if v, ok := tempval_["list"].([]interface{}); ok { for _, Tvalue := range v { if v1, ok := Tvalue.(map[string]interface{}); ok { tempval = append(tempval, v1) } } } tx, err := restful.Dbs.Beginx() if err != nil { logging.Error("tx.Begin 事务启动失败__error:", err) } defer func() { switch { case err != nil: fmt.Println("__error:", err) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } if tx != nil { } }() if err == nil { sqlname, ok := tempval_["name"] if ok { } sql, p := restful.GetSqlByNameDBT(sqlname.(string), tx) if sql == "" { appG.Response(http.StatusOK, e.ERROR, "调用接口不存在") } //s_params := make([]interface{}, 0) paramslist := strings.Split(p, ",") resname := "" for _, paramvalue := range tempval { s_params := make([]interface{}, 0) if len(paramslist) > 0 && p != "" { for _, value := range paramslist { s_params = append(s_params, paramvalue[value]) //fmt.Println(value,paramvalue[value]) } } var res []map[string]string res, err = restful.MapStrList("select id from measure where meterNumber = ? and meterType = '电表' and isdel = 0", paramvalue["meterNumber"]) if len(res) == 0 || err != nil { switch paramvalue["meterNumber"].(type) { case string: resname = paramvalue["meterNumber"].(string) } err = errors.New("电表不存在") break } _, err = execDataBySqlT(sql, s_params, tx) if err != nil { switch paramvalue["meterNumber"].(type) { case string: resname = paramvalue["meterNumber"].(string) } break } } if err == nil { appG.Response(http.StatusOK, e.SUCCESS, "ok") } else { msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg+" "+resname) //appG.Response(http.StatusOK, e.ERROR, err.Error()) } } } if err != nil { msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) //appG.Response(http.StatusOK, e.ERROR, err.Error()) } } func PostDataByNameOPEN(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() sqlnamestr = sqlnamestr + "OPEN" s_params := make([]interface{}, 0) tx, err := restful.Dbs.Beginx() defer func() { switch { case err != nil: fmt.Println("__error:", err) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } }() sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx) if sql != "" { if fsion.HasKey("parammaps") { parammaps := fsion.Get("parammaps") logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr()) paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } } } else if fsion.HasKey("params") { params := fsion.Get("params").Array() logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params) for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } queryData, err := execDataBySqlT(sql, s_params, tx) if err != nil { logging.Error("PostDataByName err: ", err) //appG.Response(http.StatusOK, e.ERROR, err.Error()) msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) } else { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } else { appG.Response(http.StatusOK, e.SUCCESS, nil) } } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags ExecDataByConfig // @Accept json // @Produce json // @Param sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/PostDataByName [POST] func ExecDataByConfig(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) tempval_ := make(map[string]interface{}) tempCommon := make(map[string]interface{}) tempval := make([]map[string]interface{}, 0) err := json.Unmarshal(dataByte, &tempval_) logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"]) if err != nil { fmt.Println("error:", err) } else { if v, ok := tempval_["common"].(map[string]interface{}); ok { tempCommon = v } if v, ok := tempval_["data"].([]interface{}); ok { for _, Tvalue := range v { if v1, ok := Tvalue.(map[string]interface{}); ok { tempval = append(tempval, v1) } } } tx, err := restful.Dbs.Beginx() if err != nil { logging.Error("tx.Begin 事务启动失败__error:", err) } defer func(tx *sqlx.Tx) { if err != nil { fmt.Println("__error:", err) if tx != nil { err := tx.Rollback() if err != nil { fmt.Println(err) } } } else { if tx != nil { err = tx.Commit() } } }(tx) //} if err == nil { if tempv, exists := c.Get("jwt_username"); exists { tempCommon["jwt_username"] = tempv.(string) } for _, paramvalue := range tempval { if _, ok := paramvalue["resultname"]; !ok { paramvalue["resultname"] = paramvalue["name"] } if paramvalue["name"] == "insertBigPartrefund" { if _, ok := paramvalue["parammaps"].(map[string]interface{})["buyeCode"]; ok { tx.Exec(` update bigrefunddetail set statu = 2 where buyeCode = ? `, paramvalue["parammaps"].(map[string]interface{})["buyeCode"]) } } _, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx) if err != nil { logging.Error("ExecDataParam error:", err) break } } if err == nil { vendor := restful.GetUserVendor(c.MustGet("jwt_username").(string)) err = NextService(tempval, tx, vendor) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) return } if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" { appG.Response(http.StatusOK, e.SUCCESS, tempval) } else { appG.Response(http.StatusOK, e.SUCCESS, "成功执行!") } } else { msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) } } } if err != nil { msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) //appG.Response(http.StatusOK, e.ERROR, err.Error()) } // 开协程 defer func() { if restful.GetUserVendor(c.MustGet("jwt_username").(string)) == 0 { go BillType(tempval_) } }() } func BillType(tempval_ map[string]interface{}) { var typein int switch tempval_["data"].(type) { case []interface{}: if len(tempval_["data"].([]interface{})) > 0 { name := tempval_["data"].([]interface{})[0].(map[string]interface{})["name"] switch name { case "insertBigPartlaid": billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["laidCode"] laidType := interfacetostringv2(tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["laidType"]) if laidType != "2" { typein = 1 } else { typein = 6 } _ = util.EASBillSync(typein, billcode, "") case "insertBigPartUse": billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["useForm"] usetypev := interfacetostringv2(tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["useType"]) if usetypev != "4" { typein = 2 } else { typein = 7 } _ = util.EASBillSync(typein, billcode, "") case "insertBigPartquit": billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["useForm"] _ = util.EASBillSync(3, billcode, "") case "PartRefundCharge1": billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["id"] statue := interfacetostringv2(tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["statue"]) if statue == "5" { _ = util.EASBillSync(4, billcode, "") } } } } } func interfacetostring(val interface{}) string { switch val.(type) { case string: ss := val.(string) return ss case int: ss := val.(int) return strconv.Itoa(ss) case int64: ss := val.(int64) return strconv.FormatInt(ss, 10) case float64: ss := val.(float64) return strconv.FormatFloat(ss, 'E', -1, 32) } return "" } func interfacetostringv2(val interface{}) string { switch val.(type) { case string: ss := val.(string) return ss case int: ss := val.(int) return strconv.Itoa(ss) case int64: ss := val.(int64) return strconv.FormatInt(ss, 10) case float64: ss := int(val.(float64)) return strconv.Itoa(ss) } return "" } func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string { if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok { tempstrb := strings.IndexAny(valuestring, "@") tempstre := strings.IndexAny(valuestring, ".") if tempstrb > -1 && tempstre > -1 { for _, ParamMapList := range ParamMap { if v, ok := ParamMapList["resultname"]; ok { if v == valuestring[tempstrb+1:tempstre] { if v1, ok := ParamMapList["resultmaps"]; ok { if newA, ok := v1.([]map[string]interface{}); ok { return interfacetostring(newA[0][valuestring[tempstre+1:]]) } else if newA, ok := v1.(map[string]interface{}); ok { return interfacetostring(newA[valuestring[tempstre+1:]]) } } } } } } else { return valuestring } } else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok { return strconv.FormatInt(int64(valuestring), 10) } return "" } func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string { if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok { tempstrb := strings.IndexAny(valuestring, "@") tempstre := strings.IndexAny(valuestring, ".") if tempstrb > -1 && tempstre > -1 { if v, ok := ParamMap[valuestring[tempstre+1:]]; ok { if s, ok := v.(string); ok { return s } else if s, ok := v.(float64); ok { return strconv.FormatInt(int64(s), 10) } } } } return "" } func ExecDataParam(fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, ParentParamMap map[string]interface{}, sameParamMap []map[string]interface{}, tx *sqlx.Tx) ([]map[string]interface{}, error) { sqlname := fasion["name"].(string) sqltype := "" //v 校验/s1 查询/sm 查询/e 执行 defer func() { if sqlname == "batchPartsSH" { id := "" switch ParentParamMap["id"].(type) { case float64: id = strconv.Itoa(int(ParentParamMap["id"].(float64))) case string: id = ParentParamMap["id"].(string) case int: id = strconv.Itoa(ParentParamMap["id"].(int)) } go util.EASBillSync(5, id, "1") //go CheckEASWebServiceParts("1",id) } }() if v, ok := fasion["type"]; ok { sqltype = v.(string) } sql := "" p := "" s_params := make([]interface{}, 0) if sqltype != "" { sql, p = restful.GetSqlByName(sqlname, nil) //sqlApi, _ := model.GetApisqlByName(sqlname) if v, ok := fasion["parammaps"].(map[string]interface{}); ok { paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { ss := "" if ss == "" && CommonParamMap != nil { if valuestring, ok := v[strings.Trim(value, " ")].(string); ok { ss = valuestring tempstrb := strings.IndexAny(valuestring, "@") tempstre := strings.IndexAny(valuestring, ".") if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") { if CommonParamMap[valuestring[tempstre+1:]] != nil { ss = CommonParamMap[valuestring[tempstre+1:]].(string) } } else { ss = "" } } } if ss == "" && ParentParamMap != nil { ss = getParamValue_(v, value, ParentParamMap) } if ss == "" && sameParamMap != nil { ss = getParamValue(v, value, sameParamMap) } if ss == "" && ParamMap != nil { ss = getParamValue(v, value, ParamMap) } s_params = append(s_params, ss) } } } } fmt.Println("=========") if sql == "" { sqltype = "" } if sqltype == "s1" { tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params) if v, ok := tempValParam.(map[string]interface{}); ok { fasion["resultmaps"] = v["list"].([]map[string]interface{}) } if err != nil { return nil, err } err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx) if err != nil { return nil, err } return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err } else if sqltype == "sm" { tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params) if v, ok := tempValParam.(map[string]interface{}); ok { fasion["resultmaps"] = v["list"].([]map[string]interface{}) } else { fmt.Println("sm", tempValParam) } if err != nil { return nil, err } err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx) if err != nil { return nil, err } return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err } else if sqltype == "v" { tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params) if v, ok := tempValParam.(map[string]interface{}); ok { fasion["resultmaps"] = v["list"].([]map[string]interface{}) } else { fmt.Println("v", tempValParam) } if err != nil { return nil, err } if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" { return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string)) } } else if sqltype == "e" { tempVal_arrary := make([]map[string]interface{}, 0) tempVal_map := make(map[string]interface{}) tempValParam, err := restful.ExecQueryT(sql, s_params, tx) if err == nil { fasion["resultmaps"] = tempValParam.(map[string]interface{}) tempVal_map["result"] = tempValParam.(map[string]interface{})["result"] tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"] tempVal_arrary = append(tempVal_arrary, tempVal_map) return tempVal_arrary, err } return nil, err } else { if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok { err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx) if err != nil { return nil, err } return nil, err } } return nil, nil } func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *sqlx.Tx) error { var err error subarray, ok := fasion["children"] if ok { for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据 tempVal_arrary := make([]map[string]interface{}, 0) for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令 tempVal_ := make(map[string]interface{}) if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok { tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"] } else { tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"] } tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行 if err != nil { return err } tempVal_arrary = append(tempVal_arrary, tempVal_) } v.(map[string]interface{})["children"] = tempVal_arrary } } return nil } // @Summary 删除图片 // @Tags RemovePicByName // @Accept json // @Produce json // @Param sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/PostDataByName [POST] func RemovePicByName(c *gin.Context) { logging.Info("RemovePicByName ", c.Keys) appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() picname := fsion.Get("picname").ValueStr() sql, _ := restful.GetSqlByNameDB(sqlnamestr) params := fsion.Get("params").Array() s_params := make([]interface{}, 0) for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } if sql != "" { queryData, err := execDataBySql(sql, s_params) if picname != "" { // Destination distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname) err := os.Remove(distPath) //删除文件test.txt if err != nil { //如果删除失败则输出 file remove Error! fmt.Println("file remove Error!") //输出错误详细信息 fmt.Printf("%s", err) } else { //如果删除成功则输出 file remove OK! fmt.Print("file remove OK!") } distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname) err = os.Remove(distPath) //删除文件test.txt if err != nil { //如果删除失败则输出 file remove Error! fmt.Println("file remove Error!") //输出错误详细信息 fmt.Printf("%s", err) } else { //如果删除成功则输出 file remove OK! fmt.Print("file remove OK!") } } if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) } else { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } else { appG.Response(http.StatusOK, e.SUCCESS, nil) } } // @Summary 删除文件 // @Tags RemoveFileByName // @Accept json // @Produce json // @Param sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/PostDataByName [POST] func RemoveFileByName(c *gin.Context) { appG := app.Gin{C: c} id := c.Param("id") logging.Info("DownloadFile ", c.Keys, id) eqdoc, err := restful.MapStrList("SELECT * FROM eq_doc where id = ? ", id) if eqdoc == nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) return } distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"]) err = os.Remove(distPath) //删除文件test.txt if err != nil { //如果删除失败则输出 file remove Error! fmt.Println("file remove Error!") //输出错误详细信息 fmt.Printf("%s", err) appG.Response(http.StatusOK, e.ERROR, err.Error()) return } fmt.Print("file remove OK!") _, err = restful.MapStrList("delete FROM eq_doc where id = ? ", id) if err != nil { log.Default().Printf("RemoveFileByName:%v", err) } appG.Response(http.StatusOK, e.SUCCESS, "OK") //dataByte, _ := ioutil.ReadAll(c.Request.Body) //fsion := gofasion.NewFasion(string(dataByte)) //sqlnamestr := fsion.Get("name").ValueStr() //filename := fsion.Get("filename").ValueStr() //sql, _ := restful.GetSqlByNameDB(sqlnamestr) //params := fsion.Get("params").Array() //s_params := make([]interface{}, 0) //for _, v_params := range params { // s_params = append(s_params, v_params.ValueStr()) //} //if sql != "" { // queryData, err := execDataBySql(sql, s_params) // // if filename != "" { // // Destination // distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename) // // err := os.Remove(distPath) //删除文件test.txt // if err != nil { // //如果删除失败则输出 file remove Error! // fmt.Println("file remove Error!") // //输出错误详细信息 // fmt.Printf("%s", err) // } else { // //如果删除成功则输出 file remove OK! // fmt.Print("file remove OK!") // } // } // if err != nil { // appG.Response(http.StatusOK, e.ERROR, err.Error()) // } else { // appG.Response(http.StatusOK, e.SUCCESS, "OK") // } //} else { // appG.Response(http.StatusOK, e.SUCCESS, nil) //} } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags PostDataByName // @Accept json // @Produce json // @Param sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/PostDataByName [POST] func UpdateDataRelation(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) tablename := fsion.Get("name").ValueStr() dataname := fsion.Get("dataname").ValueStr() datavalue := fsion.Get("datavalue").ValueStr() valuename := fsion.Get("valuename").ValueStr() logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename) values := fsion.Get("values").Array() tx, err := restful.Dbs.Beginx() defer func() { switch { case err != nil: fmt.Println("__error:", err) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } }() insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT ?, ? from DUAL " + " where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)" d_params := make([]interface{}, 4) d_params[0] = datavalue s_params := "" for _, v_values := range values { d_params[1] = v_values.ValueStr() if s_params == "" { s_params = v_values.ValueStr() } else { s_params = s_params + "," + v_values.ValueStr() } d_params[2] = d_params[1] d_params[3] = d_params[0] _, err := execDataBySqlT(insertSqlstr, d_params, tx) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) break } } if s_params != "" { deleteSqlstr := "delete from " + tablename + " " + " where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")" queryData, err := execDataBySqlT(deleteSqlstr, nil, tx) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) } else if err == nil { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } else { deleteSqlstr := "delete from " + tablename + " " + " where " + dataname + " = " + datavalue queryData, err := execDataBySqlT(deleteSqlstr, nil, tx) if err != nil { appG.Response(http.StatusOK, e.ERROR, err.Error()) } else if err == nil { appG.Response(http.StatusOK, e.SUCCESS, queryData) } } } // @Summary 根据APISQL表中SQL执行得到数据集 // @Tags PostDatasByName // @Accept json // @Produce json // @Param sqlname query string true "sqlname" // @Param offset query int true "offset" // @Param pagecount query int true "pagecount" // @Param returntype query string true "returntype" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/PostDatasByName [POST] func PostDataByNames(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlParams := fsion.Get("array").Array() queryData := make(map[string]interface{}) for _, v := range sqlParams { fsion2 := gofasion.NewFasion(v.Json()) logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr()) sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr()) if sql == "" { errorm := make(map[string]interface{}) errorm["code"] = e.ERROR errorm["message"] = "sql没有找到" errorm["param"] = "" queryData[fsion2.Get("name").ValueStr()] = errorm continue } else if sql != "" { s_params := make([]interface{}, 0) if fsion2.HasKey("parammaps") { parammaps := fsion2.Get("parammaps") paramslist := strings.Split(p, ",") if len(paramslist) > 0 && p != "" { for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr()) } } } } else if fsion2.HasKey("params") { params := fsion2.Get("params").Array() for _, v_params := range params { s_params = append(s_params, v_params.ValueStr()) } } _, err := execDataBySql(sql, s_params) if err != nil { logging.Error("PostDataByName err: ", err) errorm := make(map[string]interface{}) errorm["code"] = e.ERROR errorm["message"] = err.Error() errorm["msg"] = "fail" errorm["param"] = s_params queryData[fsion2.Get("name").ValueStr()] = errorm continue } else { errorm := make(map[string]interface{}) errorm["code"] = e.SUCCESS errorm["message"] = "success" errorm["msg"] = "ok" queryData[fsion2.Get("name").ValueStr()] = errorm continue } } else { errorm := make(map[string]interface{}) errorm["code"] = e.ERROR errorm["message"] = "NO SQL" errorm["param"] = "" queryData[fsion2.Get("name").ValueStr()] = errorm } } //appG.Response(http.StatusOK, e.SUCCESS, msg) appG.Response(http.StatusOK, e.SUCCESS, queryData) } func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) { if offset > 0 { offset = offset - 1 } if returntype == "list" { queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params) return queryData, err } else if returntype == "listlist" { queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params) return queryData, err } else { queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params) return queryData, err } } // func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *sqlx.Tx) (interface{}, error) { func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) { if offset > 0 { offset = offset - 1 } if returntype == "list" { // queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx) queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params) return queryData, err } else if returntype == "listlist" { // queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx) queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params) return queryData, err } else { // queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx) queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params) return queryData, err } } func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) { paramslist := strings.Split(Params, ",") s_params := make([]interface{}, 0) if isList { for _, v_params := range thisParams["params"].([]interface{}) { s_params = append(s_params, v_params) } } else { paramslist := strings.Split(Params, ",") if len(paramslist) > 0 && Params != "" { for _, value := range paramslist { s_params = append(s_params, thisParams[strings.Trim(value, " ")]) } } } queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params) for _, queryData_ := range queryData { if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok { if isList { //fmt.Println(idname, "-------------- -queryData_[idname]", queryData_) if queryData_[idname] != nil { thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{}) } } else { if queryData_[idname] != nil { thisParams[idname] = queryData_[idname].(interface{}) } if len(paramslist) > 0 && Params != "" { s_params = make([]interface{}, 0) for _, value := range paramslist { s_params = append(s_params, thisParams[strings.Trim(value, " ")]) } } } queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList) } else { } } return queryData, err } func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) { queryData, err := restful.ExecQuery(sqlstr, params) return queryData, err } func execDataBySqlT(sqlstr string, params []interface{}, tx *sqlx.Tx) (interface{}, error) { queryData, err := restful.ExecQueryT(sqlstr, params, tx) return queryData, err } func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) { queryData, err := restful.ExecQuery(sqlstr, params) return queryData, err } // @Summary 导入excel文件到数据库,excel第一行作为参数 // @Tags ImportExcel // @Accept json // @Produce json // @Param file query string true "文件名" // @Param name header string true "执行sql的名字" // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }" // @Failure 400 {string} json "{"code":400, "data":null,"msg":"请求参数错误"}" // @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}" // @Router /data/ImportExcel [POST] // @param 备件编号,备件名称,规格型号,计量单位,品牌,计划量,单价,备注,jwt_username // func ImportExcel(c *gin.Context) { // log.Default().Println("Importing Excel================================") // appG := app.Gin{C: c} // file, _, err := c.Request.FormFile("file") // if err != nil { // logrus.Errorf("request.FormFile: %v", err) // appG.Response(http.StatusOK, e.ERROR, err) // return // } // xlsx1, err := excelize.OpenReader(file) // if err != nil { // logrus.Errorf("excelize.OpenReader: %v", err) // appG.Response(http.StatusOK, e.ERROR, err) // return // } // c.Request.ParseForm() // params := c.Request.Form // sheetname := params.Get("sheetname") // rows := xlsx1.GetRows(sheetname) // importParams := params.Get("importParams") // paramslist := strings.Split(importParams, ",") // sqlnamestr := params.Get("name") // sql, _ := restful.GetSqlByNameDB(sqlnamestr) // inputdata := "" // ok := 0 // error := 0 // queryData := make([]interface{}, 0) // data := make(map[string]interface{}) // if len(rows) > 10000 { // rows = rows[:10000] // } // if len(rows) <= 1 { // logrus.Errorln("表格为空") // appG.Response(http.StatusOK, e.ERROR, errors.New("表格为空")) // return // } // if len(rows[0]) < len(paramslist) { // logrus.Errorln("表格缺少数据列") // appG.Response(http.StatusOK, e.ERROR, errors.New("表格缺少数据列")) // return // } // for i, v := range paramslist { // if strings.Trim(rows[0][i], " ") != v { // logrus.Errorln("表格数据列顺序不符合标准,或标题名称错误") // appG.Response(http.StatusOK, e.ERROR, errors.New("表格数据列顺序不符合标准,或标题名称错误")) // return // } // } // for _, row := range rows[1:] { // s_params := make([]interface{}, 0) // outentry := make(map[string]interface{}) // for i := range row { // row[i] = strings.TrimSpace(row[i]) // s_params = append(s_params, row[i]) // } // uname := "" // if tempv, b := c.Get("jwt_username"); b { // uname = tempv.(string) // } // s_params = append(s_params, uname) // outentry["input"] = inputdata // log.Default().Printf("params=%v", s_params...) // returnmsg, err := getDataBySql(sql, 0, 0, "4", s_params) // returnmsgmap, _ := returnmsg.(map[string]interface{}) // returnmsgmap1, _ := returnmsgmap["list"].([]map[string]interface{}) // if err != nil { // outentry["error_msg"] = err.Error() // error++ // queryData = append(queryData, outentry) // } else if (len(returnmsgmap1) > 0) && (returnmsgmap1[0]["msg"] == "success") { // ok++ // } else { // msg := geterrmsg(returnmsgmap1[0]["msg"].(string)) // outentry["error_msg"] = msg // error++ // queryData = append(queryData, outentry) // } // } // data["result"] = queryData // data["success"] = ok // data["err_count"] = error // appG.Response(http.StatusOK, e.SUCCESS, data) // } func ImportExcel(c *gin.Context) { appG := app.Gin{C: c} inputdata := "" if err := c.Request.ParseForm(); err != nil { log.Default().Printf("request.parseform:%v", err) appG.Response(http.StatusOK, e.ERROR, err) return } params := c.Request.Form // file, _, err := c.Request.FormFile("file") fileHeader, err := c.FormFile("file") file, err := fileHeader.Open() if err != nil { log.Default().Printf("multipart.FileHeader.open:%v", err) appG.Response(http.StatusOK, e.ERROR, err) return } if err != nil { log.Default().Printf("request.FormFile: %v", err) appG.Response(http.StatusOK, e.ERROR, err) return } sqlnamestr := params.Get("name") sheetname := params.Get("sheetname") importParams := params.Get("importParams") sql, _ := restful.GetSqlByNameDB(sqlnamestr) // 备件编号,备件名称,规格型号,计量单位,品牌,计划量,单价,备注,jwt_username paramslist := strings.Split(importParams, ",") if sqlnamestr != "importGasoline" && sqlnamestr != "importCoal" && sqlnamestr != "importBiomass" && sqlnamestr != "importEnergy" { paramslist = append(paramslist, "jwt_username") } queryData := make([]interface{}, 0) xlsx1, err := excelize.OpenReader(file) if err != nil { log.Default().Printf("excelize.OpenReader:%v", err) return } ok := 0 error := 0 rows := xlsx1.GetRows(sheetname) if len(rows) > 10000 { rows = rows[:10000] } for i, row := range rows { if i > 0 { if len(paramslist) > 0 { s_params := make([]interface{}, 0) entry := make(map[string]interface{}) outentry := make(map[string]interface{}) inputdata = "" for _, value := range paramslist { if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" { if tempv, exists := c.Get("jwt_username"); exists { s_params = append(s_params, tempv.(string)) } else { s_params = append(s_params, "") } } else { for j, colCell := range rows[0] { if strings.Trim(value, " ") == colCell { for k, colCell1 := range row { if j == k { outentry[colCell] = colCell1 entry[colCell] = colCell1 //inputdata = inputdata + colCell + ":" + colCell1 + ";" } } } } s_params = append(s_params, entry[strings.Trim(value, " ")]) } } outentry["input"] = inputdata returnmsg, err := getDataBySql(sql, 0, 0, "4", s_params) returnmsgmap, _ := returnmsg.(map[string]interface{}) returnmsgmap1, _ := returnmsgmap["list"].([]map[string]interface{}) log.Default().Printf("return:%v", returnmsgmap) if err != nil { outentry["error_msg"] = err.Error() error++ queryData = append(queryData, outentry) } else if (len(returnmsgmap1) > 0) && (returnmsgmap1[0]["msg"] == "success") { ok++ } else { error++ msg := "" if len(returnmsgmap1) > 0 && returnmsgmap1[0]["msg"] != nil { msg = geterrmsg(returnmsgmap1[0]["msg"].(string)) } outentry["error_msg"] = msg queryData = append(queryData, outentry) } } } } data := make(map[string]interface{}) data["result"] = queryData data["success"] = ok data["err_count"] = error appG.Response(http.StatusOK, e.SUCCESS, data) } func DownloadMailReport(context *gin.Context) { dataByte, _ := ioutil.ReadAll(context.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) //filename := context.Param("filename") sqlnamestr := fsion.Get("name").ValueStr() pastureId := fsion.Get("pastureId").ValueStr() pastureName := fsion.Get("pastureName").ValueStr() date := fsion.Get("date").ValueStr() filepath := "" if sqlnamestr == "DownloadMailReportJY" { filepath, _ = util.DownloadDataJT(date) } else if sqlnamestr == "DownloadMailReportMC" { filepath, _ = util.DownloadDataMC(pastureName, date, pastureId) } else if sqlnamestr == "sssss" { // 平时用来拉数据的 util.Sssss() } else if sqlnamestr == "DownloadEquipment" { // 设备指标导出方法 parammaps := fsion.Get("parammaps").ValueStr() filepath, _ = util.DownloadEquipment(parammaps) } if filepath == "" { http.NotFound(context.Writer, context.Request) return } originFilePath := filepath //println("originFilePath==========",originFilePath) if fs.PathExists(originFilePath) == false { // if the path not found http.NotFound(context.Writer, context.Request) return } http.ServeFile(context.Writer, context.Request, originFilePath) } // 资产标准管理判断牧场是否有选择的该部门 func PastureDepartment(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) paramMap := fsion.Get("param") ids := paramMap.Get("ids").ValueStr() deptName := paramMap.Get("deptName").ValueStr() idList := strings.Split(ids, ",") checkDeptList := make([]map[string]interface{}, 0) for _, v := range idList { aa, _ := strconv.Atoi(v) data, err := restful.MapStrList("select * from department where pastureId=? and name=? and enable=1 and isDel=0 and isPasture=0", aa, deptName) if err != nil { fmt.Println(err) } else { list := make(map[string]interface{}, 1) if len(data) == 0 { list["id"] = v list["enable"] = 0 } else { list["id"] = v list["enable"] = 1 } checkDeptList = append(checkDeptList, list) } } appG.Response(http.StatusOK, e.SUCCESS, checkDeptList) } // { 'label': '汶上', 'property': 'm1' } // 资产标准管理 func Equipment(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) deptName := fsion.Get("deptName").ValueStr() eqClassId := fsion.Get("eqClassId").ValueStr() offset := fsion.Get("offset").ValueDefaultInt(0) pagecount := fsion.Get("pagecount").ValueDefaultInt(0) dataList := make([]interface{}, 0) pastureData, err := restful.MapStrList("select p.`name`,p.id from pasture p group by p.`name`") str := "select eqS.id,eqS.deapartmentName deptName, eqS.`use`,eqclass.`typeName`,p.`name`,p.id pastureId ,eqS.eqClassId " + " from equipment_standard eqS" + " left join pasture p on p.id= eqS.pastureId" + " left join eqclass on eqclass.id=eqS.eqClassId " + " where (eqS.deapartmentName = :deptName or :deptName ='') and " + " (eqS.eqClassId = :eqClassId or :eqClassId ='') " + " group by deptName,eqClassId " + " ORDER BY eqS.id DESC" offset = offset - 1 if pagecount > 0 && offset > 0 { offset = offset * pagecount } paramMap_3_6 := map[string]interface{}{"deptName": deptName, "eqClassId": eqClassId} str += fmt.Sprintf("limit %d offset %d", pagecount, offset) equipmentStandardData1, err := restful.MapStrList(str, paramMap_3_6) //数据 equipmentStandardData2, err := restful.MapStrList("select eqS.deapartmentName deptName, eqS.id eqSId,eqS.equipmentNumber,p.`name`,p.id pastureId,eqS.eqClassId"+ " from equipment_standard eqS"+ " left join pasture p on p.id= eqS.pastureId "+ " left join eqclass eqc on eqc.id=eqS.eqClassId "+ "where (eqS.deapartmentName =? or ?='') and"+ " (eqS.eqClassId = ? or ?='') ", deptName, deptName, eqClassId, eqClassId) sqlstr := str params := make([]interface{}, 0) for i := 0; i < 2; i++ { param := make(map[string]interface{}, 0) param["deptName"] = deptName param["eqClassId"] = eqClassId params = append(params, param) } label := make([]map[string]interface{}, 0) if err != nil { fmt.Println(err) } else { for i, v := range pastureData { pasturelist := make(map[string]interface{}, 1) pasturelist["label"] = v["name"] pasturelist["id"] = v["id"] pasturelist["property"] = "m" + strconv.Itoa(i+1) label = append(label, pasturelist) } label2 := make([]map[string]interface{}, 0) for _, s := range equipmentStandardData1 { equipmentStandardList := make(map[string]interface{}, 1) for i := 1; i <= len(label); i++ { equipmentStandardList["m"+strconv.Itoa(i)] = "" } equipmentStandardList["deptName"] = s["deptName"] equipmentStandardList["use"] = s["use"] equipmentStandardList["typeName"] = s["typeName"] equipmentStandardList["eqClassId"] = s["eqClassId"] for _, z := range equipmentStandardData2 { for e, x := range label { if s["deptName"] == z["deptName"] && x["label"] == z["name"] && s["eqClassId"] == z["eqClassId"] { equipmentStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"] equipmentStandardList[x["property"].(string)] = z["equipmentNumber"] } else { equipmentStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"] } } } label2 = append(label2, equipmentStandardList) } if err != nil { msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) } else { dataList = append(dataList, label) dataList = append(dataList, label2) data := make(map[string]interface{}) recordcount := int64(0) if pagecount > 1 { sqlstr := fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", sqlstr) params := []interface{}{deptName, deptName, eqClassId, eqClassId} err := restful.BasicList(sqlstr, params, &recordcount) if err != nil { log.Default().Printf("Equipment query error: %v", err) } } if err != nil { fmt.Println(err) } if recordcount == 0 { recordcount = int64(len(equipmentStandardData1)) } data["list"] = dataList //data := make(map[string]interface{}) data["total"] = recordcount data["code"] = 0 data["message"] = "ok" if pagecount > 0 { data["pages"] = math.Ceil(float64(recordcount) / float64(pagecount)) data["pageNum"] = math.Ceil(float64(offset+1) / float64(pagecount)) } data["pageSize"] = pagecount appG.Response(http.StatusOK, e.SUCCESS, data) } } } // 资产标准管理插入修改写在一起 func UpdateAndInsert(c *gin.Context) { appG := app.Gin{C: c} data := make(map[string]interface{}, 0) dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) param := fsion.Get("param") check := fsion.Get("check").ValueStr() tx, err := restful.Dbs.Beginx() deptName := param.Get("deptName").ValueStr() eqCode := param.Get("eqCode").ValueStr() eqClassId, err := strconv.Atoi(param.Get("eqClassId").ValueStr()) use := param.Get("use").ValueStr() paramStr := fsion.Get("param").ValueStr() paramMap := make(map[string]interface{}, 0) err = json.Unmarshal([]byte(paramStr), ¶mMap) fmt.Println(len(paramMap)) fmt.Println(paramMap) // 标准库存 name := fsion.Get("name").ValueStr() partClassId, err := strconv.Atoi(param.Get("partClassId").ValueStr()) ff := 0 if check == "insert" { querydata := make([]map[string]string, 0) if name == "partStandard" { ff = 2 querydata, err = restful.MapStrList(" select * from part_standard where partClassId2 =? ", partClassId) if querydata != nil { //data["msg"]="请不输入重复数据" msg := geterrmsg("请不输入重复数据") appG.Response(http.StatusOK, e.ERROR, msg) return } } else { ff = 4 querydata, err = restful.MapStrList(" select * from equipment_standard where eqClassId =? and deapartmentName = ?", eqClassId, deptName) if querydata != nil { //data["msg"]="请不输入重复数据" msg := geterrmsg("请不输入重复数据") appG.Response(http.StatusOK, e.ERROR, msg) return } } for i := 1; i <= (len(paramMap)-ff)/2; i++ { pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr()) if err != nil { } if name == "partStandard" { if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" { tx.Exec("call add_part_standard(?,?,?)", partClassId, pastureId, param.Get("m"+strconv.Itoa(i))) } } else { if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" { tx.Exec("call add_equipment_standard(?,?,?,?,?,?)", deptName, use, eqClassId, pastureId, param.Get("m"+strconv.Itoa(i)).ValueStr(), eqCode) } } } if err != nil { } } if check == "update" { if name == "partStandard" { ff = 2 tx.Exec("delete from part_standard where partClassId2 =?", partClassId) for i := 1; i <= (len(paramMap)-ff)/2; i++ { pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr()) if err != nil { } if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" { tx.Exec("call add_part_standard(?,?,?)", partClassId, pastureId, param.Get("m"+strconv.Itoa(i)).ValueStr()) } } } else { ff = 4 tx.Exec("delete from equipment_standard where deapartmentName=? and eqClassId=?", deptName, eqClassId) for i := 1; i <= (len(paramMap)-ff)/2; i++ { pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr()) if err != nil { } if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" { tx.Exec("call add_equipment_standard(?,?,?,?,?,?)", deptName, use, eqClassId, pastureId, param.Get("m"+strconv.Itoa(i)).ValueStr(), eqCode) // " WHERE deapartmentName=? and pastureId = ? and eqClassId=?", use, param.Get("m"+strconv.Itoa(i)).ValueStr(), deptName, pastureId,eqClassId).Execute() } } } if err != nil { data["msg"] = "error" data["error"] = err.Error() appG.Response(http.StatusOK, e.SUCCESS, data) } } if check == "delete" { if name == "partStandard" { for i := 1; i <= (len(paramMap)-ff)/2; i++ { pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr()) if err != nil { } tx.Exec("delete from part_standard where pastureId=? and partClassId2=?", pastureId, partClassId) } } else { ff = 4 for i := 1; i <= (len(paramMap)-ff)/2; i++ { pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr()) if err != nil { } tx.Exec("delete from equipment_standard where deapartmentName=? and pastureId=? and eqClassId=?", deptName, pastureId, eqClassId) } } } data["msg"] = "ok" appG.Response(http.StatusOK, e.SUCCESS, data) defer func() { switch { case err != nil: logging.Error("tx.Begin 事务启动失败__error:", err) if tx != nil { tx.Rollback() } default: if tx != nil { err = tx.Commit() } } }() } func StandardPart(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) partClassId := fsion.Get("partClassId").ValueStr() offset := fsion.Get("offset").ValueDefaultInt(0) pagecount := fsion.Get("pagecount").ValueDefaultInt(0) pastureData, err := restful.MapStrList("select p.`name`,p.id from pasture p group by p.`name`") //s_params := make([]interface{}, 0) offset = offset - 1 if pagecount > 0 && offset > 0 { offset = offset * pagecount } dataList := make([]interface{}, 0) label := make([]map[string]interface{}, 0) str := "select p_c.partName,p.`name`,p_s.pastureId,p_s.partClassId2 from part_standard p_s left join part_class p_c on p_c.id= p_s.partClassId2 " + " left join pasture p on p.id = p_s.pastureId where p_s.partClassId2 = ? or ?='' " + " GROUP BY p_s.partClassId2 ORDER BY p_s.id DESC" str1 := "select p_s.standardMoney,p_s.partClassId2,p_s.pastureId,p.`name` from part_standard p_s left join pasture p on p.id=p_s.pastureId where p_s.partClassId2 = ? or ?=''" str += fmt.Sprintf(" limit %d offset %d", pagecount, offset) partStandardData1, err := restful.MapStrList(str, partClassId, partClassId) //数据 partStandardData2, err := restful.MapStrList(str1, partClassId, partClassId) if err != nil { fmt.Println(err) } else { for i, v := range pastureData { pasturelist := make(map[string]interface{}, 1) pasturelist["label"] = v["name"] pasturelist["id"] = v["id"] pasturelist["property"] = "m" + strconv.Itoa(i+1) label = append(label, pasturelist) } label2 := make([]map[string]interface{}, 0) //equipmentStandardList := make(map[string]interface{}, 1) for _, s := range partStandardData1 { partStandardList := make(map[string]interface{}, 1) for i := 1; i <= len(label); i++ { partStandardList["m"+strconv.Itoa(i)] = "" } partStandardList["partClassId"] = s["partClassId2"] partStandardList["partName"] = s["partName"] for _, z := range partStandardData2 { for e, x := range label { if x["label"] == z["name"] && s["partClassId2"] == z["partClassId2"] { partStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"] //equipmentStandardList["eqSId"+strconv.Itoa(e+1)] = z["eqSId"] partStandardList[x["property"].(string)] = z["standardMoney"] } else { partStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"] } } } label2 = append(label2, partStandardList) } if err != nil { //logging.Error("GetDataByName err: ", err) msg := geterrmsg(err.Error()) appG.Response(http.StatusOK, e.ERROR, msg) } else { dataList = append(dataList, label) dataList = append(dataList, label2) fmt.Println(label2) data := make(map[string]interface{}) recordcount := int64(0) if pagecount > 1 { sqlstr := fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", str) params := []interface{}{partClassId, partClassId} restful.BasicList(sqlstr, params, &recordcount) if err != nil { fmt.Println("s1", err) } } if err != nil { fmt.Println(err) } if recordcount == 0 { recordcount = int64(len(partStandardData1)) } data["list"] = dataList //data := make(map[string]interface{}) data["total"] = recordcount data["code"] = 0 data["message"] = "ok" if pagecount > 0 { data["pages"] = math.Ceil(float64(recordcount) / float64(pagecount)) data["pageNum"] = math.Ceil(float64(offset+1) / float64(pagecount)) } data["pageSize"] = pagecount //pageNum: 1 pageSize: 10 pages: 202 total: 2019 //data["pageNum"]=queryData //data["pageNum"]=queryData["pageNum"] appG.Response(http.StatusOK, e.SUCCESS, data) } } } func GetMtbfTable(c *gin.Context) { appG := app.Gin{C: c} //dataByte, _ := ioutil.ReadAll(c.Request.Body) //fsion := gofasion.NewFasion(string(dataByte)) data := make(map[string]interface{}) data["name"] = "epans" data["userId"] = "99" appG.Response(http.StatusOK, e.SUCCESS, data) } func GetPartsListSGv2(c *gin.Context) { appG := app.Gin{C: c} dataByte, _ := ioutil.ReadAll(c.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) sqlnamestr := fsion.Get("name").ValueStr() params := fsion.Get("parammaps") pastureId := params.Get("pastureId").ValueStr() pastureName := params.Get("pastureName").ValueStr() partCode := params.Get("partCode").ValueStr() sql, _ := restful.GetSqlByNameDBT(sqlnamestr, nil) partList, err := restful.MapStrList(sql, partCode, pastureId, pastureId, partCode, pastureId, partCode, partCode) if err != nil { logs.Error(err) appG.Response(http.StatusInternalServerError, e.ERROR, false) return } pastureSql := `select id from pasture_bigcontract where bigcontract_id in(select id from bigcontract where contractCode like concat("%",?,"%")) and pasture_id = ? union select id from bigcontract where contractCode like concat("%",?,"%") and pastureId = ? ` var prices []string var priceExist []string resp := make(map[string]string) for _, part := range partList { pastureBigcontract, err := restful.MapStrList(pastureSql, part["contractCode"], pastureId, part["contractCode"], pastureId) if err != nil { logs.Error(err) appG.Response(http.StatusInternalServerError, e.ERROR, false) return } if len(pastureBigcontract) > 0 { //partMap[part["contractCode"]] = true priceExist = append(priceExist, part["price"]) part["price"] = "" resp = part } else { //partMap[part["contractCode"]] = false prices = append(prices, part["price"]) } } partMap := make(map[string]int64) for i, p := range priceExist { if _, ok := partMap[p]; !ok { partMap[p] = partMap[p] + 1 if i == 0 { resp["price"] = fmt.Sprintf("%s %s ", pastureName, p) } else { resp["price"] = fmt.Sprintf("%s ,%s %s ", resp["price"], pastureName, p) } } } for _, p := range prices { if _, ok := partMap[p]; !ok { partMap[p] = partMap[p] + 1 if len(resp["price"]) > 0 { resp["price"] = fmt.Sprintf("%s ,现价格 %s ", resp["price"], p) } else { resp["price"] = fmt.Sprintf("现价格 %s ", p) } } } appG.Response(http.StatusOK, e.SUCCESS, map[string]interface{}{"list": []map[string]string{resp}}) } func GetWaterAndElectricity(context *gin.Context) { appG := app.Gin{C: context} dataByte, _ := ioutil.ReadAll(context.Request.Body) fsion := gofasion.NewFasion(string(dataByte)) //filename := context.Param("filename") sqlnamestr := fsion.Get("name").ValueStr() pastureName := fsion.Get("pastureId").ValueStr() //pastureName := fsion.Get("pasture").ValueStr() //date := fsion.Get("date").ValueStr() parammap := fsion.Get("parammaps") logging.Info("DownloadMailReport ", context.Keys, sqlnamestr, pastureName) sqlnamesDepartment := []string{} ///"维修费","水费","电费","柴油费","水量","电量","柴油用量" if pastureName == "现代牧业" { sqlnamesDepartment = []string{ "getChooseWaterPrice", "getChooseElectricityPrice", "getChooseMonthiolPrice"} } else { sqlnamesDepartment = []string{ "getChooseWaterPriceByPasture", "getChooseElectricityPriceByPasture", "getChooseMonthiolPriceByPasture"} } //if pastureId == "现代牧业" { // sqlnames = []string{"getChooseEqMonthBudgetListSumAll", "getChooseMonthWX", "getChooseWaterPrice", "getChooseElectricityPrice", "getChooseMonthiolPrice", // "getChooseMonthWater", "getChooseMonthElectricity", "getChooseMonthOilT", "getLgnitionChargePrice", "getChooseBiomassPrice", "getChooseGasolinePrice", // "getChooseCoalPrice"} //} else { // sqlnames = []string{"getChooseEqMonthBudgetListSumAllByPasture", "getChooseMonthWXByPasture", "getChooseWaterPriceByPasture", "getChooseElectricityPriceByPasture", "getChooseMonthiolPriceByPasture", // "getChooseMonthWaterByPasture", "getChooseMonthElectricityByPasture", "getChooseMonthOilTByPasture", "getLgnitionChargePriceByPasture", "getChooseBiomassPriceByPasture", "getChooseGasolinePriceByPasture", // "getChooseCoalPriceByPasture"} //} respMapList := make([]map[string]string, 0) for _, sqlname := range sqlnamesDepartment { valuesMap, err := restful.MapStr("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", sqlname) //parammap := make(map[string]interface{}, 0) s_params := make([]interface{}, 0) paramslist := strings.Split(valuesMap["params"], ",") if len(paramslist) > 0 && valuesMap["params"] != "" { for _, value := range paramslist { if value == "pastureId" && parammap.Get("pastureId").ValueStr() == "" { s_params = append(s_params, "现代牧业") continue } s_params = append(s_params, parammap.Get(strings.Trim(value, " ")).ValueStr()) } } values, err := restful.MapStrList(valuesMap["sqlstr"], s_params...) if err != nil { fmt.Println(err) } else { for _, v := range values { exist := false for _, item := range respMapList { if item["pastureName"] == v["pastureName"] { exist = true if sqlname == "getChooseWaterPrice" || sqlname == "getChooseWaterPriceByPasture" { item["waterOneCowSumPrice"] = v["oneCowSumPrice"] item["waterSumPrice"] = v["sumPrice"] } else if sqlname == "getChooseElectricityPrice" || sqlname == "getChooseElectricityPriceByPasture" { item["electricityOneCowSumPrice"] = v["oneCowSumPrice"] item["electricitySumPrice"] = v["sumPrice"] } else if sqlname == "getChooseMonthiolPrice" || sqlname == "getChooseMonthiolPriceByPasture" { item["monthiolOneCowSumPrice"] = v["oneCowSumPrice"] item["monthiolSumPrice"] = v["sumPrice"] } break } } if !exist { respMap := make(map[string]string, 0) respMap["pastureName"] = v["pastureName"] if sqlname == "getChooseWaterPrice" || sqlname == "getChooseWaterPriceByPasture" { respMap["waterOneCowSumPrice"] = v["oneCowSumPrice"] respMap["waterSumPrice"] = v["sumPrice"] } else if sqlname == "getChooseElectricityPrice" || sqlname == "getChooseElectricityPriceByPasture" { respMap["electricityOneCowSumPrice"] = v["oneCowSumPrice"] respMap["electricitySumPrice"] = v["sumPrice"] } else if sqlname == "getChooseMonthiolPrice" || sqlname == "getChooseMonthiolPriceByPasture" { respMap["monthiolOneCowSumPrice"] = v["oneCowSumPrice"] respMap["monthiolSumPrice"] = v["sumPrice"] } respMapList = append(respMapList, respMap) } } } } appG.Response(http.StatusOK, e.SUCCESS, map[string]interface{}{"data": respMapList}) }