package models

import (
	"eta/eta_mobile/utils"
	"github.com/beego/beego/v2/client/orm"
	"github.com/rdlucklib/rdluck_tools/paging"
	"time"
)

// 英文客户Todo状态枚举值
const (
	EnglishCompanyTodoStatusDoing     = "进行中"
	EnglishCompanyTodoStatusCompleted = "已完成"
	EnglishCompanyTodoStatusVoided    = "已作废"
	EnglishCompanyTodoStatusNull      = "无任务"
)

// EnglishCompanyTodo 英文客户TODO任务
type EnglishCompanyTodo struct {
	Id                 int       `orm:"column(id);pk"`
	CompanyId          int       `description:"客户id"`
	Content            string    `description:"任务描述"`
	SellerId           int       `description:"客户所属销售id"`
	SellerName         string    `description:"客户所属销售名称"`
	CreateUserId       int       `description:"创建人用户id"`
	CreateUserName     string    `description:"创建人用户姓名"`
	ApproveUserId      int       `description:"审批人用户id"`
	ApproveUserName    string    `description:"审批人用户姓名"`
	ApprovedSellerId   int       `description:"审批时，客户所属销售id"`
	ApprovedSellerName string    `description:"审批时，客户所属销售名称"`
	Status             string    `description:"任务状态: 枚举值：进行中,已完成,已作废"`
	ModifyTime         time.Time `description:"修改时间"`
	ApproveTime        time.Time `description:"审核时间"`
	CreateTime         time.Time `description:"创建时间"`
	EndTime            time.Time `description:"截止时间"`
	IsDelete           int       `json:"-" description:"是否已经删除，0：未删除，1：已删除；默认：0"`
	Remark             string    `description:"审批备注"`
}

// EnglishCompanyTodoResp 英文客户TODO响应体
type EnglishCompanyTodoResp struct {
	Id              int    `orm:"column(id);pk"`
	CompanyId       int    `description:"客户id"`
	Content         string `description:"任务描述"`
	SellerId        int    `description:"客户所属销售id"`
	SellerName      string `description:"客户所属销售名称"`
	CreateUserId    int    `description:"创建人用户id"`
	CreateUserName  string `description:"创建人用户姓名"`
	ApproveUserId   int    `description:"审批人用户id"`
	ApproveUserName string `description:"审批人用户姓名"`
	Status          string `description:"任务状态: 枚举值：进行中,已完成,已作废"`
	CreateTime      string `description:"创建时间"`
	EndTime         string `description:"截止时间"`
	ApproveTime     string `description:"审核时间"`
	EndTimeStr      string `description:"格式化后的截止时间"`
	Remark          string `description:"审批备注"`
}

func (item *EnglishCompanyTodo) Create() (err error) {
	o := orm.NewOrmUsingDB("rddp")
	id, err := o.Insert(item)
	if err != nil {
		return
	}
	item.CompanyId = int(id)
	return
}

func (item *EnglishCompanyTodo) Update(cols []string) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	_, err = o.Update(item, cols...)
	return
}

// EnglishCompanyTodoAddReq 新增任务请求
type EnglishCompanyTodoAddReq struct {
	CompanyId   int    `description:"客户id"`
	Description string `description:"任务描述"`
	EndTime     string `description:"截止时间"`
}

// EnglishCompanyTodoEditReq 编辑任务请求
type EnglishCompanyTodoEditReq struct {
	Id          int    `description:"客户任务记录id"`
	CompanyId   int    `description:"客户id"`
	Description string `description:"任务描述"`
	EndTime     string `description:"截止时间"`
}

// EnglishCompanyTodoApproveReq 审批任务请求
type EnglishCompanyTodoApproveReq struct {
	Id     int    `description:"客户任务记录id"`
	Remark string `description:"审批备注"`
}

// GetEnglishCompanyTodoById 根据任务ID获取客户任务
func GetEnglishCompanyTodoById(id int) (item *EnglishCompanyTodo, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_company_todo WHERE id = ? LIMIT 1 `
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// GetCountDoingEnglishCompanyTodo 获取正在进行中的任务数量
func GetCountDoingEnglishCompanyTodo(companyId int) (total int, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT count(1) AS total FROM english_company_todo WHERE status = "进行中" AND company_id = ? AND is_delete = 0 `
	err = o.Raw(sql, companyId).QueryRow(&total)
	return
}

// GetEnglishCompanyTodoPageListResp 英文客户TODO-分页列表
type GetEnglishCompanyTodoPageListResp struct {
	List   []*EnglishCompanyTodoResp
	Paging *paging.PagingItem `description:"分页数据"`
}

// GetEnglishCompanyTodoList 获取客户任务列表
func GetEnglishCompanyTodoList(companyId, startSize, pageSize int, order string) (total int, items []*EnglishCompanyTodo, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT
				a.*
			FROM
				english_company_todo a
			JOIN english_company b ON a.company_id = b.company_id
			WHERE
				a.company_id = ? AND a.status != "已作废" AND a.is_delete = 0 `
	totalSQl := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSQl, companyId).QueryRow(&total); err != nil {
		return
	}
	if order != `` {
		sql += order
	} else {
		sql += ` ORDER BY a.create_time DESC`
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, companyId, startSize, pageSize).QueryRows(&items)
	return
}

// GetDoingEnglishCompanyTodoList 获取客户的进行中任务列表
func GetDoingEnglishCompanyTodoList(companyId int) (items []*EnglishCompanyTodo, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT
				a.*
			FROM
				english_company_todo a
			JOIN english_company b ON a.company_id = b.company_id
			WHERE
				a.company_id = ? AND a.status = "进行中" AND a.is_delete = 0
			ORDER BY
				a.create_time ASC`
	_, err = o.Raw(sql, companyId).QueryRows(&items)
	return
}

// GetEnglishCompanyLatestTodoByCompanyIds 获取英文客户最新的一条TODO任务
func GetEnglishCompanyLatestTodoByCompanyIds(companyIds []int) (items []*EnglishCompanyTodo, err error) {
	itemsLen := len(companyIds)
	if itemsLen == 0 {
		return
	}
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT b.* FROM 
			(
				SELECT
					company_id,
					MAX(create_time) AS ct
				FROM
					english_company_todo
				WHERE
					is_delete = 0 AND status != "已作废" AND company_id IN (` + utils.GetOrmInReplace(itemsLen) + `)
				GROUP BY
					company_id
			) AS a
			LEFT JOIN english_company_todo AS b ON b.company_id = a.company_id AND b.create_time = a.ct `
	_, err = o.Raw(sql, companyIds).QueryRows(&items)
	return
}

type EnglishCompanyTodoDoing struct {
	Id                 int       `description:"待办ID"`
	CompanyId          int       `description:"客户id"`
	CompanyName        string    `description:"客户名称"`
	Content            string    `description:"任务描述"`
	SellerId           int       `description:"客户所属销售id"`
	SellerName         string    `description:"客户所属销售名称"`
	CreateUserId       int       `description:"创建人用户id"`
	CreateUserName     string    `description:"创建人用户姓名"`
	ApproveUserId      int       `description:"审批人用户id"`
	ApproveUserName    string    `description:"审批人用户姓名"`
	ApprovedSellerId   int       `description:"审批时，客户所属销售id"`
	ApprovedSellerName string    `description:"审批时，客户所属销售名称"`
	Status             string    `description:"任务状态: 枚举值：进行中,已完成,已作废"`
	ModifyTime         time.Time `description:"修改时间"`
	ApproveTime        time.Time `description:"审核时间"`
	CreateTime         time.Time `description:"创建时间"`
	EndTime            time.Time `description:"截止时间"`
	Remark             string    `description:"审批备注"`
}

type EnglishCompanyTodoDoingResp struct {
	Id              int    `description:"待办ID"`
	CompanyId       int    `description:"客户id"`
	CompanyName     string `description:"客户名称"`
	Content         string `description:"任务描述"`
	SellerId        int    `description:"客户所属销售id"`
	SellerName      string `description:"客户所属销售名称"`
	CreateUserId    int    `description:"创建人用户id"`
	CreateUserName  string `description:"创建人用户姓名"`
	ApproveUserId   int    `description:"审批人用户id"`
	ApproveUserName string `description:"审批人用户姓名"`
	Status          string `description:"任务状态: 枚举值：进行中,已完成,已作废"`
	CreateTime      string `description:"创建时间"`
	EndTime         string `description:"截止时间"`
	ApproveTime     string `description:"审核时间"`
	Remark          string `description:"审批备注"`
}

// GetEnglishCompanyTodoDoingPageListResp 英文客户未完成TODO-分页列表
type GetEnglishCompanyTodoDoingPageListResp struct {
	List   []*EnglishCompanyTodoDoingResp
	Paging *paging.PagingItem `description:"分页数据"`
}

// GetEnglishCompanyTodoDoingList 获取客户任务未完成列表
func GetEnglishCompanyTodoDoingList(startSize, pageSize int, order string) (total int, items []*EnglishCompanyTodoDoing, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT
				a.*,
				b.company_name
			FROM
				english_company_todo a
			JOIN english_company b ON a.company_id = b.company_id
			WHERE
				a.status = "进行中" AND a.is_delete = 0 `
	totalSQl := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSQl).QueryRow(&total); err != nil {
		return
	}
	if order != `` {
		sql += order
	} else {
		sql += ` ORDER BY a.end_time ASC`
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, startSize, pageSize).QueryRows(&items)
	return
}

// DeleteEnglishCompanyTodoByCompanyId (软)删除英文客户TODO
func DeleteEnglishCompanyTodoByCompanyId(companyId int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `UPDATE english_company_todo SET is_delete = 1 WHERE company_id = ?`
	_, err = o.Raw(sql, companyId).Exec()
	return
}
