zouyuxuan 5 anos atrás
pai
commit
4973d315a5

+ 6 - 0
src/config.json

@@ -55,6 +55,12 @@
 		"itype": "bidding",
 		"pool": 15
 	},
+	"second_push": {
+		"addr": "192.168.3.207:27092",
+		"size": 15,
+		"db": "zyx",
+		"coll": "usermail"
+	},
 	"mail": [
         {
             "addr": "smtp.exmail.qq.com",

+ 1 - 0
src/main.go

@@ -34,6 +34,7 @@ func init() {
 	xweb.AddAction(&service.Feedback{})
 	xweb.AddAction(&service.Private{})
 	xweb.AddAction(&service.Customer{})
+	xweb.AddAction(&service.SecondPush{})
 	xweb.AddAction(&history.HistoryData{})
 	xweb.RootApp().AppConfig.SessionTimeout = 1 * time.Hour
 	xweb.RootApp().Logger.SetOutputLevel(1)

+ 608 - 0
src/service/second_push.go

@@ -0,0 +1,608 @@
+package service
+
+import (
+	"encoding/json"
+	"github.com/tealeg/xlsx"
+	"history"
+	"log"
+	"os"
+	mongoutil "qfw/mongodb"
+	qu "qfw/util"
+	"qfw/util/mail"
+	"strconv"
+	"strings"
+	"sync"
+	"time"
+	. "util"
+
+	"github.com/go-xweb/xweb"
+
+	"gopkg.in/mgo.v2/bson"
+)
+var projectIdMap = sync.Map{}
+var xlsxArr []map[string]interface{}
+
+type SecondPush struct {
+	*xweb.Action
+	secondPush    xweb.Mapper `xweb:"/service/secondpush/create"`
+	getUserRule    xweb.Mapper `xweb:"/service/secondpush/getrules"`
+	saveSpushRule    xweb.Mapper `xweb:"/service/secondpush/saverule"`
+	secondPushTask    xweb.Mapper `xweb:"/service/secondpush/dotask"`
+	addSecondPushRule    xweb.Mapper `xweb:"/service/secondpush/add"`  //保存二次推送规则
+	secondPushList    xweb.Mapper `xweb:"/service/secondpush/list"`
+	secondPushClone    xweb.Mapper `xweb:"/service/secondPushClone/(.*)"`
+	delSecondPushRule       xweb.Mapper `xweb:"/service/customer/secondpush/delrule"`    //删除历史任务规则
+
+}
+
+
+
+func (s *SecondPush)SecondPush(){
+	defer qu.Catch()
+	id := s.GetString("id")
+	user := s.GetSession("user").(map[string]interface{})
+	query := bson.M{}
+	query["_id"] = mongoutil.StringTOBsonId(id)
+
+	s_pushid := s.GetString("s_pushid")
+	secondpush_id := ""
+	if s_pushid != "" {
+		secondpush_id = s_pushid
+		hData, ok := Mgo.FindOne("second_push", bson.M{"_id": mongoutil.StringTOBsonId(secondpush_id)})
+		if ok && hData != nil && len(*hData) > 0 {
+			s.T["spush_rule"] = (*hData)["dep_rules"]
+			(*hData)["_id"] = id
+			s.T["data"] = *hData
+		}
+	} else {
+		var user_name, user_customername, appid = "", "", ""
+		userInfo, ok := Mgo.FindOne("euser", query)
+		if ok && userInfo != nil && *userInfo != nil {
+			user_name = qu.ObjToString((*userInfo)["s_name"])
+			user_customername = qu.ObjToString((*userInfo)["s_customername"])
+			appid = qu.ObjToString((*userInfo)["s_appid"])
+		}
+		secondpush_id = Mgo.Save("second_push", map[string]interface{}{
+			"createtime":     time.Now().Unix(),
+			"updatetime":     time.Now().Unix(),
+			"user_id":        id,
+			"create_user":    user["name"],
+			"state":          0,
+			"s_name":         user_name,
+			"s_customername": user_customername,
+			"s_appid":        appid,
+		})
+		s.Redirect("/service/secondpush/create?id=" + id + "&s_pushid=" + secondpush_id)
+		return
+	}
+	s.T["spush_id"] = secondpush_id
+	s.Render("private/second_push_create.html", &s.T)
+}
+
+func (s *SecondPush)GetUserRule(){
+	customerId := s.GetString("c_id")
+	query := bson.M{
+		"s_userid": customerId,
+		"b_delete": false,
+	}
+	data, _ := Mgo.Find("euserdepart", query, `{"i_createtime":-1}`, nil, false, 0, 0)
+	if data != nil && len(*data) != 0 {
+		res := []map[string]interface{}{}
+		for _, m := range *data {
+			history_rule_data := make(map[string]interface{})
+			q := bson.M{
+				"s_departid": qu.BsonIdToSId(m["_id"]),
+				"b_delete":   false,
+			}
+			history_rule_data["department_isuse"] = m["i_isuse"]
+			history_rule_data["depart_name"] = m["s_name"]
+			depart_rule_data, _ := Mgo.Find("euserdepartrule", q, `{"i_createtime":-1}`, `{"s_name":1,"i_updatetime":1,"i_isuse":1,"_id":1}`, false, 0, 0)
+			if depart_rule_data != nil && len(*depart_rule_data) != 0 {
+				for _, j := range *depart_rule_data {
+					j["_id"] = qu.BsonIdToSId(j["_id"])
+				}
+				history_rule_data["department_rule"] = depart_rule_data
+				history_rule_data["is_slected"] = true
+			}
+			res = append(res, history_rule_data)
+		}
+		s.ServeJson(map[string]interface{}{
+			"status":    "success",
+			"data":      res,
+		})
+	} else {
+		s.ServeJson(map[string]interface{}{
+			"status": "fail",
+			"data":   "",
+		})
+	}
+}
+
+//保存二次推送规则
+func (s *SecondPush) SaveSpushRule() {
+	rules_id := s.GetString("rulesid")
+	s_pushid := s.GetString("s_pushid")
+	// userid := s.GetString("userid")
+	if s_pushid != "" {
+		user_history, _ := Mgo.FindOne("second_push", map[string]interface{}{
+			"_id": mongoutil.StringTOBsonId(s_pushid),
+		})
+		if *user_history != nil && user_history != nil {
+			if (*user_history)["dep_rules"] != nil {
+				dep_rules := qu.ObjArrToMapArr((*user_history)["dep_rules"].([]interface{}))
+				dep_new_rules := []map[string]interface{}{}
+				ruleMap := map[string]bool{}
+				if len(dep_rules) > 0 {
+					for _, r := range dep_rules {
+						dep_new_rules = append(dep_new_rules, r)
+						ruleMap[mongoutil.BsonIdToSId(r["_id"])] = true
+					}
+				}
+				rules_id_list := strings.Split(rules_id, ",")
+				for _, rule := range rules_id_list {
+					if !ruleMap[rule] {
+						query := bson.M{
+							"_id":      mongoutil.StringTOBsonId(rule),
+							"b_delete": false,
+						}
+						res, _ := Mgo.FindOne("euserdepartrule", query)
+						if res != nil && len(*res) != 0 {
+							//获取规则所属部门信息
+							department_info, _ := Mgo.FindOne("euserdepart", map[string]interface{}{
+								"_id":      mongoutil.StringTOBsonId((*res)["s_departid"].(string)),
+								"b_delete": false,
+							})
+							(*res)["is_new"] = false
+							(*res)["s_depart_name"] = (*department_info)["s_name"]
+							dep_new_rules = append(dep_new_rules, *res)
+						}
+					}
+				}
+				set := bson.M{
+					"$set": bson.M{
+						"dep_rules": dep_new_rules,
+						// "tag_rules":  usertags,
+						"updatetime": time.Now().Unix(),
+					},
+				}
+				ok := Mgo.Update("second_push", map[string]interface{}{
+					"_id": mongoutil.StringTOBsonId(s_pushid),
+				}, set, false, false)
+				s.ServeJson(map[string]interface{}{
+					"status": ok,
+				})
+				return
+			} else {
+				rules_id_list := strings.Split(rules_id, ",")
+				dep_rules := []map[string]interface{}{}
+				for _, rule := range rules_id_list {
+					query := bson.M{
+						"_id":      mongoutil.StringTOBsonId(rule),
+						"b_delete": false,
+					}
+					res, _ := Mgo.FindOne("euserdepartrule", query)
+					if res != nil && *res != nil {
+						//获取规则所属部门信息
+						department_info, _ := Mgo.FindOne("euserdepart", map[string]interface{}{
+							"_id":      mongoutil.StringTOBsonId((*res)["s_departid"].(string)),
+							"b_delete": false,
+						})
+						(*res)["is_new"] = false
+						(*res)["s_depart_name"] = (*department_info)["s_name"]
+						dep_rules = append(dep_rules, *res)
+					}
+				}
+				set := bson.M{
+					"$set": bson.M{
+						"dep_rules": dep_rules,
+						// "tag_rules":  usertags,
+						"updatetime": time.Now().Unix(),
+					},
+				}
+				isupdata := Mgo.Update("second_push", map[string]interface{}{
+					"_id": mongoutil.StringTOBsonId(s_pushid),
+				}, set, false, false)
+				s.ServeJson(map[string]interface{}{
+					"status": isupdata,
+				})
+				return
+			}
+
+		}
+		s.ServeJson(map[string]interface{}{
+			"status": "fail",
+		})
+
+	}
+
+}
+
+func (s *SecondPush) SecondPushTask() {
+	log.Println("开始二次推送任务...")
+	s_pushid := s.GetString("s_pushid")
+	if s_pushid != ""{
+		customer, _ := Mgo.Find("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(s_pushid)}, nil, nil, false, -1, -1)
+		if len(*customer) == 1 {
+			c := (*customer)[0]
+			customer_name := qu.ObjToString(c["s_name"]) //客户名称
+			email := qu.ObjToString(c["sendMail"])
+			starttime := qu.Int64All(c["starttime"])
+			endtime := qu.Int64All(c["endtime"])
+			if len(c)!=0&&c != nil{
+				if c["dep_rules"] !=nil&&len(c["dep_rules"].([]interface{}))!=0{
+					for _,m := range c["dep_rules"].([]interface{}){
+						q := bson.M{
+							"ruleid":mongoutil.BsonIdToSId(m.(map[string]interface{})["_id"]),
+							"createtime":bson.M{
+								"$gte":starttime,
+								"$lte":endtime,
+							},
+						}
+						d,_:=MgoSecondPush.Find("usermail",q,nil,nil,false,0,0)
+						if len(*d)>0&&d !=nil{
+							for _,l := range *d{
+								xlsxArr=append(xlsxArr, l)
+							}
+						}
+					}
+				}else{
+					q := bson.M{
+						"appid":c["s_appid"] ,
+						"createtime":bson.M{
+							"$gte":starttime,
+							"$lte":endtime,
+						},
+					}
+					d,_:=MgoSecondPush.Find("usermail",q,nil,nil,false,0,0)
+					for _,l := range *d{
+						xlsxArr=append(xlsxArr, l)
+					}
+				}
+				if len(xlsxArr) == 0{
+					log.Println("查询数据为空")
+				}else{
+					log.Println(len(xlsxArr))
+					GetXlsxs(xlsxArr, customer_name, email, s_pushid)
+					go UpdateHistoryState(2, s_pushid, len(xlsxArr))
+					xlsxArr =[]map[string]interface{}{}
+				}
+			}
+		} else {
+			log.Println("初始化客户信息失败")
+		}
+
+	}
+
+}
+
+//func (s *SecondPush) HistoryList() {
+//	id := s.GetString("id")
+//	if s.Method() == "POST" {
+//		data, _ := Mgo.Find("second_push", map[string]interface{}{"user_id": id}, `{"updatetime":-1}`, nil, false, -1, -1)
+//		s.ServeJson(map[string]interface{}{
+//			"data": data,
+//		})
+//	} else {
+//		s.T["id"] = id
+//		s.Render("private/historylog_list.html", &s.T)
+//	}
+//}
+
+func UpdateHistoryState(state int, s_pushid string, count int) {
+	if state == 2 {
+		Mgo.Update("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(s_pushid)}, map[string]interface{}{
+			"$set": map[string]interface{}{
+				"state":        state,
+				"result_count": count,
+			},
+		}, false, false)
+		return
+	}
+
+	Mgo.Update("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(s_pushid)}, map[string]interface{}{
+		"$set": map[string]interface{}{
+			"state": state,
+		},
+	}, false, false)
+}
+
+func (s *SecondPush) HistoryClone(hid string) {
+	data, ok := Mgo.FindOne("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(hid)})
+	if ok && data != nil && *data != nil {
+		(*data)["state"] = 0
+		(*data)["result_count"] = nil
+		(*data)["createtime"] = time.Now().Unix()
+		(*data)["updatetime"] = time.Now().Unix()
+		Mgo.Save("second_push", *data)
+	}
+}
+
+func (s *SecondPush) HistoryRuleEdit() {
+	hid := s.GetString("hid")
+	rid := s.GetString("rid")
+	if s.Method() == "POST" {
+		data := GetPostForm(s.Request)
+		o_rules := []map[string]interface{}{}
+		o_rulesStr := data["o_rules"].(string)
+		json.Unmarshal([]byte(o_rulesStr), &o_rules)
+		data["o_rules"] = o_rules
+		data["_id"] = mongoutil.StringTOBsonId(rid)
+		if qu.IntAll(data["i_esquerytype"]) == 1 { //自动生成es
+			data["s_esquery"] = Utiltags(data)
+		}
+		datas, ok := Mgo.FindOne("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(hid)})
+		if ok && datas != nil && *datas != nil {
+			dep_rules := qu.ObjArrToMapArr((*datas)["dep_rules"].([]interface{}))
+			for k, v := range dep_rules {
+				if rid == mongoutil.BsonIdToSId(v["_id"]) {
+					dep_rules[k] = data
+				}
+			}
+			rep := Mgo.Update("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(hid)}, map[string]interface{}{"$set": map[string]interface{}{"dep_rules": dep_rules}}, false, false)
+			s.ServeJson(map[string]interface{}{
+				"rep":       rep,
+				"s_esquery": data["s_esquery"],
+			})
+		}
+	} else {
+		id := s.GetString("id")
+		data, ok := Mgo.FindOne("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(hid)})
+		if ok && data != nil && *data != nil {
+			dep_rules := qu.ObjArrToMapArr((*data)["dep_rules"].([]interface{}))
+			for _, v := range dep_rules {
+				if rid == mongoutil.BsonIdToSId(v["_id"]) {
+					s.T["data"] = v
+				}
+			}
+		}
+		s.T["did"] = id //部门id
+		s.T["cid"] = id //客户id
+		s.T["ids"] = id
+		s.T["history_id"] = hid
+		s.T["rid"] = rid
+		s.T["province"] = Province
+		s.T["city"] = ProvinceCitys
+		s.T["district"] = CityDistricts
+		s.T["topTypeArr"] = TopTypeArr
+		s.T["subTypeArr"] = SubTypeArr
+		s.T["matchTypeMap"] = MatchTypeMap
+		s.T["matchTypeMap2"] = MatchTypeMap2
+		s.T["existField"] = ExistFiled
+		s.T["buyerClass"] = BuyerClass
+		s.T["scopeClass"] = ScopeClassMap
+		s.Render("private/history_rule_edit.html", &s.T)
+	}
+}
+
+func GetXlsxs(mMap []map[string]interface{}, fn, email, id string) {
+	if id != "" {
+		query := bson.M{
+			"_id": bson.ObjectIdHex(id),
+		}
+		data, ok := Mgo.FindOne("second_push", query)
+		if ok && (*data) != nil && len(*data) > 0 {
+			dataType := qu.IntAll((*data)["i_extfieldstype"])
+			xf, err := xlsx.OpenFile("web/res/fields.xlsx")
+			if err != nil {
+				log.Println("fields file not foud", err.Error())
+			}
+			if dataType == 1 {
+				sh := xf.Sheets[0]
+				for i, v := range mMap {
+					row := sh.AddRow()
+					row.AddCell().SetInt(i + 1)
+					row.AddCell().SetValue(v["matchkey"])
+					row.AddCell().SetValue(v["area"])
+					row.AddCell().SetValue(v["city"])
+					row.AddCell().SetValue(v["title"])
+					row.AddCell().SetValue(v["subtype"])
+					if v["publishtime"] != nil {
+						row.AddCell().SetValue(time.Unix(qu.Int64All(v["publishtime"]), 0).Format("2006-01-02"))
+					} else {
+						row.AddCell()
+					}
+					row.AddCell().SetValue(v["buyer"])
+					row.AddCell().SetValue(v["winner"])
+					if v["bidamount"] != nil {
+						row.AddCell().SetFloat(qu.Float64All(v["bidamount"]) / 10000)
+					} else {
+						row.AddCell()
+					}
+					row.AddCell().SetValue(v["projectname"])
+					row.AddCell().SetValue(v["detail"])
+					row.AddCell().SetValue(v["s_jyhref"])
+				}
+				xf.Sheets = xf.Sheets[0:1]
+			} else if dataType == 2 {
+				sh := xf.Sheets[1]
+				for i, v := range mMap {
+					row := sh.AddRow()
+					row.AddCell().SetInt(i + 1)
+					row.AddCell().SetValue(v["matchkey"])
+					row.AddCell().SetValue(v["area"])
+					row.AddCell().SetValue(v["city"])
+					row.AddCell().SetValue(v["title"])
+					row.AddCell().SetValue(v["subtype"])
+					row.AddCell().SetValue(v["detail"])
+					if v["publishtime"] != nil {
+						row.AddCell().SetValue(time.Unix(qu.Int64All(v["publishtime"]), 0).Format("2006-01-02"))
+					} else {
+						row.AddCell()
+					}
+					row.AddCell().SetValue(v["href"])
+					row.AddCell().SetValue(v["s_jyhref"])
+					row.AddCell().SetValue(v["projectcode"])
+					row.AddCell().SetValue(v["projectname"])
+					row.AddCell().SetValue(v["projectscope"])
+					if v["budget"] != nil {
+						row.AddCell().SetFloat(qu.Float64All(v["budget"]) / 10000)
+					} else {
+						row.AddCell()
+					}
+					if v["bidamount"] != nil {
+						row.AddCell().SetFloat(qu.Float64All(v["bidamount"]) / 10000)
+					} else {
+						row.AddCell()
+					}
+					if v["bidopentime"] != nil {
+						row.AddCell().SetValue(time.Unix(qu.Int64All(v["bidopentime"]), 0).Format("2006-01-02"))
+					} else {
+						row.AddCell()
+					}
+					row.AddCell().SetValue(v["buyer"])
+					row.AddCell().SetValue(v["buyerperson"])
+					row.AddCell().SetValue(v["buyertel"])
+					row.AddCell().SetValue(v["agency"])
+					row.AddCell().SetValue(v["winner"])
+					row.AddCell().SetValue(v["winnerperson"])
+					row.AddCell().SetValue(v["winnertel"])
+					row.AddCell().SetValue(v["legal_person"])
+					row.AddCell().SetValue(v["company_phone"])
+					row.AddCell().SetValue(v["company_email"])
+				}
+				xf.Sheets = xf.Sheets[1:2]
+			} else {
+				sh := xf.Sheets[2]
+				for i, v := range mMap {
+					row := sh.AddRow()
+					row.AddCell().SetInt(i + 1)
+					row.AddCell().SetValue(v["matchkey"])
+					row.AddCell().SetValue(v["area"])
+					row.AddCell().SetValue(v["city"])
+					row.AddCell().SetValue(v["district"])
+					row.AddCell().SetValue(v["title"])
+					row.AddCell().SetValue(v["detail"])
+					if v["publishtime"] != nil {
+						row.AddCell().SetValue(time.Unix(qu.Int64All(v["publishtime"]), 0).Format("2006-01-02"))
+					} else {
+						row.AddCell()
+					}
+					row.AddCell().SetValue(v["href"])
+					if v["bidamount"] != nil {
+						row.AddCell().SetFloat(qu.Float64All(v["bidamount"]) / 10000)
+					} else {
+						row.AddCell()
+					}
+					row.AddCell().SetValue(v["buyer"])
+					row.AddCell().SetValue(v["buyerperson"])
+					row.AddCell().SetValue(v["buyertel"])
+					row.AddCell().SetValue(v["s_winner"])
+					row.AddCell().SetValue(v["legal_person"])
+					row.AddCell().SetValue(v["company_phone"])
+					row.AddCell().SetValue(v["company_address"])
+					row.AddCell().SetValue(v["rank"])
+					row.AddCell().SetValue(v["purchasing"])
+					row.AddCell().SetValue(v["capital"])
+					row.AddCell().SetValue(v["establish_date"])
+					row.AddCell().SetValue(v["business_scope"])
+					row.AddCell().SetValue(v["stock_name"])
+					row.AddCell().SetValue(v["buyer_credit_no"])
+					row.AddCell().SetValue(v["winner_credit_no"])
+					row.AddCell().SetValue(v["id"])
+				}
+				xf.Sheets = xf.Sheets[2:3]
+			}
+			//生文件
+			t := strconv.FormatInt(time.Now().Unix(), 10)
+			dir := "./web/res/xlsx/" + t + "/"
+			if b, _ := history.PathExists(dir); !b {
+				err1 := os.MkdirAll(dir, os.ModePerm)
+				if err1 != nil {
+					log.Println("mkdir err", dir)
+				}
+			}
+			fname := t + ".xlsx"
+			err = xf.Save(dir + fname)
+			if err != nil {
+				log.Println("xls error", fname)
+			} else {
+				for i := 0; i < len(history.Gmails); i++ {
+					gmail := history.Gmails[i]
+					status := mail.GSendMail_q("剑鱼标讯", email, "", "", fn, "", dir+fname, fname, gmail)
+					if status {
+						log.Println("send mail success", fname, email)
+						break
+					}
+				}
+			}
+		}
+	}
+}
+
+func (s *SecondPush) AddSecondPushRule() {
+	defer qu.Catch()
+	if s.Method() == "POST" {
+		his_id := s.GetString("s_pushid")
+		if his_id != "" {
+			i_updatetime, _ := strconv.ParseInt(s.GetString("i_updatetime"), 10, 64)
+			i_extfieldstype, _ := strconv.Atoi(s.GetString("i_extfieldstype"))
+			set := bson.M{
+				"$set": bson.M{
+					"i_updatetime":    i_updatetime,
+					"sendMail":        s.GetString("sendMail"),
+					"i_extfieldstype": i_extfieldstype,
+					"starttime":       s.GetString("starttime"),
+					"endtime":       s.GetString("endtime"),
+				},
+			}
+			isupdata := Mgo.UpdateById("second_push", mongoutil.StringTOBsonId(his_id), set)
+			if isupdata {
+				s.ServeJson(map[string]interface{}{
+					"history_id": his_id,
+					"rep":        true,
+				})
+			} else {
+				s.ServeJson(map[string]interface{}{
+					"history_id": "",
+					"rep":        false,
+				})
+			}
+		}
+
+	}
+}
+
+func (s *SecondPush) SecondPushList() {
+	id := s.GetString("id")
+	if s.Method() == "POST" {
+		data, _ := Mgo.Find("second_push", map[string]interface{}{"user_id": id}, `{"updatetime":-1}`, nil, false, -1, -1)
+		s.ServeJson(map[string]interface{}{
+			"data": data,
+		})
+	}
+}
+
+func (s *SecondPush) SecondPushClone(hid string) {
+	data, ok := Mgo.FindOne("second_push", map[string]interface{}{"_id": mongoutil.StringTOBsonId(hid)})
+	if ok && data != nil && *data != nil {
+		(*data)["state"] = 0
+		(*data)["result_count"] = nil
+		(*data)["createtime"] = time.Now().Unix()
+		(*data)["updatetime"] = time.Now().Unix()
+		Mgo.Save("second_push", *data)
+	}
+}
+
+func (s *SecondPush) DelSecondPushRule() {
+	id := s.GetString("id")
+	hid := s.GetString("s_pushid")
+	if hid != "" {
+		data, ok := Mgo.FindOne("second_push", bson.M{"_id": mongoutil.StringTOBsonId(hid)})
+		if ok && data != nil && *data != nil {
+			if (*data)["dep_rules"] != nil {
+				dep_rules := qu.ObjArrToMapArr((*data)["dep_rules"].([]interface{}))
+				ruleMap := map[string]bool{id: true}
+				ruleArr := []map[string]interface{}{}
+				for _, m := range dep_rules {
+					if !ruleMap[mongoutil.BsonIdToSId(m["_id"])] {
+						ruleArr = append(ruleArr, m)
+					}
+				}
+				ok := Mgo.Update("second_push", bson.M{"_id": mongoutil.StringTOBsonId(hid)}, bson.M{"$set": bson.M{"dep_rules": ruleArr}}, false, false)
+				s.ServeJson(map[string]interface{}{
+					"success": ok,
+				})
+			}
+		}
+	}
+}

+ 8 - 0
src/util/config.go

@@ -22,6 +22,7 @@ var (
 	MgoSave         *mgo.MongodbSim //数据保存库连接
 	MgoBuyer        *mgo.MongodbSim //医院等级信息
 	MgoEnps         *mgo.MongodbSim //企业信息
+	MgoSecondPush   *mongodb.MongodbSim //二次推送
 	SaveColl        string
 	HospColl        string
 	BuyerEntColl    string
@@ -203,6 +204,13 @@ func initdb() {
 		Size:        qu.IntAllDef(buyerinfo["size"], 15),
 	}
 	MgoBuyer.InitPool()
+	second_push := Sysconfig["second_push"].(map[string]interface{})
+	MgoSecondPush = &mongodb.MongodbSim{
+		MongodbAddr: qu.ObjToString(second_push["addr"]),
+		DbName:      qu.ObjToString(second_push["db"]),
+		Size:        qu.IntAllDef(second_push["size"], 15),
+	}
+	MgoSecondPush.InitPool()
 	//mgo enterprise
 	enterprise := Sysconfig["enterprise"].(map[string]interface{})
 	EnpsColl = qu.ObjToString(enterprise["coll"])

+ 1 - 1
src/web/templates/login.html

@@ -25,7 +25,7 @@
   <![endif]-->
 
   <!-- Google Font -->
-  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
+  <!-- <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">--->
 </head>
 <body class="hold-transition login-page">
 <div class="login-box">

+ 330 - 129
src/web/templates/private/historylog_list.html

@@ -6,8 +6,8 @@
 
 <div class="content-wrapper" id="showbtn">
     <section class="content-header">
-        <h1>
-            <small><a id="addWork" class="btn btn-primary opr">新增任务</a></small>
+        <h1>
+            <small><a id="addWork" class="btn btn-primary opr" onclick="addwork()">新增任务</a></small>
         </h1>
         <ol class="breadcrumb">
             <li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li>
@@ -16,30 +16,63 @@
     </section>
     <!-- Main content -->
     <section class="content">
-        <div class="row">
-            <div class="col-xs-12">
-                <div class="box">
-                    <div class="box-body">
-                        <table id="dataTable" class="table table-bordered table-hover">
-                            <thead>
-                                <tr>
-                                    <th>序号</th>
-                                    <th>ID</th>
-                                    <th>操作人</th>
-                                    <th>状态</th>
-                                    <th>数据总量</th>
-                                    <th>创建时间</th>
-                                    <th>修改时间</th>
-                                    <th>操作</th>
-                                </tr>
-                            </thead>
-                        </table>
+        <div class="tab-content">
+            <div class="nav-tabs-custom">
+                <ul class="nav nav-tabs edit-step">
+                    <li class="active" data-mode="guide" id="showHistory"><a href="#tab_1" data-toggle="tab" aria-expanded="true">历史任务</a></li>
+                    <li data-mode="guide" class="tab_2" id="showSecondPush"><a href="#tab_2" data-toggle="tab" aria-expanded="false" >二次推送</a></li>
+                </ul>
+                <div class="row" id="history-task-list">
+                    <div class="col-xs-12">
+                        <div class="box">
+                            <div class="box-body">
+                                <table id="dataTable" class="table table-bordered table-hover">
+                                    <thead>
+                                    <tr>
+                                        <th>序号</th>
+                                        <th>ID</th>
+                                        <th>操作人</th>
+                                        <th>状态</th>
+                                        <th>数据总量</th>
+                                        <th>创建时间</th>
+                                        <th>修改时间</th>
+                                        <th>操作</th>
+                                    </tr>
+                                    </thead>
+                                </table>
+                            </div>
+                            <!-- /.box-body -->
+                        </div>
+                        <!-- /.box -->
+                    </div>
+                </div>
+                <div class="row" id="second-push-list">
+                    <div class="col-xs-12">
+                        <div class="box">
+                            <div class="box-body">
+                                <table id="sdataTable" class="table table-bordered table-hover">
+                                    <thead>
+                                    <tr>
+                                        <th>序号</th>
+                                        <th>ID</th>
+                                        <th>操作人</th>
+                                        <th>状态</th>
+                                        <th>数据总量</th>
+                                        <th>创建时间</th>
+                                        <th>修改时间</th>
+                                        <th>操作</th>
+                                    </tr>
+                                    </thead>
+                                </table>
+                            </div>
+                            <!-- /.box-body -->
+                        </div>
+                        <!-- /.box -->
                     </div>
-                    <!-- /.box-body -->
                 </div>
-                <!-- /.box -->
             </div>
         </div>
+
     </section>
 </div>
 {{include "com/footer.html"}}
@@ -85,38 +118,155 @@
                     "data": "_id"
                 },
                 {
-                    "data": "create_user",
-                    render: function(val) {
-                        if(val === undefined){
-                           return ""
-                        }else{
-                            return val
-                        }
+                    "data": "create_user",
+                    render: function(val) {
+                        if(val === undefined){
+                           return ""
+                        }else{
+                            return val
+                        }
+                    }
+                },
+                {
+                    "data": "state",
+                    render: function(val) {
+                        var str = "";
+                        if(val === 0 || val === undefined){
+                            str = "未执行";
+                        }else if(val === 1){
+                            str = "未完成";
+                        }else if(val === 2){
+                            str = "已完成";
+                        }
+                        return str
+                    }
+                },
+                {
+                    "data": "result_count",
+                    render: function(val) {
+                        if(val === undefined || val === null || val === ""){
+                           return "未执行"
+                        }else{
+                            return val
+                        }
+                    }
+                },
+                {
+                    "data": "createtime",
+                    render: function(val) {
+                        var dt = new Date()
+                        dt.setTime(parseInt(val) * 1000)
+                        return dt.format("yyyy-MM-dd hh:mm:ss")
+                    }
+                },
+                {
+                    "data": "updatetime",
+                    render: function(val) {
+                        var dt = new Date()
+                        dt.setTime(parseInt(val) * 1000)
+                        return dt.format("yyyy-MM-dd hh:mm:ss")
+                    }
+                },
+                {
+                    "data": "_id", width:"16%",
+                    render: function (val, a, row) {
+                        var tmp = "";
+                        if(row.state === 2){
+                            tmp = '<div>' +
+                              '<a class="btn btn-sm btn-primary" href="/service/customer/history?id='+ row.user_id +'&hid='+ val +'">编辑</a>' +
+                              '<a style="margin-left:10px" class="btn btn-sm btn-success" disabled>完成</a>' +
+                              '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
+                              '</div>';
+                        }else if(row.state === 1){
+                            tmp = '<div>' +
+                              '<a class="btn btn-sm btn-primary" href="/service/customer/history?id='+ row.user_id +'&hid='+ val +'">编辑</a>' +
+                              '<a style="margin-left:10px" class="btn btn-sm btn-info">进行</a>' +
+                              '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
+                              '</div>';
+                        }else{
+                            tmp = '<div>' +
+                              '<a class="btn btn-sm btn-primary" href="/service/customer/history?id='+ row.user_id +'&hid='+ val +'">编辑</a>' +
+                              '<a style="margin-left:10px" class="btn btn-sm btn-default" eid="'+val+'" onclick="historyWork(this)">执行</a>' +
+                              '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
+                              '</div>';
+                        }
+                        return tmp
+                    }
+                }
+            ]
+        });
+        stable = $('#sdataTable').DataTable({
+            "paging": true,
+            "lengthChange": false,
+            "searching": false,
+            "ordering": false,
+            "info": true,
+            "autoWidth": false,
+            "ajax": {
+                "url": "/service/secondpush/list",
+                "type": "post",
+                "data": {
+                    "id": {{.T.id}}
+                }
+            },
+            "language": {
+                "url": "/dist/js/dataTables.chinese.lang"
+            },
+            "fnDrawCallback": function() {
+                $("ul.pagination").prepend(
+                    "&nbsp;&nbsp;&nbsp;转到第 <input type='text' id='s_changePage'   style='width:20px;'> 页    <a type='text' href='javascript:void(0);' id='sdataTable-btn' style='text-align:center'>GO</a>"
+                );
+                $('#sdataTable-btn').click(function(e) {
+                    var s_redirectpage = 0
+                    if ($("#s_changePage").val() && $("#s_changePage").val() > 0) {
+                        var s_redirectpage = $("#s_changePage").val() - 1;
+                    }
+                    stable.page(s_redirectpage).draw(false);
+                });
+                this.api().column(0).nodes().each(function(cell, i) {
+                    cell.innerHTML = i + 1;
+                });
+            },
+            "columns": [{
+                "data": null,
+                width: "5%"
+            },
+                {
+                    "data": "_id"
+                },
+                {
+                    "data": "create_user",
+                    render: function(val) {
+                        if(val === undefined){
+                            return ""
+                        }else{
+                            return val
+                        }
+                    }
+                },
+                {
+                    "data": "state",
+                    render: function(val) {
+                        var str = "";
+                        if(val === 0 || val === undefined){
+                            str = "未执行";
+                        }else if(val === 1){
+                            str = "未完成";
+                        }else if(val === 2){
+                            str = "已完成";
+                        }
+                        return str
                     }
                 },
                 {
-                    "data": "state",
-                    render: function(val) {
-                        var str = "";
-                        if(val === 0 || val === undefined){
-                            str = "未执行";
-                        }else if(val === 1){
-                            str = "未完成";
-                        }else if(val === 2){
-                            str = "已完成";
-                        }
-                        return str
-                    }
-                },
-                {
-                    "data": "result_count",
-                    render: function(val) {
-                        if(val === undefined || val === null || val === ""){
-                           return "未执行"
-                        }else{
-                            return val
-                        }
-                    }
+                    "data": "result_count",
+                    render: function(val) {
+                        if(val === undefined || val === null || val === ""){
+                            return "未执行"
+                        }else{
+                            return val
+                        }
+                    }
                 },
                 {
                     "data": "createtime",
@@ -125,84 +275,135 @@
                         dt.setTime(parseInt(val) * 1000)
                         return dt.format("yyyy-MM-dd hh:mm:ss")
                     }
-                },
-                {
-                    "data": "updatetime",
-                    render: function(val) {
-                        var dt = new Date()
-                        dt.setTime(parseInt(val) * 1000)
-                        return dt.format("yyyy-MM-dd hh:mm:ss")
-                    }
-                },
-                {
-                    "data": "_id", width:"16%",
-                    render: function (val, a, row) {
-                        var tmp = "";
-                        if(row.state === 2){
-                            tmp = '<div>' +
-                              '<a class="btn btn-sm btn-primary" href="/service/customer/history?id='+ row.user_id +'&hid='+ val +'">编辑</a>' +
-                              '<a style="margin-left:10px" class="btn btn-sm btn-success" disabled>完成</a>' +
-                              '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
-                              '</div>';
-                        }else if(row.state === 1){
-                            tmp = '<div>' +
-                              '<a class="btn btn-sm btn-primary" href="/service/customer/history?id='+ row.user_id +'&hid='+ val +'">编辑</a>' +
-                              '<a style="margin-left:10px" class="btn btn-sm btn-info">进行</a>' +
-                              '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
-                              '</div>';
-                        }else{
-                            tmp = '<div>' +
-                              '<a class="btn btn-sm btn-primary" href="/service/customer/history?id='+ row.user_id +'&hid='+ val +'">编辑</a>' +
-                              '<a style="margin-left:10px" class="btn btn-sm btn-default" eid="'+val+'" onclick="historyWork(this)">执行</a>' +
-                              '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
-                              '</div>';
-                        }
-                        return tmp
-                    }
+                },
+                {
+                    "data": "updatetime",
+                    render: function(val) {
+                        var dt = new Date()
+                        dt.setTime(parseInt(val) * 1000)
+                        return dt.format("yyyy-MM-dd hh:mm:ss")
+                    }
+                },
+                {
+                    "data": "_id", width:"16%",
+                    render: function (val, a, row) {
+                        var tmp = "";
+                        if(row.state === 2){
+                            tmp = '<div>' +
+                                '<a class="btn btn-sm btn-primary" href="/service/secondpush/create?id='+ row.user_id +'&s_pushid='+ val +'">编辑</a>' +
+                                '<a style="margin-left:10px" class="btn btn-sm btn-success" disabled>完成</a>' +
+                                '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
+                                '</div>';
+                        }else if(row.state === 1){
+                            tmp = '<div>' +
+                                '<a class="btn btn-sm btn-primary" href="/service/secondpush/create?id='+ row.user_id +'&s_pushid='+ val +'">编辑</a>' +
+                                '<a style="margin-left:10px" class="btn btn-sm btn-info">进行</a>' +
+                                '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
+                                '</div>';
+                        }else{
+                            tmp = '<div>' +
+                                '<a class="btn btn-sm btn-primary" href="/service/secondpush/create?id='+ row.user_id +'&s_pushid='+ val +'">编辑</a>' +
+                                '<a style="margin-left:10px" class="btn btn-sm btn-default" eid="'+val+'" onclick="historyWork(this)">执行</a>' +
+                                '<a style="margin-left:10px" class="btn btn-sm btn-info" eid="'+val+'" onclick="cloneWork(this)">克隆</a>' +
+                                '</div>';
+                        }
+                        return tmp
+                    }
                 }
             ]
-        });
-        
-        $("#addWork").on("click",function(){
-            window.location.href = "/service/customer/history?id="+ {{.T.id}};
-        })
-    });
-    
-    function historyWork(obj){
-        var ok = confirm("是否确定执行?");
-        if (ok){
-            var val = $(obj).attr("eid");
-            $(obj).removeClass("btn-default").addClass("btn-info");
-            $(obj).text("进行");
-            $.ajax({
-                url: "/service/history/"+ val,
-                type: 'POST',
-                success: function(r) {
-                    $(obj).removeClass("btn-info").addClass("btn-success").attr("disabled","disabled");
-                    $(obj).text("完成");
-                },
-                error: function (r) {
-                    $(obj).removeClass("btn-info").addClass("btn-danger");
-                    $(obj).text("失败");
-                }
-            })
-        }
-    }
-    
-    function cloneWork(obj){
-        var ok = confirm("是否确定克隆?");
-        if (ok){
-            var val = $(obj).attr("eid");
-            $.ajax({
-                url: "/service/historyClone/"+ val,
-                type: 'POST',
-                success: function(r) {
-                    window.location.reload();
-                },
-                error: function (r) {
-                    alert("克隆失败!");
-                }
-            })
-        }
+        });
+
+    });
+    
+    function historyWork(obj){
+        var ok = confirm("是否确定执行?");
+        if (ok){
+            $(obj).removeClass("btn-default").addClass("btn-info");
+            $(obj).text("进行");
+            var ishistory = $("#showHistory").hasClass("active")
+            var val = $(obj).attr("eid");
+            if (ishistory){
+                $.ajax({
+                    url: "/service/history/"+ val,
+                    type: 'POST',
+                    success: function(r) {
+                        $(obj).removeClass("btn-info").addClass("btn-success").attr("disabled","disabled");
+                        $(obj).text("完成");
+                    },
+                    error: function (r) {
+                        $(obj).removeClass("btn-info").addClass("btn-danger");
+                        $(obj).text("失败");
+                    }
+                })
+            }else{
+                $.ajax({
+                    url: "/service/secondpush/dotask",
+                    type: 'POST',
+                    data:{"s_pushid":val},
+                    success: function(r) {
+                        $(obj).removeClass("btn-info").addClass("btn-success").attr("disabled","disabled");
+                        $(obj).text("完成");
+                    },
+                    error: function (r) {
+                        $(obj).removeClass("btn-info").addClass("btn-danger");
+                        $(obj).text("失败");
+                    }
+                })
+            }
+
+
+        }
+    }
+    
+    function cloneWork(obj){
+        var ok = confirm("是否确定克隆?");
+        if (ok){
+            var ishistory = $("#showHistory").hasClass("active")
+            var val = $(obj).attr("eid");
+            if (ishistory){
+                $.ajax({
+                    url: "/service/historyClone/"+ val,
+                    type: 'POST',
+                    success: function(r) {
+                        window.location.reload();
+                    },
+                    error: function (r) {
+                        alert("克隆失败!");
+                    }
+                })
+            }else{
+                $.ajax({
+                    url: "/service/secondPushClone/"+ val,
+                    type: 'POST',
+                    success: function(r) {
+                        window.location.reload();
+                    },
+                    error: function (r) {
+                        alert("克隆失败!");
+                    }
+                })
+            }
+
+        }
     }
-</script>
+
+    function addwork() {
+        var isactive = $("#showHistory").hasClass("active")
+        if (isactive){
+            window.location.href = "/service/customer/history?id="+ {{.T.id}};
+        }else{
+            window.location.href = "/service/secondpush/create?id="+ {{.T.id}};
+        }
+    }
+
+    $("#showHistory").on("click",function () {
+        $("#second-push-list").hide()
+        $("#history-task-list").show()
+    })
+
+    $("#showSecondPush").on("click",function () {
+        $("#history-task-list").hide()
+        $("#second-push-list").show()
+
+    })
+</script>

+ 557 - 0
src/web/templates/private/second_push_create.html

@@ -0,0 +1,557 @@
+{{include "com/inc.html"}}
+<!-- Main Header -->
+{{include "com/header.html"}}
+<!-- Left side column. 权限菜单 -->
+{{include "com/menu.html"}}
+<script src="/time/js/angular.min.js"></script>
+<script src="/time/js/wui-date.js"></script>
+<div class="content-wrapper">
+    <section class="content-header">
+        <h1>编辑客户
+        </h1>
+        <ol class="breadcrumb">
+            <li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li>
+            <li><a href="/service/customer/list"> 客户列表</a></li>
+            <li><a href="#"> 编辑客户</a></li>
+        </ol>
+    </section>
+    <!-- Main content -->
+    <section class="content">
+        <div class="tab-content">
+            <div class="nav-tabs-custom">
+                <ul class="nav nav-tabs edit-step">
+                    <li class="active" data-mode="guide"><a href="#tab_1" data-toggle="tab" aria-expanded="true">选择规则</a></li>
+                </ul>
+                <div class="tab-content">
+                    <div class="tab-pane active" id="tab_1">
+                        <form class="form-horizontal">
+                            <div class="box box-primary">
+                                <div class="box-header with-border">
+                                    <i class="fa fa-tag"></i>
+                                    <h3 class="box-title">用户基本信息</h3>
+                                    <a class="btn btn-primary btn-sm" style="float: right;margin-top: 7px;margin-right: 10px" onclick="saveCuser()"><i class="fa fa-fw fa-file-text fa-lg"></i>保存</a>
+                                </div>
+                                <div class="box-body">
+                                    <div class="form-group">
+                                        <label class="col-sm-2 control-label"><span style="color:red;">* </span>客户名称</label>
+                                        <div class="col-sm-2">
+                                            <input type="text" class="form-control" id="customername" placeholder="公司名称"
+                                                   value="{{.T.data.s_name}}" required disabled>
+                                        </div>
+                                        <label class="col-sm-2 control-label"><span style="color:red;">* </span>销售人员</label>
+                                        <div class="col-sm-2">
+                                            <input type="text" class="form-control" id="seller" placeholder="销售人员名称"
+                                                   value="{{.T.data.s_salesperson}}" required disabled>
+                                        </div>
+                                        <label class="col-sm-2 control-label">客户联系人</label>
+                                        <div class="col-sm-2">
+                                            <input type="text" class="form-control" id="contract" placeholder="客户联系人名称"
+                                                   value="{{.T.data.s_customername}}" disabled>
+                                        </div>
+                                    </div>
+                                    <div id="pushDiv">
+                                        <div class="box-header with-border">
+                                            <i class="fa fa-tag"></i>
+                                            <h3 class="box-title">推送设置</h3>
+                                        </div>
+                                        <div class="box-body">
+                                            <div class="form-group">
+                                                <label class="col-sm-2 control-label">发送邮箱</label>
+                                                <div class="col-sm-2">
+                                                    <input type="text" class="form-control" id="sendMail" placeholder="发送邮箱"
+                                                           value="{{.T.data.sendMail}}">
+                                                </div>
+                                               <label class="col-sm-2 control-label ">字段包</label>
+                                                <div class="col-sm-2">
+                                                    <select class="form-control selectpicker" id="extfiledselect">
+                                                        <option value="2">高级字段包</option>
+                                                        <option value="1">初级字段包</option>
+                                                        <option value="3">特殊字段包</option>
+                                                    </select>
+                                                    <script>
+                                                        $('#extfiledselect').on("change", function () {
+                                                            dataMap["i_extfieldstype"] = $('#extfiledselect option:selected').val();
+                                                        })
+                                                    </script>
+                                                </div>
+                                            </div>
+                                            <div class="form-group">
+                                                <label class="col-sm-2 control-label ">开始时间</label>
+                                                <div class="col-sm-2">
+                                                    <div class="wui-content">
+                                                        <div class="wui-area" id="starttime">
+                                                            <wui-date
+                                                                    format="yyyy-mm-dd hh:mm:ss"
+                                                                    placeholder="请选择或输入开始日期"
+                                                                    id="date4"
+                                                                    btns="{'ok':'确定','now':'此刻'}"
+                                                                    ng-model="date4">
+                                                            </wui-date>
+                                                        </div>
+                                                    </div>
+                                                </div>
+                                                <label class="col-sm-2 control-label ">结束时间</label>
+                                                <div class="col-sm-2">
+                                                    <div class="wui-content">
+                                                        <div class="wui-area" id="endtime" >
+                                                            <wui-date
+                                                                    format="yyyy-mm-dd hh:mm:ss"
+                                                                    placeholder="请选择或输入结束日期"
+                                                                    id="date4"
+                                                                    btns="{'ok':'确定','now':'此刻'}"
+                                                                    ng-model="date5">
+                                                            </wui-date>
+                                                        </div>
+                                                    </div>
+                                                </div>
+                                            </div>
+                                        </div>
+                                    </div>
+                                    <div class="box-header with-border">
+                                        <i class="fa fa-tag"></i>
+                                        <h3 class="box-title">选择规则</h3>
+                                    </div>
+                                    <table id="departTable" class="table table-bordered">
+                                        <thead>
+                                        <div style="margin: 10px 10px 0px;">
+                                            <a class="btn btn-default" onclick="select_Depart()">选择</a>
+                                        </div>
+                                        <tr class="show-select">
+                                            <th>编号</th>
+                                            <th>部门名称</th>
+                                            <th>规则名称</th>
+                                            <th>修改时间</th>
+                                            <th>部门状态</th>
+                                            <th>规则状态</th>
+                                            <th>操作</th>
+                                        </tr>
+                                        </thead>
+                                        <tbody class="selected-rules">
+
+                                        </tbody>
+                                    </table>
+                                </div>
+                            </div>
+                        </form>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </section>
+</div>
+
+
+<!--二次推送规则-->
+<div class="modal fade" id="modal-history" tabindex="-1" role="dialog" aria-hidden="true">
+    <div class="modal-dialog" style="width: 80%">
+        <div class="modal-content">
+            <div class="modal-header">
+                <div class="modal-header">
+                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
+                    <div class="edit-form">
+                        <div class="edit-info">
+                            <span class="glyphicon glyphicon-ok-sign" aria-hidden="true"></span>
+                            <span>选择规则</span>
+                        </div>
+                        <table id="historyRule" class="table table-bordered">
+                            <thead>
+                            <tr>
+                                <th><input type="checkbox" id="selrow" onclick="allSelect(this)"/></th>
+                                <th>编号</th>
+                                <th>部门名称</th>
+                                <th>规则名称</th>
+                                <th>修改时间</th>
+                                <th>部门状态</th>
+                                <th>规则状态</th>
+                                <th class="hidden">规则id  </th>
+
+                            </tr>
+                            </thead>
+                            <tbody class="history_rules"></tbody>
+                        </table>
+                    </div>
+                </div>
+                <div class="modal-footer">
+                    <input type="button" onclick="saveHistoryRule(this)" class="btn btn-primary saveBtn" value="确定">
+                    <input type="button" onclick="cancelModel()" class="btn btn-default" style="margin-left: 24px"
+                           value="取消">
+                </div>
+            </div>
+        </div>
+    </div><!-- /.modal -->
+</div>
+{{include "com/footer.html"}}
+<script>
+    menuActive("/customer/list");
+    var dataMap = {{.T.data}}
+    var tagruleArr = []
+    var ruleArr = []
+    var app = angular.module('app', ["wui.date"]);
+    var history_id = {{.T.history_id}}
+    var selectIndex = [];               //选中的编号
+    var history_rule = {{.T.spush_rule}};
+    var rules_id = new Array();
+    var selected_rules = [];
+    var c_id = getParam("id");
+    var s_pushid = getParam("s_pushid");
+    if (history_rule !== null){
+        if (history_rule.length>0){
+            html = "";
+            var num = 1;
+            for (var i=0;i<history_rule.length;i++){
+                var selected_rule = {};
+                selected_rule.department_name = history_rule[i].s_depart_name;
+                selected_rule.rule_name = history_rule[i].s_name;
+                selected_rule.update_time = formattime(history_rule[i].i_updatetime);
+                selected_rule.department_status = "已启用";
+                selected_rule.rule_status = "已启用";
+                // selected_rule.isinc = ;
+                selected_rule.create_time = formattime(history_rule[i].i_createtime);
+                selected_rule.rule_id = history_rule[i]._id;
+                rules_id.push(history_rule[i]._id);
+                selected_rules.push(selected_rule);
+            }
+            if (selected_rules.length>0){
+                $(".selected-rules").html(html);
+                for (var i=0;i<selected_rules.length;i++){
+                    html += '<tr><td>'+num+'</td><td>'+selected_rules[i].department_name+'</td><td>'+selected_rules[i].rule_name+'</td><td>'+selected_rules[i].update_time+'</td>'+'<td>'+selected_rules[i].department_status+'</td>'+'<td>'+selected_rules[i].rule_status+'</td>';
+                    // if (selected_rules[i].isinc == "true"){
+                    html += '<td><a style="margin-left:10px" class="btn btn-danger" eid="'+selected_rules[i].rule_id+'" onclick="del_selected_rule(this)">删除</a></td>'
+                    // html += '<td></td>'
+                    // html += '<td></td>'
+                    num++
+                }
+            }
+            $(".selected-rules").append(html);
+        }
+    }
+
+    $(document).ready(function () {
+        //起始时间
+        if (dataMap.starttime != 0&&typeof (dataMap.starttime)!="undefined") {
+            var dt = new Date();
+            dt.setTime(parseInt(dataMap.starttime) * 1000);
+            $('#starttime').find("input").val(dt.format("yyyy-MM-dd hh:mm:ss"));
+        }
+        //结束时间
+        if (dataMap.endtime != 0 &&typeof (dataMap.endtime)!="undefined") {
+            var dt = new Date();
+            dt.setTime(parseInt(dataMap.endtime) * 1000);
+            $('#endtime').find("input").val(dt.format("yyyy-MM-dd hh:mm:ss"));
+        }
+        if (dataMap.i_state == 0) {
+            $('.tab_2').hide()
+            $('#pushDiv').hide()
+        }else {
+            tagruleArr = {{.T.tagrule}}
+            $('#pushSwitch').bootstrapSwitch({
+                onText: "开启",
+                offText: "关闭",
+            })
+            if (dataMap.i_push && dataMap.i_push == 1) {
+                $('#pushSwitch').bootstrapSwitch('state', true);
+            }else {
+                $('#pushSwitch').bootstrapSwitch('state', false);
+            }
+            $('#pushModelSelect').val(dataMap.i_pushmodel)
+            if (dataMap.i_pushtype == 0) {
+                $('#pushTypeSelect').val(0)
+            }else {
+                $('#pushTypeSelect').val(1)
+            }
+            $("#sendMail").val(dataMap.sendMail);
+        }
+        $('#tagrule').DataTable({
+            "paging": false,
+            "lengthChange": false,
+            "searching": false,
+            "ordering": false,
+            "info": true,
+            "autoWidth": false,
+            "language": {
+                "url": "/dist/js/dataTables.chinese.lang"
+            },
+            "fnDrawCallback": function () {
+                this.api().column(0).nodes().each(function (cell, i) {
+                    cell.innerHTML = i + 1;
+                });
+            },
+            "data": tagruleArr,
+            "columns": [
+                {"data": null, width: "1%"},
+                {"data": "s_name", width: "10%"},
+                {"data": "i_updatetime", width:"9%", render: function (val) {
+                        var dt = new Date()
+                        dt.setTime(parseInt(val) * 1000);
+                        return dt.format("yyyy-MM-dd hh:mm:ss")
+                    }},
+                {"data": "i_isuse", render: function (val, a, row) {
+                        tmp = ""
+                        if(val == 1){
+                            tmp="<a href='#' title='停用' onclick='setupTag(\""+row._id+"\",false)'><i class='fa fa-fw fa-circle text-green'></i></a>已启用"
+                        }else{
+                            tmp="<a href='#' title='启用' onclick='setupTag(\""+row._id+"\",true)'><i class='fa fa-fw fa-circle text-red'></i></a>未启用"
+                        }
+                        return tmp
+                    }, width: "10%" },
+                {"data": "_id", width:"11%",render: function (val, a, row, pos) {
+                        tmp = '<div>' +
+                            // '<a class="btn btn-sm btn-primary" href="/service/euser/tag/edit?id='+val+'&cid='+row.s_userid+'">编辑</a>&nbsp&nbsp'+
+                            '<a class="btn btn-sm btn-danger" onclick="delTag(\''+val+'\')">删除</a>'+
+                            '</div>';
+                        return tmp
+                    }},
+                {"data": "_id", width:"11%",render: function (val, a, row, pos) {
+                        var s = [val, row.hid]
+                        tmp = '<div>' +
+                            '<a class="btn btn-sm btn-primary" onclick="associated(\''+s+'\')">关联数据范围</a>&nbsp&nbsp'+
+                            '</div>';
+                        return tmp
+                    }},
+            ],
+        });
+    })
+    function cancelModel() {
+        $('#modal-add-depart').modal("hide")
+        $('#modal-associated').modal("hide")
+        $('#modal-history').modal("hide")
+    }
+    //表格全选
+    function allSelect(obj) {
+        if ($(obj).is(':checked')) {
+            console.log("全选")
+            $(".history_rules tr").each(function () {
+                $(".history_rules tr").find('td').eq(0).find('input').addClass("");
+                var tag_ruleid = $(this).find('td').eq(7).text();
+                console.log("tag_ruleid",tag_ruleid)
+            })
+
+        } else {
+            console.log("反选")
+            $(".history_rules tr").each(function () {
+                $(".history_rules tr").find('td').eq(0).find('input').removeClass("checked");
+            })
+
+        }
+    }
+    function singleSelect(obj) {
+        var tag = true;
+        selectIndex.length = 0;
+        $('input[name="ckb-rule"]').each(function () {
+            if (this.checked) {
+                keyTableChecked = true;
+                selectIndex.push($(this).parents("tr").index());
+            }else {
+                tag = false
+            }
+        });
+        if (tag) {
+            keyTableAllChecked = true;
+            $('#allCheckbox').prop("checked", true);
+        }else {
+            keyTableAllChecked = false;
+            $('#allCheckbox').prop("checked", false);
+        }
+    }
+    function singleSelect1(obj) {
+        var tag = true;
+        selectIndex.length = 0;
+        $('input[name="ckb-depart"]').each(function () {
+            if (this.checked) {
+                keyTableChecked = true;
+                selectIndex.push($(this).parents("tr").index() + 1);
+            }else {
+                tag = false
+            }
+        });
+        if (tag) {
+            keyTableAllChecked = true;
+            $('#allCheckbox').prop("checked", true);
+        }else {
+            keyTableAllChecked = false;
+            $('#allCheckbox').prop("checked", false);
+        }
+    }
+
+    function saveCuser() {
+        // dataMap.send_mode = document.getElementById("pushModelSelect").selectedIndex;
+        // dataMap.push_type = document.getElementById("pushTypeSelect").selectedIndex;
+        // dataMap.s_extends = document.getElementById("expandSelect").selectedIndex;
+        dataMap.sendMail = $("#sendMail").val();
+        dataMap.s_pushid = s_pushid;
+        dataMap.c_id = c_id;
+        if ($('#starttime').find("input").val() != "") {
+            var start = $('#starttime').find("input").val();
+            start = new Date(start).getTime() / 1000;
+            console.log("start",start)
+            dataMap.starttime = start;
+        }
+        if ($('#endtime').find("input").val() != "") {
+            var end = $('#endtime').find("input").val();
+            end = new Date(end).getTime() / 1000;
+            console.log("end",end)
+            dataMap.endtime = end;
+        }
+        $.ajax({
+            url: "/service/secondpush/add",
+            type: 'POST',
+            data: dataMap,
+            success: function (r) {
+                if (r.rep) {
+                    showTip("保存成功", 500);
+                } else {
+                    showTip("保存失败", 500);
+                }
+            }
+        })
+    }
+    var tagid = ""
+    
+    function select_Depart() {
+        //获取用户自定义规则
+        $.ajax({
+           url:"/service/secondpush/getrules",
+           type:"POST",
+           data:{"c_id":c_id},
+           success:function (r) {
+                if (r.status=="success"){
+                    var html = ""
+                    var number = 1
+                    for (var i=0;i<r.data.length;i++){
+                        if (r.data[i].department_rule.length!=0){
+                            for (var l=0;l<r.data[i].department_rule.length;l++){
+                                html += '<tr><td><input type="checkbox" id="rule_id" onclick="getcheck(this)"/></td><td>'+number+'</td><td>'+r.data[i].depart_name+'</td><td>'+r.data[i].department_rule[l].s_name+'</td><td>'+formattime(r.data[i].department_rule[l].i_updatetime)+'</td>';
+                                if (r.data[i].department_isuse ==1){
+                                    html += "<td>"+"已启用"
+                                }else{
+                                    html += "</td><td>"+"未启用"
+                                }
+                                if (r.data[i].department_rule[l].i_isuse ==1){
+                                    html += "</td><td>"+"已启用"+"</td>"
+                                }else{
+                                    html += "</td><td>"+"未启用"+"</td>"
+                                }
+                                html += "<td hidden>"+r.data[i].department_rule[l]._id+"</td><td hidden class='is_inc'>false</td>";
+                                number++
+                            }
+                        }
+                    }
+                    $(".history_rules").html(html)
+                }
+           }
+        });
+        $("#modal-history").modal("show");
+    }
+    function getParam(name) {
+        var search = document.location.search;
+        // alert(search);
+        var pattern = new RegExp("[?&]" + name + "\=([^&]+)", "g");
+        var matcher = pattern.exec(search);
+        var items = null;
+        if (null != matcher) {
+            try {
+                items = decodeURIComponent(decodeURIComponent(matcher[1]));
+            } catch (e) {
+                try {
+                    items = decodeURIComponent(matcher[1]);
+                } catch (e) {
+                    items = matcher[1];
+                }
+            }
+        }
+        return items;
+    };
+    function formattime(date) {
+        let _date = new Date(parseInt(date)*1000);
+        let y = _date.getFullYear();
+        let m = _date.getMonth() + 1;
+        m = m < 10 ? ('0' + m) : m;
+        let d = _date.getDate();
+        d = d < 10 ? ('0' + d) : d;
+        // console.log( y + '-' + m + '-' + d + ' ' + ' ' + h + ':' + minute + ':' + second)
+        let dates = y + '-' + m + '-' + d;
+
+        return dates;
+    }
+    
+    function saveHistoryRule(e) {
+        var nowDate = new Date();
+        $(".history_rules tr").each(function () {
+            var chk = $(this).find('td').eq(0).find("#rule_id");
+            if (chk.hasClass('checked')){
+                var selected_rule = new Object()
+                var rule_id = $(this).find('td').eq(7).text();
+                if(rules_id.indexOf(rule_id)>-1){
+                    console.log("元素存在")
+                }else{
+                    selected_rule.department_name = $(this).find('td').eq(2).text();
+                    selected_rule.rule_name = $(this).find('td').eq(3).text();
+                    selected_rule.update_time = $(this).find('td').eq(4).text();
+                    selected_rule.department_status = $(this).find('td').eq(5).text();
+                    selected_rule.rule_status = $(this).find('td').eq(6).text();
+                    // selected_rule.isinc = $(this).find('td').eq(8).text();
+                    selected_rule.create_time = nowDate.getFullYear()+"-"+(nowDate.getMonth()+1)+"-"+nowDate.getDate()+" "+nowDate.getHours()+":"+nowDate.getMinutes()+":"+nowDate.getSeconds();
+                    selected_rule.rule_id = rule_id
+                    rules_id.push(rule_id);
+                    selected_rules.push(selected_rule)
+                }
+
+            }
+        })
+        var num = 1
+        var html = ""
+        if (selected_rules.length>0){
+            $(".selected-rules").html(html);
+            for (var i=0;i<selected_rules.length;i++){
+                html += '<tr><td>'+num+'</td><td>'+selected_rules[i].department_name+'</td><td>'+selected_rules[i].rule_name+'</td><td>'+selected_rules[i].update_time+'</td>'+'<td>'+selected_rules[i].department_status+'</td>'+'<td>'+selected_rules[i].rule_status+'</td>';
+                // if (selected_rules[i].isinc == "true"){
+                html += '<td><a style="margin-left:10px" class="btn btn-danger" eid="'+selected_rules[i].rule_id+'" onclick="del_selected_rule(this)">删除</a></td>'
+                // html += '<td><button class="btn btn-danger" onclick="del_selected_rule('+selected_rules[i].rule_id+')">删除</button></td>'
+                // }else{
+                // html += "<td></td>"
+                // }
+                num++
+            }
+        }
+        // $(".show-select").show();
+        $(".selected-rules").append(html);
+        $("#modal-history").modal("hide");
+        $.ajax({
+            url:"/service/secondpush/saverule",
+            type:"POST",
+            data:{'rulesid':rules_id.join(','),'userid':c_id,"s_pushid":s_pushid},
+            traditional:true,
+        })
+    }
+    function getcheck(e) {
+        $(e).toggleClass("checked")
+    }
+    $("#pushTypeSelect").on("change",function(){
+            selectid = $("option:selected",this).val();//需求主键
+            if (selectid == 0){
+                $(".sendmail").show()
+            }else{
+                $(".sendmail").hide()
+            }
+
+        });
+
+    //删除选中规则
+    function del_selected_rule(obj) {
+        var res = confirm("确定删除?")
+        if(res){
+            var val = $(obj).attr("eid");
+            $.ajax({
+                url:"/service/customer/secondpush/delrule",
+                type:"POST",
+                data:{'id':val,"s_pushid":s_pushid},
+                success:function (r) {
+                    if(r.success){
+                        window.location.reload();
+                    }
+                }
+            })
+        }
+    }
+
+</script>