package main

import (
	. "app.yhyue.com/moapp/jybase/common"
	"app.yhyue.com/moapp/jybase/date"
	"app.yhyue.com/moapp/jybase/encrypt"
	"app.yhyue.com/moapp/jybase/mongodb"
	ml "app.yhyue.com/moapp/jybase/mysql"
	"app.yhyue.com/moapp/jybase/redis"
	. "app.yhyue.com/moapp/jypkg/middleground"
	"bp.jydev.jianyu360.cn/BaseService/resourceCenter/rpc/pb"
	"bp.jydev.jianyu360.cn/BaseService/resourceCenter/rpc/resource"
	upb "bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/pb"
	"bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/usercenter"
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"io/ioutil"
	"log"
	"regexp"
	"strings"
	"time"
)

const (
	appid     = "10000"
	sessionId = "openPowerVirtualSessionId"
)

var (
	etcdAddress  []string
	Mgo          *mongodb.MongodbSim
	MgoLog       *mongodb.MongodbSim
	MysqlMain    *ml.Mysql
	goodsCode    string
	goodsSpecId  int64
	all          map[string]string
	powerType    string
	middleground *Middleground
	c            *Config
	whether      string
)

type Config struct {
	EtcdAddr []string
	Mongodb  struct {
		Main *mgoConf
		Log  *mgoConf
	}
	Mysql struct {
		Main *mysqlConf
		Base *mysqlConf
	}
	Products []int64
	Redis    string
	Domain   string
}

type mgoConf struct {
	Address    string
	Size       int
	DbName     string
	ReplSet    string
	UserName   string
	Password   string
	Collection string
}
type mysqlConf struct {
	DbName       string
	Address      string
	UserName     string
	PassWord     string
	MaxOpenConns int
	MaxIdleConns int
}

func init() {
	ReadConfig(&c)
}

func main() {
	MysqlMain = &ml.Mysql{
		Address:      c.Mysql.Main.Address,
		UserName:     c.Mysql.Main.UserName,
		PassWord:     c.Mysql.Main.PassWord,
		DBName:       c.Mysql.Main.DbName,
		MaxOpenConns: c.Mysql.Main.MaxOpenConns,
		MaxIdleConns: c.Mysql.Main.MaxIdleConns,
	}
	MysqlMain.Init()
	filterSpec := map[int64]bool{}
	for _, v := range c.Products {
		filterSpec[v] = true
	}
	allEntity := map[int64]Entity{}
	allEntity[-1] = &Yxy{}
	allT := "-1：医械通"
	for _, v := range *MysqlMain.SelectBySql(`select a.id,c.code,c.name,a.goods_code,a.name as spec_name from base_service.base_goods_spec a
		inner join base_service.base_goods_spec_power b on (a.id=b.spec_id)
		inner join base_service.base_function c on (b.function_code=c.code) order by a.id`) {
		id := Int64All(v["id"])
		if !filterSpec[id] {
			continue
		}
		name, _ := v["name"].(string)
		code, _ := v["code"].(string)
		if allEntity[id] == nil {
			spec_name, _ := v["spec_name"].(string)
			spec_name = strings.TrimPrefix(spec_name, "特殊非售卖商品_")
			if allT != "" {
				allT += " "
			}
			allT += fmt.Sprintf("%d：%s", id, spec_name)
			goods_code, _ := v["goods_code"].(string)
			allEntity[id] = &Common{
				Name:        spec_name,
				GoodsCode:   goods_code,
				GoodsSpecId: id,
				All:         map[string]string{name: code},
			}
		} else {
			(allEntity[id].(*Common)).All[name] = code
		}
	}
	phone := flag.String("p", "", "手机号")
	m := flag.Int("m", 0, "1：查询权益 2：开通权益 3：取消权益")
	t := flag.Int64("t", 0, allT)
	dayCount := flag.Int("c", 0, "自定义设置需要开通权益的天数，包含今天")
	entName := flag.String("n", "", "企业名称")
	isCheck := flag.Int("b", 1, "是否前置校验和后置处理")
	powerWay := flag.Int("a", 0, "权益开通/取消方式；0：一个身份 1：全部身份 2：仅仅企业上")
	isCreateUser := flag.Bool("cu", false, "是否创建用户")
	inputOrderCode := flag.String("oc", "", "订单号")
	inputStartTime := flag.Int64("st", 0, "unix类型的开始时间")
	inputEndTime := flag.Int64("et", 0, "unix类型的结束时间")
	resetPower := flag.Bool("rp", false, "是否重新开通权益")
	flag.Parse()
	//*phone = "15037870753"
	//*t = 22
	//*entName = "王传进的测试企业99"
	//*isCreateUser = true
	//*inputOrderCode = "259519348822"
	//*inputStartTime = 1746028800
	//*inputEndTime = 1747584000
	//*m = 2
	//
	if *phone == "" {
		log.Fatalln("-p 参数无效")
	}
	if *inputOrderCode != "" {
		*isCreateUser = true
		if *inputStartTime == 0 {
			log.Fatalln("-st 参数无效")
		}
		if *inputEndTime == 0 {
			log.Fatalln("-et 参数无效")
		}
	}
	if *m != 2 {
		*isCreateUser = false
	}
	var inputStartTimeStr, inputEndTimeStr string
	if *inputStartTime > 0 {
		inputStartTimeStr = gtime.NewFromTimeStamp(*inputStartTime).String()
		if inputStartTimeStr == "" {
			log.Fatalln("-st 参数无效")
		}
	}
	if *inputEndTime > 0 {
		inputEndTimeStr = gtime.NewFromTimeStamp(*inputEndTime).String()
		if inputEndTimeStr == "" {
			log.Fatalln("-et 参数无效")
		}
	}
	entity := allEntity[*t]
	if entity == nil {
		log.Fatalln("-t 参数无效")
	}
	powerType, goodsCode, goodsSpecId, all = entity.init()
	middleground = NewMiddleground(c.EtcdAddr)
	middleground.RegResourceCenter("resource.rpc").RegUserCenter("usercenter.rpc")
	//
	redis.InitRedis(c.Redis)
	Mgo = &mongodb.MongodbSim{
		MongodbAddr: c.Mongodb.Main.Address,
		Size:        c.Mongodb.Main.Size,
		DbName:      c.Mongodb.Main.DbName,
		ReplSet:     c.Mongodb.Main.ReplSet,
		UserName:    c.Mongodb.Main.UserName,
		Password:    c.Mongodb.Main.Password,
	}
	Mgo.InitPool()
	MgoLog = &mongodb.MongodbSim{
		MongodbAddr: c.Mongodb.Log.Address,
		Size:        c.Mongodb.Log.Size,
		DbName:      c.Mongodb.Log.DbName,
		ReplSet:     c.Mongodb.Log.ReplSet,
		UserName:    c.Mongodb.Log.UserName,
		Password:    c.Mongodb.Log.Password,
	}
	MgoLog.InitPool()
	//
	createUserOk, ur, newUserId, newBaseUserId := createUser(*phone, *isCreateUser)
	if !createUserOk {
		return
	}
	//是否创建企业
	if *isCreateUser && *entName != "" {
		isInEnt := MysqlMain.CountBySql(`select count(1) as count from jianyu.entniche_info a inner join jianyu.entniche_user b on (a.name=? and b.phone=? and a.id=b.ent_id)`, *entName, *phone)
		if isInEnt == 0 {
			log.Println("该手机号是否是企业管理员(y/n)？")
			fmt.Scan(&whether)
			if whether == "y" {
				if createEntOk, _, _, _ := createEnt(newUserId, *phone, *entName, newBaseUserId); !createEntOk {
					return
				}
			} else {
				var entAdminPhone string
				log.Println("请输入管理员手机号")
				for {
					fmt.Scan(&entAdminPhone)
					entAdminPhone = strings.TrimSpace(entAdminPhone)
					if !regexp.MustCompile("^[0-9]+$").MatchString(entAdminPhone) {
						log.Println("手机号格式错误，请重新输入！")
					} else {
						break
					}
				}
				createUserOk, _, adminUserId, adminBaseUserId := createUser(entAdminPhone, *isCreateUser)
				if !createUserOk {
					return
				}
				createEntOk, newEntId, newDeptId, nweEntUserId := createEnt(adminUserId, entAdminPhone, *entName, adminBaseUserId)
				if !createEntOk {
					return
				}
				log.Println("该手机号未在企业下，是否添加为员工(y/n)？")
				fmt.Scan(&whether)
				if whether != "y" {
					return
				}
				addToEnt(newEntId, newDeptId, nweEntUserId, newUserId, *phone)
			}
		} else if isInEnt < 0 {
			log.Fatalln("查询手机号是否在企业下失败！")
		}
	}
	//
	isFindIdentity := false
	var updateOrderUserId string
	for _, v := range *ur {
		id := Int64All(v["base_user_id"])
		for _, identity := range middleground.UserCenter.IdentityList(id) {
			if *powerWay == 0 {
				if *entName == "" && identity.PositionType == 1 {
					continue
				} else if *entName != "" && (identity.PositionType == 0 || *entName != identity.Name) {
					continue
				}
			} else if *powerWay == 2 {
				if *entName == "" {
					continue
				} else if identity.PositionType == 0 || *entName != identity.Name {
					continue
				}
			}
			isFindIdentity = true
			msg := "身份信息：" + fmt.Sprintf("%+v", identity) + " 手机号：" + *phone
			var resClient = resource.NewResource(middleground.ResourceCenter.NewClient())
			var getPowers = func() *garray.StrArray {
				r, err := resClient.Haspowers(context.Background(), &pb.HaspowersReq{
					Appid:        "10000",
					EntId:        identity.EntId,
					EntUserId:    identity.EntUserId,
					AccountId:    identity.AccountId,
					EntAccountId: identity.EntAccountId,
				})
				if err != nil {
					log.Fatalln(msg, "查询", powerType, "权益失败！", err)
				}
				return garray.NewStrArrayFrom(r.Powers)
			}
			var notHavePowers = func() []string {
				array := []string{}
				powers := getPowers()
				for k, v := range all {
					if powers.Contains(v) {
						continue
					}
					array = append(array, k)
				}
				return array
			}
			if *m == 1 {
				if array := notHavePowers(); len(array) > 0 {
					log.Println(msg, powerType, "权益异常，缺少权益：", strings.Join(array, ","))
				} else {
					for k, _ := range all {
						log.Println(msg, "拥有", powerType, "权益：", k)
					}
				}
			} else if *m == 2 {
				if identity.PositionType == 1 {
					updateOrderUserId = gconv.String(identity.PositionId)
				} else {
					updateOrderUserId = newUserId
				}
				if *isCheck == 1 && !entity.beforeOpen(phone, identity) {
					return
				}
				startTime, endTime := "", ""
				if inputStartTimeStr != "" {
					startTime = inputStartTimeStr
				}
				if inputEndTimeStr != "" {
					endTime = inputEndTimeStr
				} else if *dayCount > 0 {
					now := time.Now()
					end_time := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, time.Local)
					end_time = end_time.AddDate(0, 0, *dayCount-1)
					endTime = date.FormatDate(&end_time, date.Date_Full_Layout)
				}
				isEmpower := false
				if identity.EntId > 0 {
					resp, err := resClient.WaitEmpowerDetailBySpecId(context.Background(), &pb.WaitEmpowerDetailBySpecIdReq{
						Appid:  "10000",
						EntId:  identity.EntId,
						SpecId: goodsSpecId,
					})
					if err != nil {
						log.Println(msg, powerType, "开通失败！", err)
					} else if len(resp.WaitEmpowerDetails) > 0 {
						if *powerWay < 2 {
							isEmpower = true
						} else if *powerWay == 2 {
							log.Fatalln(msg, powerType, "权益已存在！")
						}
					}
					// for _, v := range all {
					// 	resp, err := resClient.WaitEmpowerDetail(context.Background(), &pb.WaitEmpowerDetailReq{
					// 		Appid:        "10000",
					// 		EntId:        identity.EntId,
					// 		FunctionCode: v,
					// 	})
					// 	log.Println(v, resp.Id)
					// 	if err != nil {
					// 		log.Println(msg, powerType, "开通失败！", err)
					// 	} else if resp.Id > 0 {
					// 		if *powerWay < 2 {
					// 			isEmpower = true
					// 		} else if *powerWay == 2 {
					// 			log.Fatalln(msg, powerType, "权益已存在！")
					// 		}
					// 	}
					// 	break
					// }
				}
				if len(notHavePowers()) == 0 && !*resetPower {
					log.Println(msg, powerType, "权益已存在，无需开通")
					continue
				}
				var r *pb.Resp
				var err error
				if isEmpower {
					for _, v := range all {
						r, err = resClient.Empower(context.Background(), &pb.EmpowerReq{
							Appid:        "10000",
							FunctionCode: v,
							EntId:        identity.EntId,
							EntUserId:    []int64{identity.EntUserId},
						})
					}
				} else {
					powerReq := &pb.PowerReq{
						Appid:       appid,
						GoodsCode:   goodsCode,
						GoodsSpecId: goodsSpecId,
						BuyNum:      1,
						Type:        1,
						EndTime:     endTime,
						StartTime:   startTime,
					}
					if *powerWay == 2 {
						powerReq.EntAccountId = identity.EntAccountId
						powerReq.EntId = identity.EntId
					} else {
						powerReq.AccountId = identity.AccountId
					}
					r, err = resClient.PowerHandle(context.Background(), powerReq)
				}
				if err != nil {
					log.Println(msg, powerType, "开通失败！", err)
				} else if r.Status == 1 {
					if *isCheck == 1 {
						entity.afterOpen(phone, identity)
					}
					log.Println(msg, powerType, "已开通！")
				} else {
					log.Println(msg, powerType, "开通失败！")
				}
			} else if *m == 3 {
				powerReq := &pb.PowerReq{
					Appid:       appid,
					GoodsCode:   goodsCode,
					GoodsSpecId: goodsSpecId,
					BuyNum:      1,
					Type:        -1,
				}
				if *powerWay == 2 {
					powerReq.EntAccountId = identity.EntAccountId
					powerReq.EntId = identity.EntId
				} else {
					powerReq.AccountId = identity.AccountId
					powerReq.EntAccountId = identity.EntAccountId
					powerReq.EntId = identity.EntId
				}
				r, err := resClient.PowerHandle(context.Background(), powerReq)
				if err != nil {
					log.Println(msg, powerType, "取消失败！", err)
				} else if r.Status == 1 {
					log.Println(msg, powerType, "已取消！")
				} else {
					log.Println(msg, powerType, "取消失败！", r.Status)
				}
			} else {
				log.Fatalln("-m 参数无效")
			}
			if *m == 2 || *m == 3 {
				_, err := usercenter.NewUserCenter(middleground.UserCenter.NewClient()).WorkDesktopClearUserInfo(context.Background(), &upb.WorkDesktopClearUserInfoReq{
					PositionId: fmt.Sprint(identity.PositionId),
					AppId:      appid,
				})
				if err != nil {
					log.Println("清除用户工作桌面缓存失败", err)
				}
			}
		}
	}
	if !isFindIdentity {
		log.Fatalln("没有找到身份信息！")
	}
	if *inputOrderCode != "" && updateOrderUserId != "" {
		orderData := MysqlMain.SelectBySql(`select user_id,vip_starttime,vip_endtime from jianyu.dataexport_order where order_code=?`, inputOrderCode)
		if orderData == nil || len(*orderData) == 0 {
			log.Fatalln("没有找到该订单，更新订单失败！")
		} else if len(*orderData) > 1 {
			log.Fatalln("找到多个订单，需要手动处理！")
		}
		updateArgs := []interface{}{}
		odVar := gvar.New((*orderData)[0]).MapStrVar()
		updateFields := []string{}
		array := []string{}
		if odVar["user_id"].IsEmpty() {
			updateFields = append(updateFields, "用户id")
			array = append(array, "user_id=?")
			updateArgs = append(updateArgs, updateOrderUserId)
		} else {
			log.Println("订单表用户id存在，无需更新")
		}
		if odVar["vip_starttime"].IsEmpty() {
			updateFields = append(updateFields, "服务开始时间")
			array = append(array, "vip_starttime=?")
			updateArgs = append(updateArgs, inputStartTimeStr)
		} else {
			log.Println("订单表服务开始时间存在，无需更新")
		}
		if odVar["vip_endtime"].IsEmpty() {
			updateFields = append(updateFields, "服务截止时间")
			array = append(array, "vip_endtime=?")
			updateArgs = append(updateArgs, inputEndTimeStr)
		} else {
			log.Println("订单表服务截止时间存在，无需更新")
		}
		if len(array) > 0 {
			updateArgs = append(updateArgs, *inputOrderCode)
			if MysqlMain.UpdateOrDeleteBySql(`update jianyu.dataexport_order set `+strings.Join(array, ",")+` where order_code=?`, updateArgs...) < 0 {
				log.Fatalln("更新订单表" + strings.Join(updateFields, "、") + "失败！")
			} else {
				log.Fatalln("更新订单表" + strings.Join(updateFields, "、") + "成功！")
			}
		}
	}
}

type Entity interface {
	init() (string, string, int64, map[string]string)
	beforeOpen(phone *string, identity *upb.Identity) bool
	afterOpen(phone *string, identity *upb.Identity)
}

type Common struct {
	Name        string
	GoodsCode   string
	GoodsSpecId int64
	All         map[string]string
}

func (c *Common) init() (string, string, int64, map[string]string) {
	return c.Name, c.GoodsCode, c.GoodsSpecId, c.All
}

func (c *Common) beforeOpen(phone *string, identity *upb.Identity) bool {
	return true
}

func (c *Common) afterOpen(phone *string, identity *upb.Identity) {
}

/******************************医械云******************************************/
type Yxy struct {
}

func (y *Yxy) init() (string, string, int64, map[string]string) {
	return "医械云权益", "lyh", 13, map[string]string{
		"医疗标讯搜索": "lyh_yl_ylbxss",
		"医疗机构搜索": "lyh_yl_yljgss",
		"经销商搜索":  "lyh_yl_jxsss",
		"医疗机构画像": "lyh_yl_yljghx",
		"医疗机构认领": "lyh_yl_yljgrl",
		"经销商认领":  "lyh_yl_jxsrl",
		"医疗订阅":   "lyh_yl_yldy",
	}
}

func (y *Yxy) beforeOpen(phone *string, identity *upb.Identity) bool {
	order_user_id, u := y.getUser(identity)
	if u == nil {
		return false
	}
	ok, _, _, _ := y.isOK(*phone, *u, order_user_id)
	return ok
}

func (y *Yxy) getUser(identity *upb.Identity) (string, *map[string]interface{}) {
	if identity.PositionType == 0 {
		u, _ := Mgo.FindOneByField("user", map[string]interface{}{"base_user_id": identity.UserId}, `{"_id":1,"l_vip_endtime":1,"i_member_endtime":1,"s_member_mainid":1,"i_member_sub_status":1}`)
		if u == nil || len(*u) == 0 {
			log.Println(fmt.Sprintf("%+v", identity), "mongodb user 中没有找到该用户！")
			return "", nil
		}
		return mongodb.BsonIdToSId((*u)["_id"]), u
	} else {
		u, _ := Mgo.FindOneByField("ent_user", map[string]interface{}{"i_userid": identity.EntUserId}, `{"_id":1,"l_vip_endtime":1,"i_member_endtime":1,"s_member_mainid":1,"i_member_sub_status":1}`)
		if u == nil || len(*u) == 0 {
			log.Println(fmt.Sprintf("%+v", identity), "mongodb ent_user 中没有找到该用户！")
			return "", nil
		}
		return fmt.Sprint(identity.PositionId), u
	}
}

func (y *Yxy) afterOpen(phone *string, identity *upb.Identity) {
	order_user_id, u := y.getUser(identity)
	if u == nil {
		return
	}
	ok, orderVip, vipRs, bigRs := y.isOK(*phone, *u, order_user_id)
	if ok {
		y.createYxtOrder(*phone, *u, orderVip, vipRs, bigRs)
	}
}
func (y *Yxy) isOK(phone string, user map[string]interface{}, order_user_id string) (bool, bool, *[]map[string]interface{}, *[]map[string]interface{}) {
	orderVip := true // 是否根据超级订阅订单处理 如果是大会员也是超级订阅则按大会员处理
	flag1 := false
	flag2 := false
	mainUserId := order_user_id
	if IntAllDef(user["i_member_sub_status"], -1) == 1 {
		mainUser, ok := Mgo.FindById("user", ObjToString(user["s_member_mainid"]), `{"s_phone"1:,"s_m_phone":1}`)
		if ok && mainUser != nil {
			mainUserId = mongodb.BsonIdToSId((*mainUser)["_id"])
		} else {
			log.Println("该用户是子账号，没有找到其主账号的信息")
			return false, false, nil, nil
		}
	}
	bigMemberRs := MysqlMain.SelectBySql(`select * from dataexport_order where user_id=? and order_status=1 and product_type ="大会员" and (timestampdiff(day,vip_starttime,vip_endtime)>=365) order by create_time desc limit 1`, mainUserId)
	if bigMemberRs != nil && len(*bigMemberRs) == 1 {
		(*bigMemberRs)[0]["user_phone"] = phone
		(*bigMemberRs)[0]["user_id"] = order_user_id
	}
	vipRs := MysqlMain.SelectBySql(`select * from dataexport_order where user_id=? and order_status=1 and product_type ="VIP订阅" and (timestampdiff(day,vip_starttime,vip_endtime)>=365) order by create_time desc limit 1`, order_user_id)
	if (bigMemberRs == nil || len(*bigMemberRs) == 0) && (vipRs == nil || len(*vipRs) == 0) {
		log.Println("没有查询到该用户的年度超级订阅或者大会员订单")
		return false, false, nil, nil
	}
	// 同时存在超级订阅和大会员年度订单  不再判断最晚到期时间 大会员优先
	if vipRs != nil && len(*vipRs) == 1 {
		vipEndTime := Int64All(user["l_vip_endtime"])
		leftdayvip := time.Unix(vipEndTime, 0).Sub(time.Now()).Hours() / 24
		if leftdayvip >= 90 {
			orderVip = true
			flag1 = true
		}
	}
	if *bigMemberRs != nil && len(*bigMemberRs) == 1 {
		// 判断最晚到期时间
		bigMemberEndTime := IntAll(user["i_member_endtime"])
		leftdaybig := time.Unix(int64(bigMemberEndTime), 0).Sub(time.Now()).Hours() / 24
		if leftdaybig >= 90 {
			orderVip = false
			flag2 = true
		}
	}
	if !flag1 && !flag2 {
		log.Println("该用户剩余不符合条件")
		return false, false, nil, nil
	}
	return true, orderVip, vipRs, bigMemberRs

}

// 生成医械通订单
func (y *Yxy) createYxtOrder(phone string, user map[string]interface{}, orderVip bool, vipRs, bigMemberRs *[]map[string]interface{}) {
	var insertOrder map[string]interface{}
	filterMap := map[string]interface{}{}
	// 超级订阅
	if orderVip {
		insertOrder = (*vipRs)[0]
		// 生订单信息
		orderMoney := Float64All(insertOrder["order_money"])
		endTime := Int64All(user["l_vip_endtime"])
		var money int
		filterData := (*vipRs)[0]["filter"]
		err := json.Unmarshal([]byte(filterData.(string)), &filterMap)
		if err != nil {
			log.Println("反序列化失败", err)
			return
		}
		if IntAll(insertOrder["is_backstage_order"]) == 1 {
			cycle := Float64All(filterMap["cyclecount"])
			cycleUnit := Float64All(filterMap["cycleunit"])
			money = y.getPriceBack(orderMoney, time.Unix(endTime, 0), cycle, cycleUnit)
		} else {
			money = y.getPrice(orderMoney, time.Unix(endTime, 0))
		}
		insertOrder["order_money"] = money
		insertOrder["original_price"] = money
		insertOrder["vip_endtime"] = time.Unix(endTime, 0).Format(date.Date_Full_Layout)
	} else {
		// 大会员
		endTime := Int64All(user["i_member_endtime"])
		filterData := (*bigMemberRs)[0]["filter"]
		err := json.Unmarshal([]byte(filterData.(string)), &filterMap)
		if err != nil {
			log.Println("反序列化失败", err)
			return
		}
		filterMap["area"] = "-"
		insertOrder = (*bigMemberRs)[0]
		insertOrder["order_money"] = 0
		insertOrder["original_price"] = 0
		insertOrder["vip_endtime"] = time.Unix(endTime, 0).Format(date.Date_Full_Layout)
	}
	filterMap["source"] = "qmx" // 后台订单
	// 生订单信息
	filter, _ := json.Marshal(filterMap)
	insertOrder["filter"] = string(filter)
	insertOrder["is_backstage_order"] = 1 // 后台创建
	insertOrder["product_type"] = "医械通"
	insertOrder["order_code"] = fmt.Sprintf("%s%s", time.Now().Format("150405"), GetRandom(6))
	insertOrder["prepay_id"] = ""
	insertOrder["pay_money"] = 0
	insertOrder["discount_price"] = 0
	insertOrder["pay_way"] = ""
	insertOrder["out_trade_no"] = ""
	insertOrder["create_time"] = date.NowFormat(date.Date_Full_Layout)
	insertOrder["vip_starttime"] = date.NowFormat(date.Date_Full_Layout)
	insertOrder["pay_time"] = insertOrder["vip_starttime"]
	insertOrder["prepay_time"] = insertOrder["vip_starttime"]
	delete(insertOrder, "id")
	saveRs := MysqlMain.Insert("dataexport_order", insertOrder)
	if saveRs > 0 {
		log.Println("医械通订单保存成功")
	} else {
		log.Println("医械通订单保存失败", saveRs)
	}
}

// 计算价格 线上的
func (y *Yxy) getPrice(orderMoney float64, endTime time.Time) int {
	// 计算价格
	dis := endTime.Sub(time.Now())
	days := dis.Hours() / 24 // 剩余天数
	money := int(orderMoney / 360 * float64(int(days)))
	return money
}

// 计算价格 管理后台创建的
func (y *Yxy) getPriceBack(orderMoney float64, endTime time.Time, cycle, cycleUnit float64) int {
	//(1:年 2:月 3:天 4:季)
	// 计算价格
	unitPrice := 0.0
	switch cycleUnit {
	case 1:
		unitPrice = orderMoney / cycle / 360
	case 2:
		unitPrice = orderMoney / cycle / 30
	case 3:
		unitPrice = orderMoney / cycle
	case 4:
		unitPrice = orderMoney / cycle / 90
	}
	dis := endTime.Sub(time.Now())
	days := dis.Hours() / 24 // 剩余天数
	//log.Println("=========", int(days), "=================")
	money := unitPrice * float64(int(days))
	return int(money)
}
func createUser(phone string, isCreateUser bool) (bool, *[]map[string]interface{}, string, int64) {
	ur, userOk := Mgo.Find("user", map[string]interface{}{
		"$or": []map[string]interface{}{
			map[string]interface{}{
				"s_phone": phone,
			},
			map[string]interface{}{
				"s_m_phone": phone,
			},
		},
		"i_appid": 2,
	}, nil, `{"_id":1,"base_user_id":1}`, false, -1, -1)
	var newBaseUserId int64
	var newUserId string
	if !userOk {
		log.Fatalln("mgo user 查询失败")
	} else if ur == nil || len(*ur) <= 0 {
		if isCreateUser {
			log.Println("没有找到该用户！是否创建(y/n)？")
			fmt.Scan(&whether)
			if whether != "y" {
				return false, nil, "", 0
			}
		} else {
			log.Fatalln("没有找到该用户！")
		}
		resp := middleground.UserCenter.UserAdd(upb.UserAddReq{Appid: appid, Phone: phone})
		if resp == nil || resp.Data.Status != 1 {
			log.Fatalln("创建用户失败")
		}
		newBaseUserId = resp.Data.Id
		newUserId = Mgo.Save("user", map[string]interface{}{
			"i_appid":       2,
			"s_phone":       phone,
			"base_user_id":  resp.Data.Id,
			"l_registedate": time.Now().Unix(),
			"s_regsource":   "openpower",
		})
		MgoLog.Save("user", map[string]interface{}{
			"userid":      newUserId,
			"phone":       phone,
			"way":         "phone",
			"system":      "pc",
			"source":      "openpower",
			"create_time": date.NowFormat(date.Date_Full_Layout),
		})
		*ur = append(*ur, map[string]interface{}{
			"_id":          mongodb.StringTOBsonId(newUserId),
			"base_user_id": newBaseUserId,
		})
	} else {
		newUserId = mongodb.BsonIdToSId((*ur)[0]["_id"])
		newBaseUserId = gconv.Int64((*ur)[0]["base_user_id"])
	}
	return true, ur, newUserId, newBaseUserId
}
func createEnt(mgoUserId, phone, entName string, baseUserId int64) (bool, int64, int64, int64) {
	entDept := MysqlMain.SelectBySql(`select a.id as eid,b.id as did,c.id as uid from jianyu.entniche_info a inner join entniche_department b on (a.id=b.ent_id and b.pid=0) inner join entniche_user c on (a.id=c.ent_id and c.phone=?) where a.phone=? and a.name=?`, phone, phone, entName)
	if entDept == nil {
		log.Fatalln("查询企业是否存在失败！")
	} else if len(*entDept) > 0 {
		return true, gconv.Int64((*entDept)[0]["eid"]), gconv.Int64((*entDept)[0]["did"]), gconv.Int64((*entDept)[0]["uid"])
	}
	log.Println("没有找到该企业！是否创建(y/n)？")
	fmt.Scan(&whether)
	if whether != "y" {
		return false, 0, 0, 0
	}
	//创建企业
	redis.Put("session", sessionId, map[string]interface{}{
		"userId":       mgoUserId,
		"mgoUserId":    mgoUserId,
		"base_user_id": baseUserId,
	}, 60)
	resp, err := g.Client().SetCookie("SESSIONID", sessionId).Post(gctx.New(), c.Domain+"/entbase/ent/add", g.Map{
		"switch": true,
		"name":   entName,
	})
	if err != nil {
		log.Fatalln(err)
	}
	defer resp.Body.Close()
	b, _ := ioutil.ReadAll(resp.Body)
	eId := gvar.New(b).MapStrVar()["data"].MapStrVar()["entid"].String()
	if eId == "" {
		log.Fatalln("创建企业失败", string(b))
	}
	entId := gconv.Int64(encrypt.SE.Decode4HexByCheck(eId))
	if entId <= 0 {
		log.Fatalln("创建企业失败", string(b))
	}
	resp1, err1 := g.Client().SetCookie("SESSIONID", sessionId).Post(gctx.New(), c.Domain+"/entbase/ent/entinfo")
	if err1 != nil {
		log.Fatalln(err)
	}
	defer resp1.Body.Close()
	b1, _ := ioutil.ReadAll(resp1.Body)
	deptId := gvar.New(b1).MapStrVar()["data"].MapStrVar()["dept_id"].Int64()
	entUserId := gconv.Int64(encrypt.SE.Decode4HexByCheck(gvar.New(b1).MapStrVar()["data"].MapStrVar()["user_id"].String()))
	if deptId <= 0 {
		log.Fatalln("创建企业后，获取部门id失败", string(b1))
	}
	return true, entId, deptId, entUserId
}

func addToEnt(entId, deptId, entUserId int64, userId, phone string) {
	redis.Put("session", sessionId, map[string]interface{}{
		"entId":          entId,
		"entUserId":      entUserId,
		"frameworkEntId": entId,
		"userId":         userId,
	}, 60)
	resp, err := g.Client().SetCookie("SESSIONID", sessionId).Post(gctx.New(), c.Domain+"/entbase/person/add", g.Map{
		"id":    deptId,
		"name":  phone,
		"phone": phone,
	})
	if err != nil {
		log.Fatalln(err)
	}
	defer resp.Body.Close()
	b, _ := ioutil.ReadAll(resp.Body)
	if gvar.New(b).MapStrVar()["data"].MapStrVar()["status"].Int() != 1 {
		log.Fatalln("人员添加到企业下失败", string(b))
	}
}
