package common

import (
	"dbweb/core"
	"dbweb/lib/safe"
	"dbweb/modules/common/recordview"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"time"

	"github.com/kardianos/osext"
	"github.com/linlexing/dbx/data"
	"github.com/linlexing/dbx/pageselect"
)

const (
	modelTaskName         = "TASK"
	modelTaskProgressName = "TASKPROGRESS"
)

type task struct{}
type taskZipFile struct{}
type modelTaskProgress struct {
	TaskID  string    `dbx:"str(24) primary key"`
	RowNO   int64     `dbx:"int primary key"`
	LogTime time.Time `dbx:"date not null"`
	Content string    `dbx:"str not null"`
}
type modelTask struct {
	ID            string    `dbx:"str(24) primary key"`
	Name          string    `dbx:"str(300) not null"`
	Status        string    `dbx:"str(20) not null"`
	Result        string    `dbx:"str"`
	Executor      string    `dbx:"str(50) not null"`
	ExeTime       time.Time `dbx:"DATE NOT NULL"`
	ExeDept       string    `dbx:"str(50) not null"`
	ExeIP         string    `dbx:"str(50) not null"`
	CompletedTime time.Time `dbx:"date"`
	Params        string    `dbx:"STR"`
}

func init() {
	core.RegisterModel(modelTask{}, 1, false, modelTaskName)
	/*taskprogress 不能直接调入，可能会太多*/
	core.RegisterModel(modelTaskProgress{}, 1, false, modelTaskProgressName)
	core.RegisterBill("task", new(task), modelTaskName)
	core.RegisterFun("taskzipfile", new(taskZipFile))
}
func (t *taskZipFile) Get(p *core.ElementHandleArgs) {
	dir, err := osext.ExecutableFolder()
	if err != nil {
		core.LOG.Panic(err)
	}
	fileName := filepath.Join(dir, "taskfiles", p.PKS[0])
	http.ServeFile(p.Res, p.Req, fileName)
}
func (t *task) Get(p *core.BillGetHandleArgs) {
	dir, err := osext.ExecutableFolder()
	if err != nil {
		core.LOG.Panic(err)
	}
	fileName := filepath.Join(dir, "taskfiles", p.KeyValues()[0].(string)+".zip")

	if finfo, err := os.Stat(fileName); err != nil && !os.IsNotExist(err) {
		core.LOG.Panic(err)
	} else if err == nil && p.Record.Main["STATUS"].(string) == "completed" {
		p.More["ZipFileSize"] = finfo.Size()
		p.More["ZipFileUrl"] = p.User.Sign(fmt.Sprintf("/taskzipfile/%s.zip", p.Record.Main["ID"]))
		p.More["HasZipFile"] = true
	}
	//调入进度明细，只载入前面的20条
	tab, err := data.OpenTable(p.DB.DriverName(), p.DB, "TASKPROGRESS")
	if err != nil {
		core.LOG.Panic(err)
	}
	sel := pageselect.NewPageSelect(
		"select * from taskprogress where taskid={{P .id}}",
		tab.ColumnTypes, false)
	sel.SQLRenderArgs = map[string]interface{}{"id": p.Record.Main["ID"]}
	sel.Order = []string{"ROWNO"}
	sel.Limit = 21
	rows, _, err := sel.QueryRows(p.DB.DriverName(), p.DB)
	if err != nil {
		core.LOG.Panic(err)
	}
	if len(rows) > 20 {
		rows = rows[0:20]
		p.More["MoreProgressUrl"] = p.User.Sign(recordview.BuildRecordViewURL(
			"taskprogress",
			fmt.Sprintf("%s的进度明细", p.Record.Main["ID"]),
			fmt.Sprintf("taskid='%s'", p.Record.Main["ID"]),
			nil,
			p.User))
	}
	p.More["PROGRESS"] = rows
	//生成摘要信息
	switch safe.String(p.Record.Main["STATUS"]) {
	case "completed":
		strMes := "成功完成"
		if mes := safe.String(p.Record.Main["RESULT"]); len(mes) > 0 {
			strMes = mes
		}
		p.More["Message"] = template.HTML(strMes)
	case "running":
		p.More["Message"] = template.HTML("正在运行中...")
	case "error":
		p.More["Error"] = true
		p.More["Message"] = convertMessage(safe.Split(safe.String(p.Record.Main["RESULT"]), "\n")[0])
	}
	p.HTML()
}
func convertMessage(str string) template.HTML {
	str = strings.Replace(str, "\r\n", "\n", -1)
	str = strings.Replace(str, "\n", "<br/>", -1)
	str = strings.Replace(str, " ", "&nbsp;", -1)
	str = strings.Replace(str, "\t", "&emsp;", -1)
	return template.HTML(str)
}
