package company_todo

import (
	"github.com/beego/beego/v2/client/orm"
	"time"
)

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

type CompanyTodoListItem struct {
	*CompanyTodo
	EndTimeStr string `description:"格式化后的截止时间"`
}

// Update 客户任务 数据表
func (companyTodo *CompanyTodo) Update(cols []string) (err error) {
	o := orm.NewOrm()
	_, err = o.Update(companyTodo, cols...)
	return
}

// AddCompanyTodo 新增任务请求
func AddCompanyTodo(item *CompanyTodo) (lastId int64, err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	lastId, err = to.Insert(item)
	if err != nil {
		return
	}

	//更新客户产品的状态
	sql := `UPDATE company_product SET todo_status='未完成',todo_create_time=NOW(),todo_modify_time=NOW(),modify_time=NOW(),todo_end_time=? WHERE company_id=? AND product_id=? `
	_, err = to.Raw(sql, item.EndTime, item.CompanyId, item.ProductId).Exec()
	return
}

// EditCompanyTodo 编辑任务
func (companyTodo *CompanyTodo) EditCompanyTodo(cols []string) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	_, err = to.Update(companyTodo, cols...)

	//更新客户产品的状态
	//sql := `UPDATE company_product SET todo_status='未完成',modify_time=NOW() WHERE company_id=? AND product_id=? `
	//_, err = to.Raw(sql, companyTodo.CompanyId, companyTodo.ProductId).Exec()
	return
}

// ApproveCompanyTodo 审批通过任务
func (companyTodo *CompanyTodo) ApproveCompanyTodo(cols []string) (err error) {
	o := orm.NewOrm()
	to, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	_, err = to.Update(companyTodo, cols...)

	//更新客户产品的状态
	sql := `UPDATE company_product SET todo_status='已完成',todo_approve_time=NOW(),todo_modify_time=NOW(),modify_time=NOW() WHERE company_id=? AND product_id=? `
	_, err = to.Raw(sql, companyTodo.CompanyId, companyTodo.ProductId).Exec()
	return
}

// GetCountDoingCompanyTodo 获取正在进行中的任务数量
func GetCountDoingCompanyTodo(companyId, productId int) (total int, err error) {
	o := orm.NewOrm()
	sql := `select count(1) as total from company_todo where status="进行中" and company_id = ? and product_id =? AND is_delete=0 `
	err = o.Raw(sql, companyId, productId).QueryRow(&total)
	return
}

// GetCompanyTodoById 根据任务id获取客户任务
func GetCompanyTodoById(id int) (item *CompanyTodo, err error) {
	o := orm.NewOrm()
	sql := `select * from company_todo where id = ? `
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// GetCompanyTodoList 获取客户任务列表
func GetCompanyTodoList(companyId, productId int) (items []*CompanyTodo, err error) {
	o := orm.NewOrm()
	var pars []interface{}
	sql := `select a.* from company_todo a join company_product b on a.company_id=b.company_id and a.product_id=b.product_id and a.seller_id=b.seller_id  where a.company_id = ? and a.status !="已作废" and a.is_delete=0 `
	pars = append(pars, companyId)

	//如果有传入产品id，那么只查询该类型下的产品
	if productId != 0 {
		sql += ` and a.product_id = ? `
		pars = append(pars, productId)
	}
	sql += ` order by a.create_time asc`
	_, err = o.Raw(sql, pars...).QueryRows(&items)
	return
}

// GetCompanyTodoListV2 获取客户任务列表
func GetCompanyTodoListV2(condition string, pars []interface{}) (items []*CompanyTodo, err error) {
	o := orm.NewOrm()
	sql := `select * from company_todo where 1 = 1 `

	sql += condition + ` order by create_time asc`
	_, err = o.Raw(sql, pars...).QueryRows(&items)
	return
}

// GetDoingCompanyTodoList 获取客户的进行中任务列表
func GetDoingCompanyTodoList(companyId, productId int) (items []*CompanyTodo, err error) {
	o := orm.NewOrm()
	var pars []interface{}
	sql := `select a.* from company_todo a join company_product b on a.company_id=b.company_id and a.product_id=b.product_id and a.seller_id=b.seller_id where a.status="进行中" and a.company_id = ? and a.is_delete=0 `
	pars = append(pars, companyId)

	//如果有传入产品id，那么只查询该类型下的产品
	if productId != 0 {
		sql += ` and a.product_id = ? `
		pars = append(pars, productId)
	}
	sql += ` order by a.product_id asc,a.create_time asc `
	_, err = o.Raw(sql, pars...).QueryRows(&items)
	return
}

// GetDoingCompanyTodoByCompanyIds 根据客户id集合字符串获取所有客户待办的任务列表
func GetDoingCompanyTodoByCompanyIds(companyIds, condition string, pars []interface{}) (items []*CompanyTodo, err error) {
	if companyIds == `` {
		return
	}
	sql := `SELECT * FROM company_todo WHERE status="进行中" and company_id in (` + companyIds + `) and is_delete=0 `
	sql += condition
	sql += ` ORDER BY id ASC `
	o := orm.NewOrm()
	_, err = o.Raw(sql, pars...).QueryRows(&items)
	return
}

type CompanyTodoReportRecordGroup struct {
	AdminId    int    `description:"所属销售id"`
	AdminName  string `description:"所属销售名称"`
	Num        int    `description:"汇总次数"`
	CompanyIds string `description:"客户id字符串"`
}

// GetDoingGroupCompanyReportRecordGroupList 获取销售分组数据（进行中）
func GetDoingGroupCompanyReportRecordGroupList(condition string, pars []interface{}) (list []*CompanyTodoReportRecordGroup, err error) {
	o := orm.NewOrm()
	//sql := ` SELECT DISTINCT b.id, a.seller_id as admin_id,a.seller_name admin_name,count(1) num,GROUP_CONCAT(DISTINCT a.company_id SEPARATOR ',') AS company_ids
	//			FROM  company_report_record a join company_todo b on a.company_id=b.company_id and a.product_id=b.product_id
	//			WHERE 1=1
	//`
	//if condition != "" {
	//	sql += condition
	//}
	//sql += ` GROUP BY a.seller_id`

	//sql := ` SELECT a.seller_id as admin_id,a.seller_name as admin_name,count(1) num,GROUP_CONCAT(DISTINCT a.company_id SEPARATOR ',') AS company_ids
	//			FROM  company_todo a
	//join company_product b on a.company_id=b.company_id and a.product_id=b.product_id
	//			WHERE 1=1
	//`
	sql := ` SELECT b.seller_id as admin_id,b.seller_name as admin_name,count(1) num,GROUP_CONCAT(DISTINCT a.company_id SEPARATOR ',') AS company_ids  
				FROM  company_todo a 
	join company_product b on a.company_id=b.company_id and a.product_id=b.product_id and a.seller_id =b.seller_id
				WHERE 1=1 AND a.is_delete=0 
 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY admin_id`

	_, err = o.Raw(sql, pars).QueryRows(&list)

	return
}

// GetFinishedGroupCompanyReportRecordGroupList 获取销售分组数据（已完成）
func GetFinishedGroupCompanyReportRecordGroupList(condition string, pars []interface{}) (list []*CompanyTodoReportRecordGroup, err error) {
	o := orm.NewOrm()
	//sql := ` SELECT a.approved_seller_id as admin_id,a.approved_seller_name as admin_name,count(1) num,GROUP_CONCAT(DISTINCT a.company_id SEPARATOR ',') AS company_ids
	//			FROM  company_todo a
	//join company_product b on a.company_id=b.company_id and a.product_id=b.product_id
	//			WHERE 1=1
	//`
	sql := ` SELECT b.seller_id as admin_id,b.seller_name as admin_name,count(1) num,GROUP_CONCAT(DISTINCT a.company_id SEPARATOR ',') AS company_ids  
				FROM  company_todo a 
	join company_product b on a.company_id=b.company_id and a.product_id=b.product_id and a.approved_seller_id=b.seller_id 
				WHERE 1=1 AND a.is_delete=0 
 `
	if condition != "" {
		sql += condition
	}
	sql += ` GROUP BY admin_id`

	_, err = o.Raw(sql, pars).QueryRows(&list)

	return
}

// CompanyTodoAddReq 新增任务请求
type CompanyTodoAddReq struct {
	CompanyId   int    `description:"客户id"`
	ProductId   int    `description:"产品id，ficc传：1，权益传：2"`
	Description string `description:"任务描述"`
	EndTime     string `description:"截止时间"`
}

// CompanyTodoEditReq 编辑任务请求
type CompanyTodoEditReq struct {
	Id          int    `description:"客户任务记录id"`
	CompanyId   int    `description:"客户id"`
	ProductId   int    `description:"产品id，ficc传：1，权益传：2"`
	Description string `description:"任务描述"`
	EndTime     string `description:"截止时间"`
}

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