package models

import (
	"LAPP_LF_MOM_BACKEND/conf"
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/middleware/glog"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"strings"
	"time"
)

type Buffer struct {
	Orderid      string `bson:"orderid" json:"buffer-orderid"`           //流水号id
	Finr         int    `bson:"finr" json:"buffer-finr"`                 //映射关系
	Eid          int    `bson:"eid" json:"buffer-eid"`                   //映射关系
	Data         string `bson:"data" json:"buffer-data"`                 //json串
	TimeStamp    string `bson:"timestamp" json:"buffer-timestamp"`       //时间戳
	Todb         string `bson:"todb" json:"buffer-todb"`                 //导入数据库
	Todrivername string `bson:"todrivername" json:"buffer-todrivername"` //导入数据库引擎
	Totable      string `bson:"totable" json:"buffer-totable"`           //导入数据表
	Flag         int    `bson:"flag" json:"buffer-flag"`                 //是否导入状态
	Times        int    `bson:"times" json:"buffer-times"`               //执行次数
	Status       string `bson:"status" json:"buffer-status"`             //ok  or  error
	Message      string `bson:"message" json:"buffer-message"`           //错误信息
	Funcspec     string `bson:"funcspec" json:"buffer-funcspec"`         //导入执行方法
	Dbtype       string `bson:"dbtype" json:"buffer-dbtype"`             //导入数据库类型
}

func (t *Buffer) TableName() string {
	return "buffer"
}

func (t *Buffer) InsertRecord() (insertID primitive.ObjectID) {
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("buffer")
	insertRest, err := collect.InsertOne(context.TODO(), t)
	if err != nil {
		glog.InfoExtln("buffer 数据导入", "err", err)
		return
	}
	insertID = insertRest.InsertedID.(primitive.ObjectID)
	return insertID
}

func (t *Buffer) FindList(logred SerchData, skip int64, limit int64) ([]*Buffer, int64) {
	res := bson.M{}
	// 创建需要过滤的条件
	if logred.Key == "message" {
		res = bson.M{"message": primitive.Regex{Pattern: logred.Val}}
	}
	if logred.Key == "totable" {
		res = bson.M{"totable": primitive.Regex{Pattern: logred.Val}}
	}
	if logred.Key == "status" {
		res = bson.M{"status": primitive.Regex{Pattern: logred.Val}}
	}
	if logred.Key == "timestamp" {
		times := strings.Split(logred.Val, "-")
		stime := time.Unix(int64(utils.ValueToInt(times[0], 0)), 0)
		etime := time.Unix(int64(utils.ValueToInt(times[1], 0)), 0)
		stimestr := utils.TimeFormat(stime, "yyyyMMddHHmmss")
		etimestr := utils.TimeFormat(etime, "yyyyMMddHHmmss")
		res = bson.M{"timestamp": bson.M{"$lte": etimestr, "$gte": stimestr}}
	}
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("buffer")

	//var skip int64 = 0//从那个开始
	//var limit int64 = 2//炼制几个输出字段
	cursor, err := collect.Find(context.TODO(), res, &options.FindOptions{
		Skip:  &skip,
		Limit: &limit,
		Sort:  bson.D{{"timestamp", -1}},
	})

	if err != nil {
		return nil, 0
	}
	defer cursor.Close(context.TODO())
	//创建需要反序列化成什么样子的结构体对象
	records := make([]*Buffer, 0)
	for cursor.Next(context.TODO()) {
		record := &Buffer{}
		//反序列化
		err = cursor.Decode(record)
		if err != nil {
			return nil, 0
		}
		//追加
		records = append(records, record)
	}
	// 获取数据总数
	count, err := collect.CountDocuments(context.Background(), bson.D{})
	if err != nil {
		return nil, 0
	}
	return records, count
}

func (t *Buffer) FindData() []*Buffer {
	limit := int64(500)
	skip := int64(0)
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("buffer")

	//var skip int64 = 0//从那个开始
	//var limit int64 = 2//炼制几个输出字段
	cursor, err := collect.Find(context.TODO(), bson.D{
		{"flag", 0},
		{"status", "ok"},
	}, &options.FindOptions{
		Skip:  &skip,
		Limit: &limit,
		Sort:  bson.D{{"timestamp", -1}},
	})
	if err != nil {
		return nil
	}
	defer cursor.Close(context.TODO())
	//创建需要反序列化成什么样子的结构体对象
	records := make([]*Buffer, 0)
	for cursor.Next(context.TODO()) {
		record := &Buffer{}
		//反序列化
		err = cursor.Decode(record)
		if err != nil {
			return nil
		}
		//追加
		records = append(records, record)
	}
	return records
}

func (t *Buffer) UpdateData() error {
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("buffer")

	new := &Buffer{
		Orderid:      t.Orderid,
		Eid:          t.Eid,
		Finr:         t.Finr,
		Data:         t.Data,
		TimeStamp:    t.TimeStamp,
		Todrivername: t.Todrivername,
		Totable:      t.Totable,
		Todb:         t.Todb,
		Status:       t.Status,
		Message:      t.Message,
		Funcspec:     t.Funcspec,
		Dbtype:       t.Dbtype,
		Times:        t.Times + 1,
		Flag:         1,
	}
	update := bson.M{"$set": new}
	_, err := collect.UpdateOne(context.Background(), bson.M{"orderid": new.Orderid}, update)
	if err != nil {
		return err
	}
	return nil
}

//累计更新次数，超过5次的直接关闭订单
func (t *Buffer) UpdateDataTimes() error {
	//1.初始化链接
	client := db.MgoDb()
	//2.选择数据库，数据表
	collect := client.Database(conf.DbConfig.Mongdbname).Collection("buffer")
	if t.Times > 5 {
		// 修改一条数据，如果不存在则插入
		new := &Buffer{
			Orderid:      t.Orderid,
			Eid:          t.Eid,
			Finr:         t.Finr,
			Data:         t.Data,
			TimeStamp:    t.TimeStamp,
			Todrivername: t.Todrivername,
			Totable:      t.Totable,
			Todb:         t.Todb,
			Status:       t.Status,
			Message:      t.Message,
			Funcspec:     t.Funcspec,
			Dbtype:       t.Dbtype,
			Times:        t.Times + 1,
			Flag:         1,
		}
		update := bson.M{"$set": new}
		_, err := collect.UpdateOne(context.Background(), bson.M{"orderid": new.Orderid}, update)
		if err != nil {
			return err
		}
		return nil
	} else {
		new := &Buffer{
			Orderid:      t.Orderid,
			Eid:          t.Eid,
			Finr:         t.Finr,
			Data:         t.Data,
			TimeStamp:    t.TimeStamp,
			Todrivername: t.Todrivername,
			Totable:      t.Totable,
			Todb:         t.Todb,
			Status:       t.Status,
			Message:      t.Message,
			Funcspec:     t.Funcspec,
			Dbtype:       t.Dbtype,
			Times:        t.Times + 1,
			Flag:         0,
		}
		update := bson.M{"$set": new}
		_, err := collect.UpdateOne(context.Background(), bson.M{"orderid": new.Orderid}, update)
		if err != nil {
			return err
		}
		return nil
	}


}
