12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562 |
- package api
- import (
- "fmt"
- "io/ioutil"
- "log"
- "math"
- "net/http"
- "sort"
- "strconv"
- "strings"
- "../../utils"
- "../../pkg/app"
- "../../pkg/e"
- "../../routers/restful"
- "github.com/Anderson-Lu/gofasion/gofasion"
- "github.com/gin-gonic/gin"
- "github.com/tealeg/xlsx"
- )
- func GetProductAreas(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- productname := parammaps.Get("productname").ValueStr()
- classids := parammaps.Get("productclassid").ValueStr()
- var recordcount int64 = 0
- queryData := make([]map[string]interface{}, 1)
- var err error
- tx := restful.Engine.NewSession()
- defer tx.Close()
- {
- sqlstr := `SELECT t1.id,t1.productname,t1.spec FROM productinfo t1
- INNER JOIN prounit t2 ON t1.prounit = t2.id where 1=1 and t1.enable = 1 `
- if len(classids) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productclass in ('%s')", classids)
- }
- if len(productname) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productname like ('%s')", "%"+productname+"%")
- }
- tt, err := tx.SQL(sqlstr).Query().Count()
- if err != nil {
- log.Println("GetProductAreas-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- recordcount = int64(tt)
- }
- if pagecount == 0 {
- sqlstr := `SELECT t1.id as productid,t1.productname,ifnull(t1.spec,"") as specifications,ifnull(t2.unitname,"") as unit
- FROM productinfo t1
- INNER JOIN prounit t2 ON t1.prounit = t2.id where 1=1 and t1.enable = 1 `
- if len(classids) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productclass in ('%s')", classids)
- }
- if len(productname) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productname like ('%s')", "%"+productname+"%")
- }
- query := tx.SQL(sqlstr)
- queryData, err = query.Query().List()
- if err != nil {
- log.Println("GetProductAreas-err2: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- } else {
- sqlstr := `SELECT t1.id as productid,t1.productname,ifnull(t1.spec,"") as specifications,ifnull(t2.unitname,"") as unit
- FROM productinfo t1
- INNER JOIN prounit t2 ON t1.prounit = t2.id where 1=1 and t1.enable = 1 `
- if len(classids) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productclass in ('%s')", classids)
- }
- if len(productname) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productname like ('%s')", "%"+productname+"%")
- }
- queryData, err = tx.SQL(sqlstr).Limit(pagecount, (offset-1)*pagecount).Query().List()
- if err != nil {
- log.Println("GetProductAreas-err3: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- }
- headlist := make([]map[string]interface{}, 0)
- areaData := make([]map[string]interface{}, 0)
- {
- sqlstr := `SELECT
- t1.id AS productareaid,
- t1.AreaId as areaid,
- t2.name,
- t1.Productid as productid
- FROM
- productarea t1
- INNER JOIN canton t2 ON t1.AreaId = t2.ID order by areaid`
- areaData, err = tx.SQL(sqlstr).Query().List()
- if err != nil {
- log.Println("GetProductAreas-err4: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- areaMap := make(map[interface{}]interface{})
- contactlistMap := make(map[interface{}][]interface{})
- for _, area := range areaData {
- areaMap[area["areaid"]] = area["name"]
- contactlistMap[area["productid"]] = append(contactlistMap[area["productid"]], area["areaid"])
- }
- areaids := []int64{}
- for areaid, _ := range areaMap {
- areaids = append(areaids, areaid.(int64))
- }
- utils.QuickSort(areaids, 0, int64(len(areaids)-1))
- for _, v := range areaids {
- head := make(map[string]interface{})
- head["column_name"] = fmt.Sprintf("column%v", v)
- head["column_title"] = areaMap[v]
- head["column_id"] = v
- headlist = append(headlist, head)
- }
- for _, data := range queryData {
- for id, _ := range areaMap {
- data[fmt.Sprintf("column%v", id)] = 0
- }
- if _, ok := contactlistMap[data["productid"]]; ok {
- for _, areaid := range contactlistMap[data["productid"]] {
- data[fmt.Sprintf("column%v", areaid)] = 1
- }
- }
- }
- }
- data := make(map[string]interface{})
- data["headlist"] = headlist
- data["list"] = queryData
- 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 GetPublishPrice(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- productclass := parammaps.Get("productclassid").ValueInt64()
- date := parammaps.Get("starttime").ValueStr()
- productname := parammaps.Get("productname").ValueStr()
- data := make(map[string]interface{})
- var err error
- queryData := make([]map[string]interface{}, 0)
- var recordcount int
- tx := restful.Engine.NewSession()
- defer tx.Close()
- {
- sqlstr := `select t1.id as productid,t1.productname,t1.productclass,ifnull(t1.spec,"") as specifications ,ifnull(t2.unitname,"") as unitname from productinfo t1
- join prounit t2 on t2.id = t1.prounit where 1=1 and t1.enable = 1 `
- var args []interface{}
- if productclass > 0 {
- sqlstr += " and t1.productclass = ?"
- args = append(args, productclass)
- }
- if len(productname) > 0 {
- sqlstr += " and t1.productname like CONCAT('%',?,'%')"
- args = append(args, productname)
- }
- if pagecount > 0 {
- sqlstr += " limit ?,?"
- args = append(args, (offset-1)*pagecount, pagecount)
- }
- productrow := tx.SQL(sqlstr, args...)
- defer productrow.Close()
- queryData, err = productrow.Query().List()
- if err != nil {
- log.Println("GetPublishPrice-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- var args1 []interface{}
- sqlstr1 := `select t1.id from productinfo t1
- join prounit t2 on t2.id = t1.prounit where 1=1 and t1.enable = 1 `
- if productclass > 0 {
- sqlstr1 += " and t1.productclass = ?"
- args1 = append(args1, productclass)
- }
- if len(productname) > 0 {
- sqlstr1 += " and t1.productname like CONCAT('%',?,'%')"
- args1 = append(args1, productname)
- }
- row := tx.SQL(sqlstr1, args1...)
- defer row.Close()
- count, err := row.Query().Count()
- if err != nil {
- log.Println("GetPublishPrice-err2: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- recordcount = count
- }
- productidlist := []string{"0"}
- for _, data := range queryData {
- productidlist = append(productidlist, strconv.FormatInt(data["productid"].(int64), 10))
- }
- type areaid struct {
- areaid int64
- name string
- parentid int64
- layer int64
- sort int64
- }
- headlist := make([]map[string]interface{}, 0)
- {
- sqlstr := `select t1.id,t1.name,t1.parent_id as parentid ,t1.layer,t1.ord from canton t1
- join (select DISTINCT(areaid) as areaid,t2.name from productarea t1 join canton t2 on t2.id = t1.areaid
- where productid in (%s)) t2 on (t1.id = t2.areaid or t1.PARENT_ID = t2.areaid)`
- arearow := tx.SQL(fmt.Sprintf(sqlstr, strings.Join(productidlist, ",")))
- areaData, err := arearow.Query().List()
- if err != nil {
- log.Println("GetPublishPrice-err3: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- bigarea := make([]*areaid, 0)
- for _, area := range areaData {
- if area["layer"].(int64) == 1 {
- bigarea = append(bigarea, &areaid{
- areaid: area["id"].(int64),
- name: area["name"].(string),
- parentid: area["parentid"].(int64),
- layer: area["layer"].(int64),
- sort: area["ord"].(int64),
- })
- }
- }
- sort.Slice(bigarea, func(i, j int) bool {
- return bigarea[i].areaid < bigarea[j].areaid // 升序
- })
- sort.Slice(bigarea, func(i, j int) bool {
- return bigarea[i].sort < bigarea[j].sort // 升序
- })
- for _, big := range bigarea {
- head := make(map[string]interface{})
- head["column_id"] = big.areaid
- head["column_name"] = fmt.Sprintf("column_%d", big.areaid)
- head["column_title"] = big.name
- smallarea := make([]*areaid, 0)
- for _, area := range areaData {
- if area["parentid"].(int64) == big.areaid {
- smallarea = append(smallarea, &areaid{
- areaid: area["id"].(int64),
- name: area["name"].(string),
- parentid: area["parentid"].(int64),
- layer: area["layer"].(int64),
- sort: area["ord"].(int64),
- })
- }
- }
- sort.Slice(smallarea, func(i, j int) bool {
- return smallarea[i].areaid < smallarea[j].areaid // 升序
- })
- sort.Slice(smallarea, func(i, j int) bool {
- return smallarea[i].sort < smallarea[j].sort // 升序
- })
- smallhead := make([]map[string]interface{}, 0)
- for _, small := range smallarea {
- data1 := make(map[string]interface{})
- data1["column_id"] = small.areaid
- data1["column_name"] = fmt.Sprintf("column_%d", small.areaid)
- data1["column_title"] = small.name
- smallhead = append(smallhead, data1)
- }
- head["headlist"] = smallhead
- headlist = append(headlist, head)
- }
- productpricesql := `SELECT productid,marketid as smallareaid , marketclass as bigareaid,price FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate DESC limit 10000000000000000
- ) AS t where 1=1 `
- if date != "" {
- productpricesql += fmt.Sprintf(" and DATE_FORMAT(pricedate,'%%Y-%%c-%%d') = %s ", date)
- }
- productpricesql += " group by productid, marketid "
- productpricerow := tx.SQL(fmt.Sprintf(productpricesql, strings.Join(productidlist, ",")))
- productpriceData, err := productpricerow.Query().List()
- type priceStruct struct {
- marketid int64
- price string
- }
- priceMap := make(map[int64][]priceStruct)
- for _, productprice := range productpriceData {
- priceMap[productprice["productid"].(int64)] = append(priceMap[productprice["productid"].(int64)], priceStruct{
- marketid: productprice["smallareaid"].(int64),
- price: productprice["price"].(string),
- })
- }
- for _, query := range queryData {
- for _, area := range areaData {
- if area["layer"].(int64) == 2 {
- query[fmt.Sprintf("column_%v", area["id"])] = 0
- }
- }
- query["Edit"] = false
- query["NoEdit"] = true
- query["isCreate"] = false
- query["isUpdate"] = true
- query["isUpdateSave"] = false
- }
- for _, query := range queryData {
- for _, price := range priceMap[query["productid"].(int64)] {
- query[fmt.Sprintf("column_%d", price.marketid)] = price.price
- }
- }
- data["list"] = queryData
- }
- data["headlist"] = headlist
- 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 UpdatePublishPrice(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- params := fsion.Get("params").Array()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- for _, param := range params {
- productid := param.Get("productid").ValueInt64()
- productclass := param.Get("productclass").ValueStr()
- areaidlist := []string{"0"}
- for _, key := range param.Keys() {
- if strings.Index(key, "column_") > -1 {
- areaidlist = append(areaidlist, key[len("column_"):])
- }
- }
- areamap, err := tx.SQL(fmt.Sprintf(`select t1.id,t2.PARENT_ID as parentid from canton t1
- join canton t2 on t1.PARENT_ID = t2.id where t1.id in (%s)
- order by t2.ORD ,t1.ORD,t1.id`, strings.Join(areaidlist, ","))).Query().List()
- if err != nil {
- log.Println("UpdatePublishPrice-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- pricemap, err := tx.SQL(`SELECT t.marketid ,t.marketclass,t.price , t.pricedate,id FROM (
- SELECT * FROM productprice WHERE productid = ? ORDER BY pricedate DESC limit 10000000000000000
- ) AS t
- GROUP BY t.marketid `, productid).Query().List()
- if err != nil {
- log.Println("UpdatePublishPrice-err2: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, area := range areamap {
- pricenum := param.Get(fmt.Sprintf("column_%v", area["id"])).ValueFloat64()
- isupdateprice := false
- exist := false
- for _, price := range pricemap {
- if area["id"].(int64) == price["marketid"].(int64) {
- priceintface, _ := strconv.ParseFloat(price["price"].(string), 64)
- if priceintface == pricenum {
- // if !isupdateinfo {
- // _, err := tx.SQL("update productinfo set price = ? where id = ?", pricenum, productid).Execute()
- // if err != nil {
- // log.Println("UpdatePublishPrice-err3: ", err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- // return
- // }
- // isupdateinfo = true
- // }
- isupdateprice = true
- }
- exist = true
- break
- }
- }
- // if !isupdateinfo && (exist && pricenum == 0) {
- // _, err := tx.SQL("update productinfo set price = ? where id = ?", pricenum, productid).Execute()
- // if err != nil {
- // log.Println("UpdatePublishPrice-err3: ", err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- // return
- // }
- // isupdateinfo = true
- // }
- if (!isupdateprice && (exist)) || (!isupdateprice && !exist && pricenum != 0) {
- var args []interface{}
- args = append(args, productid, area["id"], pricenum, area["parentid"], productclass)
- _, err := tx.SQL("insert into productprice(productid,marketid,price,marketclass,productclass,pricedate)values(?,?,?,?,?,now())", args...).Execute()
- if err != nil {
- log.Println("UpdatePublishPrice-err4: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- }
- }
- }
- appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
- //查看产品信息 GetProductInfo
- func GetProductInfo(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- smallclassid := parammaps.Get("smallclassid").ValueStr()
- productname := parammaps.Get("productname").ValueStr()
- var args []interface{}
- tx := restful.Engine.NewSession()
- defer tx.Close()
- sqlstr := ` select t1.id as productid ,t1.productname, IFNULL(t1.spec,'') as specifications ,t2.unitname as unit,t1.prounit as unitid ,t1.enable,t1.ordernum as sort , t3.productclass ,t3.id as smallclassid
- from productinfo t1
- inner join prounit t2 on t2.id = t1.prounit
- inner join (select t1.classname as smallname,t2.classname as bigname,t1.id,CONCAT(t2.classname,'-',t1.classname)as productclass ,t1.ordernum as smallsort ,t2.ordernum as bigsort
- from productclass t1 join productclass t2 on t2.id = t1.parentid where t1.leavel = 2) t3 on t3.id = t1.productclass
- where 1=1 `
- if smallclassid != "" {
- sqlstr += " and t1.productclass = ? "
- args = append(args, smallclassid)
- }
- if productname != "" {
- sqlstr += " and t1.productname like CONCAT('%',?,'%') "
- args = append(args, productname)
- }
- sqlstr += " order by t3.bigsort,t3.smallsort ,t1.ordernum"
- arearow := tx.SQL(sqlstr, args...)
- defer arearow.Close()
- queryData := make([]map[string]interface{}, 0)
- var err error
- if pagecount > 0 {
- queryData, err = arearow.Limit(pagecount, (offset-1)*pagecount).Query().List()
- if err != nil {
- log.Println("GetProductInfo-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- } else {
- queryData, err = arearow.Query().List()
- if err != nil {
- log.Println("GetProductInfo-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- }
- sqlstrcount := `select t1.id
- from productinfo t1
- inner join prounit t2 on t2.id = t1.prounit
- inner join (select t1.classname as smallname,t2.classname as bigname,t1.id,CONCAT(t2.classname,'-',t1.classname)as productclass ,t1.ordernum as smallsort ,t2.ordernum as bigsort
- from productclass t1 join productclass t2 on t2.id = t1.parentid where t1.leavel = 2) t3 on t3.id = t1.productclass
- where 1=1 and t1.enable = 1 `
- if smallclassid != "" {
- sqlstrcount += " and t1.productclass = ? "
- }
- if productname != "" {
- sqlstrcount += " and t1.productname like CONCAT('%',?,'%') "
- }
- countrow := tx.SQL(sqlstr, args...)
- recordcount, err := countrow.Query().Count()
- if err != nil {
- log.Println("GetProductInfo-err2: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- productids := []string{"0"}
- for _, query := range queryData {
- productids = append(productids, fmt.Sprintf("%v", query["productid"]))
- }
- pricemap, err := tx.SQL(fmt.Sprintf(`SELECT productid,price FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate DESC limit 10000000000000000
- ) AS t group by productid `, strings.Join(productids, ","))).Query().List()
- if err != nil {
- log.Println("GetProductInfo-err3: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, query := range queryData {
- productid := query["productid"].(int64)
- for _, price := range pricemap {
- if productid == price["productid"].(int64) {
- query["price"] = price["price"]
- }
- }
- }
- data := make(map[string]interface{})
- data["list"] = queryData
- 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 GetAveragePrice(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- productclass := parammaps.Get("productclassid").ValueStr()
- productid := parammaps.Get("productid").ValueInt64()
- starttime := parammaps.Get("starttime").ValueStr()
- endtime := parammaps.Get("endtime").ValueStr()
- productname := parammaps.Get("productname").ValueStr()
- userid := parammaps.Get("userid").ValueStr()
- var productidlist []string
- if productid != 0 {
- productidlist = append(productidlist, fmt.Sprintf("%d", productid))
- }
- data := make(map[string]interface{})
- var err error
- queryData := make([]map[string]interface{}, 0)
- var recordcount int
- tx := restful.Engine.NewSession()
- defer tx.Close()
- if userid != "" {
- productidmap, err := tx.SQL("select Productid as productid from attention where userid = ?", userid).Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, product := range productidmap {
- productidlist = append(productidlist, fmt.Sprintf("%v", product["productid"]))
- }
- if len(productidlist) == 0 {
- appG.Response(http.StatusOK, e.SUCCESS, data)
- return
- }
- }
- {
- sqlstr := `select t1.id as productid,t1.productname,t1.productclass,ifnull(t1.spec,"") as specifications ,ifnull(t2.unitname,"") as unitname from productinfo t1
- join prounit t2 on t2.id = t1.prounit join productclass t3 on t3.id = t1.productclass where 1=1 and t1.enable = 1 `
- var args []interface{}
- if len(productclass) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productclass in (%s)", productclass)
- }
- if len(productname) > 0 {
- sqlstr += " and t1.productname like CONCAT('%',?,'%')"
- args = append(args, productname)
- }
- // if productid != 0 {
- // sqlstr += " and t1.id in (?) "
- // args = append(args, strings.Join(productidlist, ","))
- // }
- if len(productidlist) > 0 {
- sqlstr += fmt.Sprintf(" and t1.id in (%s) ", strings.Join(productidlist, ","))
- }
- sqlstr += " order by t3.ordernum,t3.id,t1.ordernum,t1.id"
- if pagecount > 0 && productid == 0 {
- sqlstr += " limit ?,?"
- args = append(args, (offset-1)*pagecount, pagecount)
- }
- productrow := tx.SQL(sqlstr, args...)
- defer productrow.Close()
- queryData, err = productrow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- if productid == 0 {
- var args1 []interface{}
- sqlstr1 := `select t1.id from productinfo t1
- join prounit t2 on t2.id = t1.prounit where 1=1 and t1.enable = 1 `
- if len(productclass) > 0 {
- sqlstr1 += fmt.Sprintf(" and t1.productclass in (%s) ", productclass)
- }
- if len(productname) > 0 {
- sqlstr1 += " and t1.productname like CONCAT('%',?,'%')"
- args1 = append(args1, productname)
- }
- if len(productidlist) > 0 {
- sqlstr1 += fmt.Sprintf(" and t1.id in (%s) ", strings.Join(productidlist, ","))
- }
- row := tx.SQL(sqlstr1, args1...)
- defer row.Close()
- count, err := row.Query().Count()
- if err != nil {
- log.Println("GetAveragePrice-err2: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- recordcount = count
- defer row.Close()
- }
- defer productrow.Close()
- }
- // productidlist := []string{"0"}
- for _, data := range queryData {
- productidlist = append(productidlist, strconv.FormatInt(data["productid"].(int64), 10))
- }
- type areaid struct {
- areaid int64
- name string
- parentid int64
- layer int64
- sort int64
- }
- headlist := make([]map[string]interface{}, 0)
- if len(productidlist) > 0 {
- sqlstr := `select t1.id,t1.name,t1.parent_id as parentid ,t1.layer,t1.ord from canton t1
- join (select DISTINCT(areaid) as areaid,t2.name from productarea t1 join canton t2 on t2.id = t1.areaid
- where productid in (%s)) t2 on (t1.id = t2.areaid or t1.PARENT_ID = t2.areaid)`
- arearow := tx.SQL(fmt.Sprintf(sqlstr, strings.Join(productidlist, ",")))
- areaData, err := arearow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err3: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- bigarea := make([]*areaid, 0)
- for _, area := range areaData {
- if area["layer"].(int64) == 1 {
- bigarea = append(bigarea, &areaid{
- areaid: area["id"].(int64),
- name: area["name"].(string),
- parentid: area["parentid"].(int64),
- layer: area["layer"].(int64),
- sort: area["ord"].(int64),
- })
- }
- }
- sort.Slice(bigarea, func(i, j int) bool {
- return bigarea[i].areaid < bigarea[j].areaid // 升序
- })
- sort.Slice(bigarea, func(i, j int) bool {
- return bigarea[i].sort < bigarea[j].sort // 升序
- })
- for _, big := range bigarea {
- head := make(map[string]interface{})
- head["column_id"] = big.areaid
- head["column_name"] = fmt.Sprintf("column_%d", big.areaid)
- head["column_title"] = big.name
- smallarea := make([]*areaid, 0)
- for _, area := range areaData {
- if area["parentid"].(int64) == big.areaid {
- smallarea = append(smallarea, &areaid{
- areaid: area["id"].(int64),
- name: area["name"].(string),
- parentid: area["parentid"].(int64),
- layer: area["layer"].(int64),
- sort: area["ord"].(int64),
- })
- }
- }
- sort.Slice(smallarea, func(i, j int) bool {
- return smallarea[i].areaid < smallarea[j].areaid // 升序
- })
- sort.Slice(smallarea, func(i, j int) bool {
- return smallarea[i].sort < smallarea[j].sort // 升序
- })
- smallhead := make([]map[string]interface{}, 0)
- for _, small := range smallarea {
- data1 := make(map[string]interface{})
- data1["column_id"] = small.areaid
- data1["column_name"] = fmt.Sprintf("column_%d", small.areaid)
- data1["column_title"] = small.name
- smallhead = append(smallhead, data1)
- }
- head["headlist"] = smallhead
- headlist = append(headlist, head)
- }
- type priceStruct struct {
- marketid int64
- price float64
- pricedate string
- }
- priceMap := make(map[int64][]priceStruct)
- if productid == 0 {
- productpricesql := `SELECT productid,marketid as smallareaid , marketclass as bigareaid,avg(price) as price,pricedate FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate DESC limit 10000000000000000
- ) AS t where 1=1 `
- if starttime != "" && endtime != "" {
- productpricesql += fmt.Sprintf(" and pricedate BETWEEN '%s' and '%s' ", fmt.Sprintf("%s 00:00:00", starttime), fmt.Sprintf("%s 23:59:59", endtime))
- }
- productpricesql += " group by productid, marketid "
- if offset != 0 || pagecount != 0 {
- productpricesql += fmt.Sprintf(" limit %d,%d", (offset-1)*pagecount, pagecount)
- }
- productpricerow := tx.SQL(fmt.Sprintf(productpricesql, strings.Join(productidlist, ",")))
- defer productpricerow.Close()
- productpriceData, err := productpricerow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err4: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, productprice := range productpriceData {
- price, err := strconv.ParseFloat(productprice["price"].(string), 64)
- if err != nil {
- log.Println("GetAveragePrice-err6: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- priceMap[productprice["productid"].(int64)] = append(priceMap[productprice["productid"].(int64)], priceStruct{
- marketid: productprice["smallareaid"].(int64),
- price: utils.Round(price, 2),
- })
- }
- for _, query := range queryData {
- for _, area := range areaData {
- if area["layer"].(int64) == 2 {
- query[fmt.Sprintf("column_%v", area["id"])] = 0
- }
- }
- query["Edit"] = false
- query["NoEdit"] = true
- query["isCreate"] = false
- query["isUpdate"] = true
- query["isUpdateSave"] = false
- }
- for _, query := range queryData {
- for _, price := range priceMap[query["productid"].(int64)] {
- query[fmt.Sprintf("column_%d", price.marketid)] = price.price
- }
- }
- data["list"] = queryData
- } else {
- timesql := `SELECT date_format(pricedate, '%%Y-%%c-%%d') as pricedate FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate desc limit 10000000000000000
- ) AS t where 1=1 group by date_format(pricedate, '%%Y-%%c-%%d') ORDER BY pricedate desc `
- count, err := tx.SQL(fmt.Sprintf(timesql, strings.Join(productidlist, ","))).Query().Count()
- if err != nil {
- log.Println("GetAveragePrice-err4: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- recordcount = int(count)
- dates := []string{}
- if offset != 0 || pagecount != 0 {
- timesql += fmt.Sprintf(" limit %d,%d", (offset-1)*pagecount, pagecount)
- }
- timeData, err := tx.SQL(fmt.Sprintf(timesql, strings.Join(productidlist, ","))).Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err5: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- productpricesql := `SELECT productid,marketid as smallareaid , marketclass as bigareaid,avg(price) as price,date_format(pricedate, '%%Y-%%c-%%d') as pricedate FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate DESC limit 10000000000000000
- ) AS t where 1=1 `
- if len(timeData) > 0 {
- starttime = fmt.Sprintf("%s 00:00:00", timeData[len(timeData)-1]["pricedate"].(string))
- endtime = fmt.Sprintf("%s 23:59:59", timeData[0]["pricedate"].(string))
- productpricesql += fmt.Sprintf(" and pricedate BETWEEN '%s' and '%s' ", fmt.Sprintf("%s 00:00:00", starttime), fmt.Sprintf("%s 23:59:59", endtime))
- }
- productpricesql += " group by marketid,date_format(pricedate, '%%Y-%%c-%%d') "
- productpricerow := tx.SQL(fmt.Sprintf(productpricesql, strings.Join(productidlist, ",")))
- defer productpricerow.Close()
- productpriceData, err := productpricerow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err6: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, productprice := range productpriceData {
- dates = append(dates, productprice["pricedate"].(string))
- price, err := strconv.ParseFloat(productprice["price"].(string), 64)
- if err != nil {
- log.Println("GetAveragePrice-err7: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- priceMap[productprice["productid"].(int64)] = append(priceMap[productprice["productid"].(int64)], priceStruct{
- marketid: productprice["smallareaid"].(int64),
- price: utils.Round(price, 2),
- pricedate: productprice["pricedate"].(string),
- })
- }
- datelist := utils.RemoveRepeatedElement(dates)
- sort.Sort(sort.Reverse(sort.StringSlice(datelist)))
- productmap := make([]map[string]interface{}, 0)
- for _, date := range datelist {
- product := make(map[string]interface{}, 0)
- product["productid"] = productid
- for _, query := range queryData {
- if query["productid"].(int64) == productid {
- product["productclass"] = query["productclass"]
- product["productname"] = query["productname"]
- product["unitname"] = query["unitname"]
- product["specifications"] = query["specifications"]
- break
- }
- }
- for _, area := range areaData {
- if area["layer"].(int64) == 2 {
- product[fmt.Sprintf("column_%v", area["id"])] = 0
- }
- }
- product["Edit"] = false
- product["NoEdit"] = true
- product["isCreate"] = false
- product["isUpdate"] = true
- product["isUpdateSave"] = false
- product["pricedate"] = date
- for _, price := range priceMap[product["productid"].(int64)] {
- if date == price.pricedate {
- product[fmt.Sprintf("column_%d", price.marketid)] = price.price
- }
- }
- productmap = append(productmap, product)
- }
- data["list"] = productmap
- }
- }
- data["headlist"] = headlist
- 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 GetQuotationChart(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- parammaps := fsion.Get("parammaps")
- productid := parammaps.Get("productid").ValueInt64()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- areamap, err := tx.SQL("select name from canton t1 join productarea t2 on t2.productid = ? and t1.PARENT_ID = t2.areaid where layer = 2 ", productid).Query().List()
- if err != nil {
- log.Println("GetQuotationChart-err0: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- sqlstr := `select avg(t1.price) as price , date_format(t1.pricedate, '%Y-%c-%d') as date ,t2.name from productprice t1
- join canton t2 on t2.id = t1.marketid where t1.productid = ? group by date,name order by date desc `
- priceData, err := tx.SQL(sqlstr, productid).Query().List()
- if err != nil {
- log.Println("GetQuotationChart-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- datelist := []string{}
- daylist := []interface{}{}
- for _, price := range priceData {
- datelist = append(datelist, price["date"].(string))
- }
- days := utils.RemoveRepeatedElement(datelist)
- sort.Sort(sort.Reverse(sort.StringSlice(days)))
- for _, day := range days {
- daylist = append(daylist, day)
- }
- var list [][]interface{}
- namelist := []interface{}{}
- for _, area := range areamap {
- namelist = append(namelist, area["name"].(string))
- }
- list = append(list, namelist)
- list = append(list, daylist)
- for _, name := range namelist {
- pricelist := []interface{}{}
- for _, day := range daylist {
- exist := false
- for _, pricemap := range priceData {
- if pricemap["name"].(string) == name.(string) && day.(string) == pricemap["date"].(string) {
- price, err := strconv.ParseFloat(pricemap["price"].(string), 64)
- if err != nil {
- log.Println("GetAveragePrice-err6: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- pricelist = append(pricelist, utils.Round(price, 2))
- exist = true
- }
- }
- if !exist {
- pricelist = append(pricelist, 0)
- }
- }
- list = append(list, pricelist)
- }
- appG.Response(http.StatusOK, e.SUCCESS, list)
- }
- func AttentionProduce(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- userid := fsion.Get("userid").ValueStr()
- params := fsion.Get("params").Array()
- tx := restful.Engine.NewSession()
- defer tx.Close()
- productids := []string{}
- for _, product := range params {
- productids = append(productids, product.ValueStr())
- exist, err := tx.SQL("select id from attention where userid = ? and productid = ? ", userid, product.ValueInt64()).Exist()
- if err != nil {
- log.Println("AttentionProduce-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- if !exist {
- _, err := tx.SQL("insert into attention(userid,productid)values(?,?)", userid, product.ValueInt64()).Execute()
- if err != nil {
- log.Println("AttentionProduce-err2: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- }
- }
- if len(productids) == 0 {
- productids = append(productids, "0")
- }
- _, err := tx.SQL(fmt.Sprintf("delete from attention where userid = ? and productid not in(%s)", strings.Join(productids, ",")), userid).Execute()
- if err != nil {
- log.Println("AttentionProduce-err3: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- appG.Response(http.StatusOK, e.SUCCESS, true)
- }
- func GetAveragePriceExcel(c *gin.Context) {
- appG := app.Gin{C: c}
- dataByte, _ := ioutil.ReadAll(c.Request.Body)
- fsion := gofasion.NewFasion(string(dataByte))
- offset := fsion.Get("offset").ValueDefaultInt(0)
- pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
- parammaps := fsion.Get("parammaps")
- productclass := parammaps.Get("productclassid").ValueStr()
- productid := parammaps.Get("productid").ValueInt64()
- starttime := parammaps.Get("starttime").ValueStr()
- endtime := parammaps.Get("endtime").ValueStr()
- productname := parammaps.Get("productname").ValueStr()
- userid := parammaps.Get("userid").ValueStr()
- username := parammaps.Get("empname").ValueStr()
- // var productidlist []string
- // if productid != 0 {
- // productidlist = append(productidlist, fmt.Sprintf("%d", productid))
- // }
- // data := make(map[string]interface{})
- // var err error
- // queryData := make([]map[string]interface{}, 0)
- var productidlist []string
- if productid != 0 {
- productidlist = append(productidlist, fmt.Sprintf("%d", productid))
- }
- data := make(map[string]interface{})
- var err error
- queryData := make([]map[string]interface{}, 0)
- // var recordcount int
- tx := restful.Engine.NewSession()
- defer tx.Close()
- if userid != "" {
- productidmap, err := tx.SQL("select Productid as productid from attention where userid = ?", userid).Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, product := range productidmap {
- productidlist = append(productidlist, fmt.Sprintf("%v", product["productid"]))
- }
- if len(productidlist) == 0 {
- appG.Response(http.StatusOK, e.SUCCESS, data)
- return
- }
- }
- {
- sqlstr := `select t3.classname,t1.id as productid,t1.productname,t1.productclass,ifnull(t1.spec,"") as specifications ,ifnull(t2.unitname,"") as unitname from productinfo t1
- join prounit t2 on t2.id = t1.prounit join productclass t3 on t3.id = t1.productclass where 1=1 and t1.enable = 1 `
- var args []interface{}
- if len(productclass) > 0 {
- sqlstr += fmt.Sprintf(" and t1.productclass in (%s)", productclass)
- }
- if len(productname) > 0 {
- sqlstr += " and t1.productname like CONCAT('%',?,'%')"
- args = append(args, productname)
- }
- // if productid != 0 {
- // sqlstr += " and t1.id in (?) "
- // args = append(args, strings.Join(productidlist, ","))
- // }
- if len(productidlist) > 0 {
- sqlstr += fmt.Sprintf(" and t1.id in (%s) ", strings.Join(productidlist, ","))
- }
- sqlstr += " order by t3.ordernum,t3.id,t1.ordernum,t1.id"
- // if pagecount > 0 && productid == 0 {
- // sqlstr += " limit ?,?"
- // args = append(args, (offset-1)*pagecount, pagecount)
- // }
- productrow := tx.SQL(sqlstr, args...)
- defer productrow.Close()
- queryData, err = productrow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err1: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- // if productid == 0 {
- // var args1 []interface{}
- // sqlstr1 := `select t1.id from productinfo t1
- // join prounit t2 on t2.id = t1.prounit where 1=1 and t1.enable = 1 `
- // if len(productclass) > 0 {
- // sqlstr1 += fmt.Sprintf(" and t1.productclass in (%s) ", productclass)
- // }
- // if len(productname) > 0 {
- // sqlstr1 += " and t1.productname like CONCAT('%',?,'%')"
- // args1 = append(args1, productname)
- // }
- // if len(productidlist) > 0 {
- // sqlstr1 += fmt.Sprintf(" and t1.id in (%s) ", strings.Join(productidlist, ","))
- // }
- // row := tx.SQL(sqlstr1, args1...)
- // defer row.Close()
- // count, err := row.Query().Count()
- // if err != nil {
- // log.Println("GetAveragePrice-err2: ", err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- // return
- // }
- // recordcount = count
- // defer row.Close()
- // }
- defer productrow.Close()
- }
- // productidlist := []string{"0"}
- for _, data := range queryData {
- productidlist = append(productidlist, strconv.FormatInt(data["productid"].(int64), 10))
- }
- type areaid struct {
- areaid int64
- name string
- parentid int64
- layer int64
- sort int64
- }
- headlist := make([]map[string]interface{}, 0)
- if len(productidlist) > 0 {
- sqlstr := `select t1.id,t1.name,t1.parent_id as parentid ,t1.layer,t1.ord from canton t1
- join (select DISTINCT(areaid) as areaid,t2.name from productarea t1 join canton t2 on t2.id = t1.areaid
- where productid in (%s)) t2 on (t1.id = t2.areaid or t1.PARENT_ID = t2.areaid)`
- arearow := tx.SQL(fmt.Sprintf(sqlstr, strings.Join(productidlist, ",")))
- areaData, err := arearow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err3: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- bigarea := make([]*areaid, 0)
- for _, area := range areaData {
- if area["layer"].(int64) == 1 {
- bigarea = append(bigarea, &areaid{
- areaid: area["id"].(int64),
- name: area["name"].(string),
- parentid: area["parentid"].(int64),
- layer: area["layer"].(int64),
- sort: area["ord"].(int64),
- })
- }
- }
- sort.Slice(bigarea, func(i, j int) bool {
- return bigarea[i].areaid < bigarea[j].areaid // 升序
- })
- sort.Slice(bigarea, func(i, j int) bool {
- return bigarea[i].sort < bigarea[j].sort // 升序
- })
- for _, big := range bigarea {
- head := make(map[string]interface{})
- head["column_id"] = big.areaid
- head["column_name"] = fmt.Sprintf("column_%d", big.areaid)
- head["column_title"] = big.name
- smallarea := make([]*areaid, 0)
- for _, area := range areaData {
- if area["parentid"].(int64) == big.areaid {
- smallarea = append(smallarea, &areaid{
- areaid: area["id"].(int64),
- name: area["name"].(string),
- parentid: area["parentid"].(int64),
- layer: area["layer"].(int64),
- sort: area["ord"].(int64),
- })
- }
- }
- sort.Slice(smallarea, func(i, j int) bool {
- return smallarea[i].areaid < smallarea[j].areaid // 升序
- })
- sort.Slice(smallarea, func(i, j int) bool {
- return smallarea[i].sort < smallarea[j].sort // 升序
- })
- smallhead := make([]map[string]interface{}, 0)
- for _, small := range smallarea {
- data1 := make(map[string]interface{})
- data1["column_id"] = small.areaid
- data1["column_name"] = fmt.Sprintf("column_%d", small.areaid)
- data1["column_title"] = small.name
- smallhead = append(smallhead, data1)
- }
- head["headlist"] = smallhead
- headlist = append(headlist, head)
- }
- type priceStruct struct {
- marketid int64
- price float64
- pricedate string
- }
- priceMap := make(map[int64][]priceStruct)
- if productid == 0 {
- productpricesql := `SELECT productid,marketid as smallareaid , marketclass as bigareaid,avg(price) as price,pricedate FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate DESC limit 10000000000000000
- ) AS t where 1=1 `
- if starttime != "" && endtime != "" {
- productpricesql += fmt.Sprintf(" and pricedate BETWEEN '%s' and '%s' ", fmt.Sprintf("%s 00:00:00", starttime), fmt.Sprintf("%s 23:59:59", endtime))
- }
- productpricesql += " group by productid, marketid "
- if offset != 0 || pagecount != 0 {
- productpricesql += fmt.Sprintf(" limit %d,%d", (offset-1)*pagecount, pagecount)
- }
- productpricerow := tx.SQL(fmt.Sprintf(productpricesql, strings.Join(productidlist, ",")))
- defer productpricerow.Close()
- productpriceData, err := productpricerow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err4: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, productprice := range productpriceData {
- price, err := strconv.ParseFloat(productprice["price"].(string), 64)
- if err != nil {
- log.Println("GetAveragePrice-err6: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- priceMap[productprice["productid"].(int64)] = append(priceMap[productprice["productid"].(int64)], priceStruct{
- marketid: productprice["smallareaid"].(int64),
- price: utils.Round(price, 2),
- })
- }
- for _, query := range queryData {
- for _, area := range areaData {
- if area["layer"].(int64) == 2 {
- query[fmt.Sprintf("column_%v", area["id"])] = 0
- }
- }
- query["Edit"] = false
- query["NoEdit"] = true
- query["isCreate"] = false
- query["isUpdate"] = true
- query["isUpdateSave"] = false
- }
- for _, query := range queryData {
- for _, price := range priceMap[query["productid"].(int64)] {
- query[fmt.Sprintf("column_%d", price.marketid)] = price.price
- }
- }
- data["list"] = queryData
- } else {
- timesql := `SELECT date_format(pricedate, '%%Y-%%c-%%d') as pricedate FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate desc limit 10000000000000000
- ) AS t where 1=1 group by date_format(pricedate, '%%Y-%%c-%%d') ORDER BY pricedate desc `
- // count, err := tx.SQL(fmt.Sprintf(timesql, strings.Join(productidlist, ","))).Query().Count()
- // if err != nil {
- // log.Println("GetAveragePrice-err4: ", err)
- // appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- // return
- // }
- // recordcount = int(count)
- dates := []string{}
- if offset != 0 || pagecount != 0 {
- timesql += fmt.Sprintf(" limit %d,%d", (offset-1)*pagecount, pagecount)
- }
- timeData, err := tx.SQL(fmt.Sprintf(timesql, strings.Join(productidlist, ","))).Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err5: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- productpricesql := `SELECT productid,marketid as smallareaid , marketclass as bigareaid,avg(price) as price,date_format(pricedate, '%%Y-%%c-%%d') as pricedate FROM (
- SELECT * FROM productprice WHERE productid in (%s) ORDER BY pricedate DESC limit 10000000000000000
- ) AS t where 1=1 `
- if len(timeData) > 0 {
- starttime = fmt.Sprintf("%s 00:00:00", timeData[len(timeData)-1]["pricedate"].(string))
- endtime = fmt.Sprintf("%s 23:59:59", timeData[0]["pricedate"].(string))
- productpricesql += fmt.Sprintf(" and pricedate BETWEEN '%s' and '%s' ", fmt.Sprintf("%s 00:00:00", starttime), fmt.Sprintf("%s 23:59:59", endtime))
- }
- productpricesql += " group by marketid,date_format(pricedate, '%%Y-%%c-%%d') "
- productpricerow := tx.SQL(fmt.Sprintf(productpricesql, strings.Join(productidlist, ",")))
- defer productpricerow.Close()
- productpriceData, err := productpricerow.Query().List()
- if err != nil {
- log.Println("GetAveragePrice-err6: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- for _, productprice := range productpriceData {
- dates = append(dates, productprice["pricedate"].(string))
- price, err := strconv.ParseFloat(productprice["price"].(string), 64)
- if err != nil {
- log.Println("GetAveragePrice-err7: ", err)
- appG.Response(http.StatusInternalServerError, e.ERROR, nil)
- return
- }
- priceMap[productprice["productid"].(int64)] = append(priceMap[productprice["productid"].(int64)], priceStruct{
- marketid: productprice["smallareaid"].(int64),
- price: utils.Round(price, 2),
- pricedate: productprice["pricedate"].(string),
- })
- }
- datelist := utils.RemoveRepeatedElement(dates)
- sort.Sort(sort.Reverse(sort.StringSlice(datelist)))
- productmap := make([]map[string]interface{}, 0)
- for _, date := range datelist {
- product := make(map[string]interface{}, 0)
- product["productid"] = productid
- for _, query := range queryData {
- if query["productid"].(int64) == productid {
- product["productclass"] = query["productclass"]
- product["productname"] = query["productname"]
- product["unitname"] = query["unitname"]
- product["specifications"] = query["specifications"]
- product["classname"] = query["classname"]
- break
- }
- }
- for _, area := range areaData {
- if area["layer"].(int64) == 2 {
- product[fmt.Sprintf("column_%v", area["id"])] = 0
- }
- }
- product["Edit"] = false
- product["NoEdit"] = true
- product["isCreate"] = false
- product["isUpdate"] = true
- product["isUpdateSave"] = false
- product["pricedate"] = date
- for _, price := range priceMap[product["productid"].(int64)] {
- if date == price.pricedate {
- product[fmt.Sprintf("column_%d", price.marketid)] = price.price
- }
- }
- productmap = append(productmap, product)
- }
- data["list"] = productmap
- }
- }
- var file *xlsx.File
- var sheet *xlsx.Sheet
- var row *xlsx.Row
- var cell *xlsx.Cell
- style := xlsx.NewStyle()
- style.Alignment = xlsx.Alignment{
- Horizontal: "center",
- Vertical: "center",
- WrapText: true,
- ShrinkToFit: true,
- }
- file = xlsx.NewFile()
- sheet, _ = file.AddSheet("Sheet1")
- row = sheet.AddRow()
- cell = row.AddCell()
- classnum := make(map[string]int64)
- datamap := make(map[string][]interface{})
- classlist := []string{}
- fmt.Println(data["list"].([]map[string]interface{})[:10])
- for _, data := range data["list"].([]map[string]interface{}) {
- exist := false
- for _, class := range classlist {
- if data["classname"].(string) == class {
- exist = true
- }
- }
- if !exist {
- classlist = append(classlist, data["classname"].(string))
- }
- classnum[data["classname"].(string)]++
- datamap[data["classname"].(string)] = append(datamap[data["classname"].(string)], data)
- }
- exceltitle := "品种: "
- for _, v := range classlist {
- exceltitle += v + ","
- }
- exceltitle = exceltitle[:len(exceltitle)-1]
- exceltitle = fmt.Sprintf("%s 用户: %s", exceltitle, username)
- cell.Value = exceltitle
- cell.Merge(len(datamap), 2)
- cell.SetStyle(style)
- row = sheet.AddRow()
- cell = row.AddCell()
- row = sheet.AddRow()
- cell = row.AddCell()
- row = sheet.AddRow()
- cell = row.AddCell()
- cell.Value = "分类"
- cell.Merge(0, 1)
- cell.SetStyle(style)
- cell = row.AddCell()
- cell.Value = "序号"
- cell.SetStyle(style)
- cell.Merge(0, 1)
- cell = row.AddCell()
- cell.Value = "品名"
- cell.SetStyle(style)
- cell.Merge(0, 1)
- cell = row.AddCell()
- cell.Value = "规格"
- cell.SetStyle(style)
- cell.Merge(0, 1)
- cell = row.AddCell()
- cell.Value = "单位"
- cell.SetStyle(style)
- cell.Merge(0, 1)
- if data["list"] == nil {
- _ = file.Write(c.Writer)
- return
- }
- v := 0
- for _, data := range headlist {
- for i := 0; i < v; i++ {
- cell = row.AddCell()
- cell.Value = ""
- }
- cell = row.AddCell()
- cell.Value = data["column_title"].(string)
- cell.SetStyle(style)
- head := data["headlist"].([]map[string]interface{})
- hcells := len(head) - 1
- cell.Merge(hcells, 0)
- v = hcells
- }
- row = sheet.AddRow()
- for i := 0; i < 5; i++ {
- cell = row.AddCell()
- cell.Value = ""
- }
- var datatitle []string
- for _, data := range headlist {
- headlist := data["headlist"].([]map[string]interface{})
- for _, head := range headlist {
- cell = row.AddCell()
- cell.SetStyle(style)
- cell.Value = head["column_title"].(string)
- datatitle = append(datatitle, head["column_name"].(string))
- }
- }
- i := 0
- for _, v := range classlist {
- row = sheet.AddRow()
- cell = row.AddCell()
- cell.SetStyle(style)
- cell.Value = v
- cell.Merge(0, int(classnum[v])-1)
- n := len(datamap[v]) - 1
- for m, data := range datamap[v] {
- avgdata := data.(map[string]interface{})
- i++
- cell = row.AddCell()
- cell.SetStyle(style)
- cell.SetValue(i)
- cell = row.AddCell()
- cell.SetStyle(style)
- cell.SetValue(avgdata["productname"])
- cell = row.AddCell()
- cell.SetStyle(style)
- cell.SetValue(avgdata["specifications"])
- cell = row.AddCell()
- cell.SetStyle(style)
- cell.SetValue(avgdata["unitname"])
- for _, title := range datatitle {
- var value float64
- if _, ok := avgdata[title].(float64); ok {
- value = avgdata[title].(float64)
- }
- cell = row.AddCell()
- cell.SetStyle(style)
- // value := avgdata[title].(float64)
- cell.SetValue(value)
- }
- if n != m {
- row = sheet.AddRow()
- cell = row.AddCell()
- }
- }
- }
- row = sheet.AddRow()
- cell = row.AddCell()
- cell.Merge(len(datamap), 0)
- cell.Value = "备注:1、本网站市场价格为市场现金交易价。配送价为配送到酒店的价格(含运输费,发票,15天帐期)。"
- row = sheet.AddRow()
- cell = row.AddCell()
- cell.Merge(len(datamap), 0)
- cell.Value = " 2、本网站蔬菜类价格主要是市场上大量采购及供货商拿货时间段(凌晨4:00-6:00)的价格。"
- row = sheet.AddRow()
- cell = row.AddCell()
- cell.Merge(len(datamap), 0)
- cell.Value = " 3、会员企业可根据市场价格上浮一定比例给供应商定价,部分加工品种可根据加工程度另调上浮比例来定价。"
- c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
- c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
- c.Header("Content-Transfer-Encoding", "binary")
- _ = file.Write(c.Writer)
- // appG.Response(http.StatusOK, e.SUCCESS, nil)
- }
|