package models

import (
	"LAPP_LF_MOM_BACKEND/db"
	"LAPP_LF_MOM_BACKEND/utils"
	"LAPP_LF_MOM_BACKEND/web/middleware/glog"
	"context"
	"errors"
	"fmt"
	"log"
	"strconv"
	"strings"
	"time"
	"xorm.io/core"
)

type PmWo struct {
	Finr          int           `json:"finr" xorm:"not null pk INT(4)"`
	Maintwoid     string        `json:"maintwoid" xorm:"not null pk VARCHAR(18)"`
	Mainservicenr string        `json:"mainservicenr" xorm:"not null VARCHAR(18)"`
	Descr         string        `json:"descr" xorm:"not null VARCHAR(40)"`
	Status        int           `json:"status" xorm:"not null INT(4)"`
	Priority      int           `json:"priority" xorm:"not null SMALLINT(2)"`
	Assetid       int           `json:"assetid" xorm:"not null INT(4)"`
	Plbegdat      string        `json:"plbegdat" xorm:"not null VARCHAR(8)"`
	Plenddat      string        `json:"plenddat" xorm:"not null VARCHAR(8)"`
	Needschedule  int           `json:"needschedule" xorm:"not null INT(4)"`
	Maintimelen   float64       `json:"maintimelen" xorm:"not null DECIMAL(16,6)"`
	Timeunit      string        `json:"timeunit" xorm:"not null VARCHAR(5)"`
	Schedbegtime  string        `json:"schedbegtime" xorm:"not null VARCHAR(14)"`
	Schedendtime  string        `json:"schedendtime" xorm:"not null VARCHAR(14)"`
	Actbegtime    string        `json:"actbegtime" xorm:"not null VARCHAR(14)"`
	Actendtime    string        `json:"actendtime" xorm:"not null VARCHAR(14)"`
	Assignedto    string        `json:"assignedto" xorm:"not null VARCHAR(1)"`
	Operator      int           `json:"operator" xorm:"not null INT(4)"`
	Vendor        int           `json:"vendor" xorm:"not null INT(4)"`
	Mainttype     string        `json:"mainttype" xorm:"not null VARCHAR(14)"`
	Costcenterid  string        `json:"costcenterid" xorm:"not null VARCHAR(12)"`
	Poid          string        `json:"poid" xorm:"not null VARCHAR(18)"`
	Lastmodif     string        `json:"lastmodif" xorm:"not null VARCHAR(14)"`
	Lastuser      string        `json:"lastuser" xorm:"not null VARCHAR(20)"`
	Credatuz      string        `json:"credatuz" xorm:"not null VARCHAR(14)"`
	UrgencyDegree int           `json:"urgencyDegree" xorm:"-"`
	Valst         []PmWoAttrlst `json:"valst" xorm:"-"`
}

const (
	UngencyStatusNot int = iota
	UngencyStatusYes
)

type PmWoService struct {
	PmWo      `xorm:"extends"`
	PmService `xorm:"extends"`
}

func (t *PmWo) TableName() string {
	return "pm_wo"
}

// 清除string字段的右侧空格
func (t *PmWo) Clipped() {
	utils.TrimStruct(t, *t)
}

//增
func (t *PmWo) Add() error {
	e := db.Eloquent.Master()
	count := new(PmWo)
	affw, err := e.Table("pm_wo").ID(core.PK{t.Finr, t.Maintwoid}).Count(count)
	if err != nil {
		return err
	}
	if affw > 0 {
		return errors.New("数据已经存在！")
	}
	_, err = e.Table("pm_wo").Insert(t)

	if err != nil {
		return err
	}
	return nil
}

func (t *PmWo) InsertOne() error {
	now := time.Now()
	today := now.Format("20060102")
	nowTime := now.Format("20060102150405")
	snr := new(Snrtab)
	snr.Finr = 100
	woid, err := snr.GetNextSnr("WOID")
	if err != nil {
		return errors.New("生成Maintwoid出错:" + err.Error())
	}
	t.Maintwoid = woid
	t.Status = 26
	t.Plbegdat = today
	t.Schedbegtime = nowTime
	t.Schedendtime = nowTime
	t.Credatuz = nowTime
	t.Lastmodif = nowTime
	return t.Add()
}

//删
func (t *PmWo) Del() bool {
	e := db.Eloquent.Master()
	_, err := e.ID(core.PK{t.Finr, t.Maintwoid}).Delete(&PmWo{})
	if err != nil {
		return false
	}
	return true
}

//改
func (t *PmWo) Update() error {
	e := db.Eloquent.Master()

	var data PmWo
	_, err := e.ID(core.PK{t.Finr, t.Maintwoid}).Get(&data)
	if err != nil {
		return err
	}
	_, err = e.ID(core.PK{t.Finr, t.Maintwoid}).Update(t)
	if err != nil {
		return err
	}
	if data.Status != t.Status {
		snr := new(Snrtab)
		snr.Finr = 100
		//生成ID
		woreid, _ := snr.GetNextSnr("Worecnr")
		//添加记录
		pm := new(PmWostatus)
		pm.Finr = t.Finr
		pm.Maintwoid = t.Maintwoid
		pm.Statusfrom = data.Status
		pm.Statusto = t.Status
		pm.Worecnr = utils.ValueToInt(woreid, 0)
		pm.Operatetime = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		pm.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		pm.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
		pm.Lastuser = t.Lastuser
		err = pm.Add()
		fmt.Printf("err is :%v", err)
	}
	return nil
}

//查
func (t *PmWo) SelectOne() (PmWo, error) {
	e := db.Eloquent.Master()
	var data PmWo
	_, err := e.ID(core.PK{t.Finr, t.Maintwoid}).Get(&data)
	if err != nil {
		return data, err
	}
	var datalist []PmWoAttrlst
	err = e.Table("pm_wo_attrlst").Where("finr = ? and maintwoid = ?", t.Finr, t.Maintwoid).Find(&datalist)
	if err != nil {
		return data, err
	}
	data.Valst = datalist
	return data, nil
}

//查
func (t *PmWo) SelectPmWoOne() (PmWo, error) {
	e := db.Eloquent.Master()
	var data PmWo
	_, err := e.Where("finr = ? and mainservicenr = ?", t.Finr, t.Mainservicenr).OrderBy("schedbegtime desc").Get(&data)
	if err != nil {
		return data, err
	}
	return data, nil
}

type PmWoDate struct {
	Date    string        `json:"date"`
	Content []PmWoContent `json:"content"`
}
type PmWoContent struct {
	Key    string `json:"key"`
	Value  string `json:"value"`
	Status int    `json:"status"`
}

//按月份查询维护工单调度
func (t *PmWo) SelectPmWoAll(nowdate string) ([]PmWoDate, error) {
	e := db.Eloquent.Master()
	data := make([]PmWo, 0)
	datalist := make([]PmWoDate, 0)
	temlist := make(map[string][]PmWoContent)
	query := e.Table("pm_wo").Where("finr = ?", t.Finr)
	if !utils.ValueIsEmpty(nowdate) {
		time1, _ := utils.TimeParseyyyyMMdd(nowdate)
		first, last := utils.TimeReturnMonth(time1)
		query = query.And("plbegdat >= ?", first)
		query = query.And("plbegdat <= ?", last)
	} else {
		first, last := utils.TimeReturnMonth(time.Now())
		query = query.And("plbegdat >= ?", first)
		query = query.And("plbegdat <= ?", last)
	}
	if t.Status > 0 {
		query = query.And("status = ?", t.Status)
	}
	if t.Assetid > 0 {
		query = query.And("assetid = ?", t.Assetid)
	}
	err := query.Find(&data)
	if err != nil {
		return datalist, err
	}
	for _, v := range data {
		str := v.Plbegdat
		key := str[0:4] + "-" + str[4:6] + "-" + str[6:8]
		content := PmWoContent{}
		content.Key = v.Mainservicenr
		content.Value = v.Descr
		content.Status = v.Status
		temlist[key] = append(temlist[key], content)
	}

	for key, content := range temlist {
		dataone := PmWoDate{}
		dataone.Date = key
		dataone.Content = content
		datalist = append(datalist, dataone)
	}
	return datalist, nil
}

//分页
func (t *PmWo) GetPage(pageSize int, pageIndex int, searchtime string, mainttype string, userId string) ([]PmWoService, int, error) {
	data := make([]PmWoService, 0)

	e := db.Eloquent.Master()
	assetIdLi := make([]int, 0)
	err := e.Table("PM_UserAssetLst").Where("UserId = ?", userId).Cols("AssetId").Find(&assetIdLi)
	if err != nil {
		return data, 0, err
	}
	serviceIdLi := make([]int, 0)
	err = e.Table("PM_UserServiceLst").Where("UserId = ?", userId).Cols("MainServiceId").Find(&serviceIdLi)
	if err != nil {
		return data, 0, err
	}
	where := `from pm_wo left join pm_service on pm_wo.finr = pm_service.finr and pm_wo.mainservicenr = pm_service.mainserviceid`
	where += " where pm_wo.finr = ? "
	parameters := []interface{}{t.Finr}
	table := e.Table(t.TableName()).Where("pm_wo.finr = ? ", t.Finr)
	query := e.Table(t.TableName())
	table = table.Join("LEFT", "pm_service", "pm_wo.finr = pm_service.finr and pm_wo.mainservicenr = pm_service.mainserviceid")

	if !utils.ValueIsEmpty(searchtime) {
		searchtimes := strings.Split(searchtime, "-")
		table = table.And("pm_wo.credatuz >= ?", searchtimes[0])
		table = table.And("pm_wo.credatuz <= ?", searchtimes[1])
		where += " and pm_wo.credatuz >= ? "
		where += " and pm_wo.credatuz <= ? "
		parameters = append(parameters, searchtimes[0], searchtimes[1])
	}
	if t.Assetid > 0 {
		table = table.And("pm_wo.assetid = ?", t.Assetid)
		where += " and pm_wo.assetid = ? "
		parameters = append(parameters, t.Assetid)
	}
	if t.Status == 80 {
		table = table.And("pm_wo.status = 80")
		where += " and pm_wo.status = 80 "

	} else {
		statusLi := []int{26, 40}
		table = table.In("pm_wo.status", statusLi)
		where += " and pm_wo.status in (26, 40) "
	}
	if mainttype != "" {
		table = table.Where("pm_wo.mainttype = ?", mainttype)
		where += " and pm_wo.mainttype = ? "
		parameters = append(parameters, mainttype)
	}
	table = table.In("pm_wo.assetid", assetIdLi)
	table = table.In("pm_wo.mainservicenr", serviceIdLi)
	if len(assetIdLi) > 0{
		inAssetStr := "("
		for index, assetId := range assetIdLi {
			inAssetStr += strconv.Itoa(assetId)
			if index != len(assetIdLi)-1 {
				inAssetStr += ","
			}
		}
		inAssetStr += ")"
		where = where + " and pm_wo.assetid in " + inAssetStr + " "
	} else {
		where += " and 1 = 2 "
	}
	if len(serviceIdLi) > 0 {
		inServiceStr := "("
		for index, serviceId := range serviceIdLi {
			inServiceStr += strconv.Itoa(serviceId)
			if index != len(serviceIdLi)-1 {
				inServiceStr += ","
			}
		}
		inServiceStr += ")"
		where = where + " and pm_wo.mainservicenr in " + inServiceStr + " "
	} else {
		where += " and 1 = 2 "
	}


	orderBy := " order by pm_wo.finr "
	offset := (pageIndex - 1) * pageSize
	querySql := `select pm_wo.*,pm_service.* ` + where + orderBy + " offset ? row fetch next ? row only"
	parameters = append(parameters, offset, pageSize)
	err = query.SQL(querySql, parameters...).Find(&data)
	if err != nil {
		fmt.Println("err:", err)
		return data, 0, err
	}

	pcount := new(PmWoService)
	count, err := table.Count(pcount)
	if err != nil {
		fmt.Println("err2:", err)
		return data, 0, err
	}
	now := time.Now()
	for index, item := range data {
		closeTimeStr := item.Schedendtime
		closeTime, err := time.ParseInLocation("20060102150405", closeTimeStr, utils.TimezoneLocation)
		if err != nil {
			continue
		}
		if now.Before(closeTime) {
			item.UrgencyDegree = UngencyStatusNot
		} else {
			item.UrgencyDegree = UngencyStatusYes
		}
		data[index] = item
	}
	return data, int(count), nil
}

//分页
func (t *PmWo) GetMonthPage(pageSize int, pageIndex int, nowdate string) ([]PmWo, int, error) {
	data := make([]PmWo, 0)
	e := db.Eloquent.Master()
	table := e.Table("pm_wo").Where("finr = ? ", t.Finr)
	where := "where finr = " + "'" + utils.ValueToString(t.Finr, "") + "'"

	if !utils.ValueIsEmpty(nowdate) {
		time1, _ := utils.TimeParseyyyyMMdd(nowdate)
		first, last := utils.TimeReturnMonth(time1)
		table = table.And("plbegdat >= ?", first)
		table = table.And("plbegdat <= ?", last)
		where += " and plbegdat >= " + "'" + utils.ValueToString(first, "") + "'"
		where += " and plbegdat <= " + "'" + utils.ValueToString(last, "") + "'"
	} else {
		first, last := utils.TimeReturnMonth(time.Now())
		table = table.And("plbegdat >= ?", first)
		table = table.And("plbegdat <= ?", last)
		where += " and plbegdat >= " + "'" + utils.ValueToString(first, "") + "'"
		where += " and plbegdat <= " + "'" + utils.ValueToString(last, "") + "'"
	}
	if t.Assetid > 0 {
		table = table.And("assetid = ?", t.Assetid)
		where += " and assetid = " + "'" + utils.ValueToString(t.Assetid, "") + "'"
	}
	if t.Status > 0 {
		table = table.And("status = ?", t.Status)
		where += " and status = " + "'" + utils.ValueToString(t.Status, "") + "'"
	}

	Offset := (pageIndex - 1) * pageSize
	err := e.SQL("SELECT TOP " + utils.ValueToString(pageSize, "") + " pm_wo.* FROM pm_wo " + where + " AND (convert(varchar(10),finr)+convert(varchar(40),maintwoid) NOT IN (SELECT TOP " + utils.ValueToString(Offset, "") + " convert(varchar(10),finr)+convert(varchar(40),maintwoid) FROM pm_wo " + where + " ORDER BY credatuz DESC)) ORDER BY credatuz DESC").Find(&data)
	pcount := new(PmWo)
	count, err := table.Count(pcount)
	if err != nil {
		return data, 0, err
	}
	return data, int(count), nil
}

type CreateData struct {
	TaskType             string
	PmAsset              `xorm:"extends"`
	PmAssetTemplatelst   `xorm:"extends"`
	PmTemplate           `xorm:"extends"`
	PmTemplateServicelst `xorm:"extends"`
	PmService            `xorm:"extends"`
}

//结构体
type TaskData struct {
	TaskType   string
	PmAsset    PmAsset
	PmTemplate PmTemplate
	PmService  PmService
}

var taskChan = make(chan TaskData, 1000) //定义一个调度任务通道

/****
*生成维护工单
***************/
func (t *PmWo) CreateOrder() {

	//创建继承Baxkground的子节点Context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go doSth(ctx)

	data := make([]CreateData, 0)
	//第一步，多表联查出所有的数据
	engine := db.Eloquent.Master()
	query := engine.Table("pm_asset")
	query = query.Join("INNER", "pm_asset_templatelst", "pm_asset.finr = pm_asset_templatelst.finr and pm_asset.assetid = pm_asset_templatelst.assetid")
	query = query.Join("INNER", "pm_template", "pm_template.finr = pm_asset_templatelst.finr and pm_template.maintemplatenr = pm_asset_templatelst.maintemplatenr")
	query = query.Join("INNER", "pm_template_servicelst", "pm_template.finr = pm_template_servicelst.finr and pm_template.maintemplatenr = pm_template_servicelst.maintemplatenr")
	query = query.Join("INNER", "pm_service", "pm_service.finr = pm_template_servicelst.finr and pm_service.mainserviceid = pm_template_servicelst.mainservicenr")

	query = query.Where("pm_asset.finr = ? ", t.Finr)
	err := query.Find(&data)
	if err != nil {
		return
	}
	//第二步，把所有的服务调度放到channel
	for _, v := range data {
		//判断激活状态
		if utils.ValueIsEmpty(v.PmService.Enabled) {
			continue
		}
		dataone := TaskData{}
		dataone.PmService = v.PmService
		dataone.PmTemplate = v.PmTemplate
		dataone.PmAsset = v.PmAsset
		//判断taskType
		if v.PmService.Maintbydate > 0 {
			dataone.TaskType = "A" //A是按照日期维护
		} else if v.PmService.Maintbyhour > 0 {
			dataone.TaskType = "B" //B是按照小时维护
		} else if v.PmService.Maintbymileage > 0 {
			dataone.TaskType = "C" //C是按照仪表值维护
		} else if v.PmService.Needschedule > 0 {
			dataone.TaskType = "D" //D是按照调度维护
		} else {
			continue
		}
		taskChan <- dataone
	}
}

//生成任务工单
func doSth(ctx context.Context) {
	//第三步，启动协程，从channel里读取数据，根据服务维护日期进入不同的方法里
	for {
		select {
		case <-ctx.Done():
			return
		case task, ok := <-taskChan:

			if !ok {
				log.Println("调度生成终止")
				return //停机退出
			}
			switch task.TaskType {
			case "A":

				//当前零点时间
				today := utils.GetZeroTime(time.Now())
				//逻辑：判断是否到了维护时间，（当前时间戳-起始时间戳）%间隔时间
				t1 := utils.TimeFormat(time.Now(), "yyyyMMdd")
				t2 := task.PmService.Duedateon
				time1, _ := utils.TimeParseyyyyMMdd(t1)
				time2, _ := utils.TimeParseyyyyMMdd(t2)
				timelen := int(time1.Unix()) - int(time2.Unix())
				timeunit := task.PmService.Duedateinterval
				glog.InfoExtln("维护工单A", "Mainservicenr:", task.PmService.Mainserviceid)
				glog.InfoExtln("维护工单A", "t1:", t1)
				glog.InfoExtln("维护工单A", "t2:", task.PmService.Duedateon)
				glog.InfoExtln("维护工单A", "timelen:", timelen)
				glog.InfoExtln("维护工单A", "timeunit:", timeunit)
				glog.InfoExtln("维护工单A", "res:", ((timelen / 86400) % timeunit))
				if res := ((timelen / 86400) % timeunit); res == 0 {

					//判断是否已经生成了维护工单，如果生成了，跳过
					pms := new(PmWo)
					pms.Finr = task.PmService.Finr
					pms.Mainservicenr = task.PmService.Mainserviceid
					tem, err := pms.SelectPmWoOne()
					if err != nil {
						glog.InfoExtln("维护工单A", "tem.Mainservicenr:", tem.Mainservicenr)
						continue
					}

					//判断是否添加了服务
					t2now, _ := utils.TimeParse(tem.Schedbegtime)
					endtime := t2now.AddDate(0, 0, timeunit)
					//先把时间字符串格式化成相同的时间类型
					nowtime, _ := utils.TimeParseyyyyMMdd(t1)

					if nowtime.Before(endtime) {
						//处理逻辑
						glog.InfoExtln("维护工单A", "nowtime:", nowtime)
						glog.InfoExtln("维护工单A", "endtime:", endtime)
						continue
					}

					snr := new(Snrtab)
					snr.Finr = 100
					//生成ID
					woid, err := snr.GetNextSnr("WOID")
					if err != nil {
						continue
					}
					//符合逻辑生成维护工单
					pm := new(PmWo)
					pm.Finr = task.PmService.Finr
					pm.Maintwoid = woid
					pm.Mainservicenr = task.PmService.Mainserviceid
					pm.Descr = task.PmService.Descr
					pm.Status = 26
					pm.Priority = task.PmService.Priority
					pm.Assetid = task.PmAsset.Assetid
					pm.Plbegdat = utils.TimeFormat(time.Now(), "yyyyMMdd")
					pm.Schedbegtime = utils.TimeFormat(today, "yyyyMMddHHmmss")
					pm.Schedendtime = utils.TimeFormat(today, "yyyyMMddHHmmss")
					pm.Mainttype = task.PmService.Mainttype
					pm.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					pm.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					err = pm.Add()
					if err != nil {
						continue
					}
					me := new(PmServiceAttrlst)
					me.Finr = task.PmService.Finr
					me.Mainserviceid = task.PmService.Mainserviceid
					data, err := me.SelectAll()
					if err != nil {
						continue
					}
					//生成属性
					for _, v := range data {
						at := new(PmWoAttrlst)
						at.Finr = v.Finr
						at.Descr = v.Descr
						at.Mainservicenr = v.Mainserviceid
						at.Maintwoid = woid
						at.Pos = v.Pos
						at.Parameter = v.Parameter
						at.Paravalue = v.Paravalue
						at.Attrnr = v.Attrnr
						at.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						at.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						err := at.Add()
						if err != nil {
							continue
						}
					}
				}
			case "B":
				//逻辑：起始时间+间隔时间，
				t1 := utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
				//判断是否已经生成了维护工单，如果生成了，跳过
				pms := new(PmWo)
				pms.Finr = task.PmService.Finr
				pms.Mainservicenr = task.PmService.Mainserviceid
				tem, err := pms.SelectPmWoOne()
				if err != nil {
					glog.InfoExtln("维护工单B", "err:", err)
					continue
				}
				glog.InfoExtln("维护工单B", "tem:", tem)
				time2, _ := utils.TimeParse(tem.Schedbegtime)
				time1, _ := utils.TimeParse(t1)
				timelen := int(time1.Unix()) - int(time2.Unix())
				timeunit := task.PmService.Duehourinterval
				glog.InfoExtln("维护工单B", "Mainservicenr:", task.PmService.Mainserviceid)
				glog.InfoExtln("维护工单B", "tem.Schedbegtime:", tem.Schedbegtime)
				glog.InfoExtln("维护工单B", "timelen:", timelen)
				glog.InfoExtln("维护工单B", "timeunit:", timeunit)
				if (timelen - timeunit*3600) > 0 {

					snr := new(Snrtab)
					snr.Finr = 100
					//生成ID
					woid, err := snr.GetNextSnr("WOID")
					if err != nil {
						glog.InfoExtln("维护工单B", "err:", err)
						continue
					}
					//符合逻辑生成维护工单
					pm := new(PmWo)
					pm.Finr = task.PmService.Finr
					pm.Maintwoid = woid
					pm.Mainservicenr = task.PmService.Mainserviceid
					pm.Descr = task.PmService.Descr
					pm.Status = 26
					pm.Priority = task.PmService.Priority
					pm.Assetid = task.PmAsset.Assetid
					pm.Plbegdat = utils.TimeFormat(time.Now(), "yyyyMMdd")
					pm.Schedbegtime = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					pm.Schedendtime = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					pm.Mainttype = task.PmService.Mainttype
					pm.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					pm.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					err = pm.Add()
					if err != nil {
						glog.InfoExtln("维护工单B", "err:", err)
						continue
					}
					me := new(PmServiceAttrlst)
					me.Finr = task.PmService.Finr
					me.Mainserviceid = task.PmService.Mainserviceid
					data, err := me.SelectAll()
					if err != nil {
						glog.InfoExtln("维护工单B", "err:", err)
						continue
					}
					//生成属性
					for _, v := range data {
						at := new(PmWoAttrlst)
						at.Finr = v.Finr
						at.Descr = v.Descr
						at.Mainservicenr = v.Mainserviceid
						at.Maintwoid = woid
						at.Pos = v.Pos
						at.Parameter = v.Parameter
						at.Paravalue = v.Paravalue
						at.Attrnr = v.Attrnr
						at.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						at.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						err := at.Add()
						if err != nil {
							glog.InfoExtln("维护工单B", "err:", err)
							continue
						}
					}
				}
			case "C":
				//逻辑：仪表值
				//第一步：查询资产阈值表，判断是否是触发状态
				pma := new(PmAssetKpi)
				pma.Finr = 100
				pma.Mainserviceid = utils.ValueToString(task.PmService.Mainserviceid, "")
				info, err := pma.SelectAll()
				if err != nil {
					continue
				}
				for _, pmaInfo := range info {
					switch pmaInfo.Kpitype {
					case 1:
						if pmaInfo.Triggerstatus == 1 {
							continue
						}
						if pmaInfo.Thresholdval < pmaInfo.Actualval {
							continue
						}

						//第二步：生成维护工单，
						//逻辑：根据调度时间维护
						snr := new(Snrtab)
						snr.Finr = 100
						//生成ID
						woid, err := snr.GetNextSnr("WOID")
						log.Printf("流水号id:%v", woid)
						if err != nil {
							return
						}
						//符合逻辑生成维护工单
						pm := new(PmWo)
						pm.Finr = task.PmService.Finr
						pm.Maintwoid = woid
						pm.Mainservicenr = task.PmService.Mainserviceid
						pm.Descr = task.PmService.Descr
						pm.Status = 26
						pm.Priority = task.PmService.Priority
						pm.Assetid = task.PmAsset.Assetid
						pm.Plbegdat = utils.TimeFormat(time.Now(), "yyyyMMdd")
						pm.Schedbegtime = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						timenow := utils.ValueToString(task.PmService.Maintimelen, "")
						m, _ := time.ParseDuration(timenow + "h")
						pm.Schedendtime = utils.TimeFormat(time.Now().Add(m), "yyyyMMddHHmmss")
						pm.Mainttype = task.PmService.Mainttype
						pm.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						pm.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						err = pm.Add()
						if err != nil {
							continue
						}
						me := new(PmServiceAttrlst)
						me.Finr = task.PmService.Finr
						me.Mainserviceid = task.PmService.Mainserviceid
						data, err := me.SelectAll()
						if err != nil {
							continue
						}
						//生成属性
						for _, v := range data {
							at := new(PmWoAttrlst)
							at.Finr = v.Finr
							at.Descr = v.Descr
							at.Mainservicenr = v.Mainserviceid
							at.Maintwoid = woid
							at.Pos = v.Pos
							at.Parameter = v.Parameter
							at.Paravalue = v.Paravalue
							at.Attrnr = v.Attrnr
							at.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
							at.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
							err := at.Add()
							if err != nil {
								continue
							}
						}
						//第三步：锁定触发器状态
						pmu := new(PmAssetKpi)
						pmu.Finr = 100
						pmu.Triggerstatus = 1
						pmu.Assetid = utils.ValueToString(task.PmAsset.Assetid, "")
						err = pma.Update()
						if err != nil {
							continue
						}
					case 2:
						if pmaInfo.Counterval < pmaInfo.Countercycleval {
							continue
						}
						//第二步：生成维护工单，
						//逻辑：根据调度时间维护
						snr := new(Snrtab)
						snr.Finr = 100
						//生成ID
						woid, err := snr.GetNextSnr("WOID")
						log.Printf("流水号id:%v", woid)
						if err != nil {
							return
						}
						//符合逻辑生成维护工单
						pm := new(PmWo)
						pm.Finr = task.PmService.Finr
						pm.Maintwoid = woid
						pm.Mainservicenr = task.PmService.Mainserviceid
						pm.Descr = task.PmService.Descr
						pm.Status = 26
						pm.Priority = task.PmService.Priority
						pm.Assetid = task.PmAsset.Assetid
						pm.Plbegdat = utils.TimeFormat(time.Now(), "yyyyMMdd")
						pm.Schedbegtime = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						timenow := utils.ValueToString(task.PmService.Maintimelen, "")
						m, _ := time.ParseDuration(timenow + "h")
						pm.Schedendtime = utils.TimeFormat(time.Now().Add(m), "yyyyMMddHHmmss")
						pm.Mainttype = task.PmService.Mainttype
						pm.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						pm.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						err = pm.Add()
						if err != nil {
							continue
						}
						me := new(PmServiceAttrlst)
						me.Finr = task.PmService.Finr
						me.Mainserviceid = task.PmService.Mainserviceid
						data, err := me.SelectAll()
						if err != nil {
							continue
						}
						//生成属性
						for _, v := range data {
							at := new(PmWoAttrlst)
							at.Finr = v.Finr
							at.Descr = v.Descr
							at.Mainservicenr = v.Mainserviceid
							at.Maintwoid = woid
							at.Pos = v.Pos
							at.Parameter = v.Parameter
							at.Paravalue = v.Paravalue
							at.Attrnr = v.Attrnr
							at.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
							at.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
							err := at.Add()
							if err != nil {
								continue
							}
						}
						//第三步：计数清零
						pmu := new(PmAssetKpi)
						pmu.Finr = 100
						pmu.Countercycleval = 1
						pmu.Assetid = utils.ValueToString(task.PmAsset.Assetid, "")
						err = pma.Update()
						if err != nil {
							continue
						}
					}
				}

			case "D":
				//逻辑：起始时间+间隔时间，
				t1 := utils.TimeFormat(time.Now(), "yyyyMMdd")
				//判断是否已经生成了维护工单，如果生成了，跳过
				pms := new(PmWo)
				pms.Finr = task.PmService.Finr
				pms.Mainservicenr = task.PmService.Mainserviceid
				tem, err := pms.SelectPmWoOne()
				if err != nil {
					continue
				}
				time2, _ := utils.TimeParse(tem.Schedbegtime)
				time1, _ := utils.TimeParseyyyyMMdd(t1)
				timelen := int(time1.Unix()) - int(time2.Unix())
				if err != nil {
					continue
				}
				if timelen >= 0 {
					//逻辑：根据调度时间维护
					snr := new(Snrtab)
					snr.Finr = 100
					//生成ID
					woid, err := snr.GetNextSnr("WOID")
					log.Printf("流水号id:%v", woid)
					if err != nil {
						return
					}
					//符合逻辑生成维护工单
					pm := new(PmWo)
					pm.Finr = task.PmService.Finr
					pm.Maintwoid = woid
					pm.Mainservicenr = task.PmService.Mainserviceid
					pm.Descr = task.PmService.Descr
					pm.Status = 26
					pm.Priority = task.PmService.Priority
					pm.Assetid = task.PmAsset.Assetid
					pm.Plbegdat = utils.TimeFormat(time.Now(), "yyyyMMdd")
					pm.Schedbegtime = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					timenow := utils.ValueToString(task.PmService.Maintimelen, "")
					m, _ := time.ParseDuration(timenow + "h")
					pm.Schedendtime = utils.TimeFormat(time.Now().Add(m), "yyyyMMddHHmmss")
					pm.Mainttype = task.PmService.Mainttype
					pm.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					pm.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
					err = pm.Add()
					if err != nil {
						continue
					}
					me := new(PmServiceAttrlst)
					me.Finr = task.PmService.Finr
					me.Mainserviceid = task.PmService.Mainserviceid
					data, err := me.SelectAll()
					if err != nil {
						continue
					}
					//生成属性
					for _, v := range data {
						at := new(PmWoAttrlst)
						at.Finr = v.Finr
						at.Descr = v.Descr
						at.Mainservicenr = v.Mainserviceid
						at.Maintwoid = woid
						at.Pos = v.Pos
						at.Parameter = v.Parameter
						at.Paravalue = v.Paravalue
						at.Attrnr = v.Attrnr
						at.Credatuz = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						at.Lastmodif = utils.TimeFormat(time.Now(), "yyyyMMddHHmmss")
						err := at.Add()
						if err != nil {
							continue
						}
					}
				}

			default:
				//进行非抢占式任务
			}
		}
	}
}
