package front

import (
	"fmt"
	"github.com/tealeg/xlsx"
	"os"
	qu "qfw/util"
	"strings"
	"time"
	"util"
)

// GroupTaskListByGroup 用户组权限用户组任务列表
func (f *Front) GroupTaskListByGroup() {
	defer qu.Catch()
	if f.Method() == "POST" {
		start, _ := f.GetInteger("start")
		limit, _ := f.GetInteger("length")
		draw, _ := f.GetInteger("draw")
		status := f.GetString("status")
		searchStr := f.GetString("search[value]")
		search := strings.TrimSpace(searchStr)
		query := map[string]interface{}{
			"s_stype": "group", //检索用户组任务
		}
		if status != "-1" { //任务状态
			query["s_status"] = status
		}
		if search != "" {
			query["$or"] = []interface{}{
				map[string]interface{}{"s_projectname": map[string]interface{}{"$regex": search}},
			}
		}
		list, _ := util.Mgo.Find(util.TASKCOLLNAME, query, nil, nil, false, start, limit)
		count := util.Mgo.Count(util.TASKCOLLNAME, query)
		f.ServeJson(map[string]interface{}{"draw": draw, "data": *list, "recordsFiltered": count, "recordsTotal": count})
	} else {
		_ = f.Render("project/task_group_list.html")
	}
}

// GroupTaskListByAdmin 系统管理员权限用户组任务列表
func (f *Front) GroupTaskListByAdmin() {
	defer qu.Catch()
	if f.Method() == "POST" {
		start, _ := f.GetInteger("start")
		limit, _ := f.GetInteger("length")
		draw, _ := f.GetInteger("draw")
		status := f.GetString("status")
		searchStr := f.GetString("search[value]")
		search := strings.TrimSpace(searchStr)
		query := map[string]interface{}{
			"s_stype": "group", //检索用户组任务
		}
		if status != "-1" { //任务状态
			query["s_status"] = status
		}
		if search != "" {
			query["$or"] = []interface{}{
				map[string]interface{}{"s_projectname": map[string]interface{}{"$regex": search}},
				map[string]interface{}{"s_entname": map[string]interface{}{"$regex": search}},
				map[string]interface{}{"s_rule": map[string]interface{}{"$regex": search}},
				map[string]interface{}{"s_departname": map[string]interface{}{"$regex": search}},
			}
		}
		list, _ := util.Mgo.Find(util.TASKCOLLNAME, query, nil, nil, false, start, limit)
		count := util.Mgo.Count(util.TASKCOLLNAME, query)
		f.ServeJson(map[string]interface{}{"draw": draw, "data": *list, "recordsFiltered": count, "recordsTotal": count})
	} else {
		_ = f.Render("project/task_list.html")
	}
}

// GroupTaskDeliver 用户组任务交付
func (f *Front) GroupTaskDeliver() {
	defer qu.Catch()
	user := f.GetSession("user").(map[string]interface{})
	username := qu.ObjToString(user["s_login"]) //当前登录用户
	success := true
	msg := ""
	taskId := f.GetString("taskid") //用户组任务id
	qu.Debug("Group Task ID：", taskId)
	groupTask, _ := util.Mgo.FindById(util.TASKCOLLNAME, taskId, map[string]interface{}{"v_sonids": 1})
	if groupTask != nil && len(*groupTask) > 0 {
		sonUserIds := (*groupTask)["v_sonids"].([]interface{})
		if len(sonUserIds) > 0 {
			for _, id := range sonUserIds {
				userTaskId := qu.ObjToString(id)
				userTask, _ := util.Mgo.FindById(util.TASKCOLLNAME, userTaskId, map[string]interface{}{"s_status": 1})
				status := qu.ObjToString((*userTask)["s_status"])
				if status != "已完成" || status != "已关闭" {
					success = false
					msg = "任务暂未完成"
				}
			}
			if success { //用户组下用户任务全部完成，更新该用户组任务状态
				success = util.Mgo.UpdateById(util.TASKCOLLNAME, taskId, map[string]interface{}{
					"$set": map[string]interface{}{
						"i_completetime": time.Now().Unix(),
						"s_updateperson": username,
						"i_updatetime":   time.Now().Unix(),
						"s_status":       "已完成",
					},
				})
				if !success {
					msg = "更新任务信息失败"
				}
			}
		} else {
			success = false
			msg = "任务暂未分配"
		}
	} else {
		success = false
		msg = "查询任务失败"
	}
	f.ServeJson(map[string]interface{}{"success": success, "msg": msg})
}

var modelpath string = "web/model/任务详情%d.xlsx"

// GroupTaskExport 用户组任务导出
func (f *Front) GroupTaskExport() {
	defer qu.Catch()
	starttime, _ := f.GetInt("i_starttime")
	completetime, _ := f.GetInt("i_completetime")
	status := f.GetString("s_status")
	searchStr := f.GetString("search[value]")
	search := strings.TrimSpace(searchStr)
	query := map[string]interface{}{
		"s_stype": "group",
	}
	if status != "-1" { //任务状态
		query["s_status"] = status
	}
	if search != "" {
		query["$or"] = []interface{}{
			map[string]interface{}{"s_entname": map[string]interface{}{"$regex": search}},
		}
	}
	if starttime > 0 {
		query["i_starttime"] = map[string]interface{}{
			"$gte": starttime,
		}
	}
	if completetime > 0 {
		query["i_completetime"] = map[string]interface{}{
			"$lte": completetime,
		}
	}
	qu.Debug("Query：", query)
	count := util.Mgo.Count(util.TASKCOLLNAME, query)
	if count > 0 {
		file, err := xlsx.OpenFile("taskexportmodel.xlsx")
		if err != nil {
			qu.Debug("Load Excel Model Error")
			f.ServeJson("加载脚本失败")
			return
		}
		sheet := file.Sheets[0]
		fields := map[string]interface{}{
			"s_entname":      1,
			"s_departname":   1,
			"s_rulename":     1,
			"s_projectname":  1,
			"s_groupname":    1,
			"s_personname":   1,
			"i_givenum":      1,
			"i_starttime":    1,
			"i_completetime": 1,
		}
		list, _ := util.Mgo.Find(util.TASKCOLLNAME, query, nil, fields, false, -1, -1)
		for _, l := range *list {
			row := sheet.AddRow()
			entname := qu.ObjToString(l["s_entname"])
			departname := qu.ObjToString(l["s_departname"])
			rulename := qu.ObjToString(l["s_rulename"])
			projectname := qu.ObjToString(l["s_projectname"])
			groupname := qu.ObjToString(l["s_groupname"])
			personname := qu.ObjToString(l["s_personname"])
			givenum := qu.IntAll(l["i_givenum"])
			starttimestr := ""
			if starttime := qu.Int64All(l["i_starttime"]); starttime != 0 {
				starttimestr = qu.FormatDateByInt64(&starttime, qu.Date_Full_Layout)
			}
			completetimestr := ""
			if completetime := qu.Int64All(l["i_completetime"]); completetime != 0 {
				completetimestr = qu.FormatDateByInt64(&completetime, qu.Date_Full_Layout)
			}
			row.AddCell().SetValue(entname)
			row.AddCell().SetValue(departname)
			row.AddCell().SetValue(rulename)
			row.AddCell().SetValue(projectname)
			row.AddCell().SetValue(groupname)
			row.AddCell().SetValue(personname)
			row.AddCell().SetValue(givenum)
			row.AddCell().SetValue(starttimestr)
			row.AddCell().SetValue(completetimestr)
		}
		fname := fmt.Sprintf(modelpath, time.Now().Unix())
		qu.Debug("File Name：", fname)
		err = file.Save(fname)
		if err != nil {
			qu.Debug("Save Excel" + fname + "Error")
			f.ServeJson("导出失败")
			return
		}
		f.ServeFile(fname)
		go func(path string) {
			time.Sleep(time.Minute * 10)
			os.Remove(path)
		}(fname)
	} else {
		f.ServeJson("没有数据")
	}
}
