package models

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

const (
	EnglishCompanyDisabled = iota
	EnglishCompanyEnabled
	EnglishCompanyHalfEnabled
)

// EnglishCompany 英文客户
type EnglishCompany struct {
	CompanyId   int       `orm:"column(company_id);pk" description:"英文客户ID"`
	CompanyName string    `description:"客户名称"`
	CountryCode string    `description:"国家Code"`
	Country     string    `description:"国家"`
	SellerId    int       `description:"销售ID"`
	SellerName  string    `description:"销售姓名"`
	ViewTotal   int       `description:"累计点击量/阅读量"`
	IsDeleted   int       `description:"删除状态：0-正常；1-已删除"`
	CreateTime  time.Time `description:"创建时间"`
	ModifyTime  time.Time `description:"更新时间"`
	Enabled     int       `description:"0-禁用; 1-启用; 2-部分禁用"`
	Status      int       `description:"1:正式,2:临时,3:终止"`
}

type EnglishCompanyListItem struct {
	EnglishCompany
	TodoStatusStr string
	TodoEndTime   time.Time
	TodoSellerId  int
}

func (item *EnglishCompany) TableName() string {
	return "english_company"
}

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

// EnglishCompanySaveReq 英文客户-保存请求体
type EnglishCompanySaveReq struct {
	CompanyId     int    `description:"客户ID"`
	CompanyName   string `description:"客户名称"`
	CountryCode   string `description:"国家代码"`
	Country       string `description:"国家"`
	SellerId      int    `description:"销售ID"`
	EnPermissions []int  `description:"英文权限IDs"`
}

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

// GetEnglishCompanyById 主键获取客户
func GetEnglishCompanyById(id int) (item *EnglishCompany, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_company WHERE is_deleted = 0 AND company_id = ? LIMIT 1`
	err = o.Raw(sql, id).QueryRow(&item)
	return
}

// GetEnglishCompanyByName 名称获取客户
func GetEnglishCompanyByName(companyName string) (item *EnglishCompany, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_company WHERE is_deleted = 0 AND company_name = ? LIMIT 1`
	err = o.Raw(sql, companyName).QueryRow(&item)
	return
}

// EnglishCompanyDelReq 英文客户-删除请求体
type EnglishCompanyDelReq struct {
	CompanyId int `description:"客户ID"`
}

// DeleteEnglishCompanyAndEmails 删除英文客户及联系人
func DeleteEnglishCompanyAndEmails(companyId int) (err error) {
	o := orm.NewOrmUsingDB("rddp")
	tx, err := o.Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 删除客户
	sql := `UPDATE english_company SET is_deleted = 1,modify_time = NOW() WHERE company_id = ? LIMIT 1`
	_, err = tx.Raw(sql, companyId).Exec()
	if err != nil {
		return
	}

	// 删除联系人
	sql = `UPDATE english_report_email SET is_deleted = 1,modify_time = NOW() WHERE company_id = ?`
	_, err = tx.Raw(sql, companyId).Exec()
	return
}

// EnglishCompanyPageListResp 英文客户-分页列表响应体
type EnglishCompanyPageListResp struct {
	List   []*EnglishCompanyResp
	Paging *paging.PagingItem `description:"分页数据"`
}

// EnglishCompanyResp 英文客户-列表响应体
type EnglishCompanyResp struct {
	CompanyId     int                     `description:"客户ID"`
	CompanyName   string                  `description:"客户名称"`
	CountryCode   string                  `description:"国家代码"`
	Country       string                  `description:"国家"`
	SellerId      int                     `description:"销售ID"`
	SellerName    string                  `description:"销售姓名"`
	ViewTotal     int                     `description:"累计点击量"`
	CreateTime    string                  `description:"创建时间"`
	Enabled       int                     `description:"0-禁用; 1-启用; 2-部分禁用"`
	TodoInfo      *EnglishCompanyListTodo `description:"TODO任务信息"`
	EnPermissions []int                   `description:"英文权限"`
}

// EnglishCompanyListTodo 英文客户列表-TODO任务信息
type EnglishCompanyListTodo struct {
	Deadline       string `description:"未完成的todo任务的截止日期，截止目前还剩余的天数"`
	TodoEndTimeStr string `description:"未完成的todo任务的截止日期拼接格式"`
	//TodoEndTime     time.Time `description:"未完成的todo任务的截止日期"`
	TodoStatus      bool   `description:"是否存在进行中任务"`
	CanConfirm      bool   `description:"是否允许完成任务"`
	HiddenConfirm   bool   `description:"是否隐藏完成任务按钮"`
	HiddenCreate    bool   `description:"是否隐藏新增/编辑按钮"`
	TodoButtonColor string `description:"任务按钮颜色: red; green; gray"`
}

// GetEnglishCompanyPageList 获取客户列表-分页
func GetEnglishCompanyPageList(condition string, pars []interface{}, order string, startSize, pageSize int) (total int, list []*EnglishCompanyListItem, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT
	c.*,
IF
	( ct.status IS NULL, "无任务", ct.status ) AS todo_status_str,
	ct.seller_id as todo_seller_id,
IF
	( ct.end_time IS NULL or ct.status !="进行中", "9999-01-01", ct.end_time) AS todo_end_time
FROM
	english_company AS c
	LEFT JOIN (
SELECT
	b.* 
FROM
	(
SELECT
	company_id,
	MAX( create_time ) AS ct 
FROM
	english_company_todo 
WHERE
	is_delete = 0 
	AND STATUS != "已作废"
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 
	) AS ct ON c.company_id = ct.company_id 
WHERE
	c.is_deleted = 0 AND c.status = 1`
	sql += condition
	if order != "" {
		sql += order
	} else {
		sql += ` ORDER BY c.create_time DESC, c.company_id DESC`
	}
	totalSQl := `SELECT COUNT(1) total FROM (` + sql + `) z`
	if err = o.Raw(totalSQl, pars).QueryRow(&total); err != nil {
		return
	}
	sql += ` LIMIT ?,?`
	_, err = o.Raw(sql, pars, startSize, pageSize).QueryRows(&list)
	return
}

// GetEnglishCompanyViewPageListResp 英文客户-点击量分页列表响应体
type GetEnglishCompanyViewPageListResp struct {
	List   []*EnglishCompanyViewResp
	Paging *paging.PagingItem `description:"分页数据"`
}

// EnglishCompanyViewResp 英文客户-点击量响应体
type EnglishCompanyViewResp struct {
	EmailId      int    `description:"联系人ID"`
	UserName     string `description:"联系人姓名"`
	Email        string `description:"邮箱地址"`
	ViewTotal    int    `description:"累计点击量"`
	LastViewTime string `description:"创建时间"`
}

// GetEnglishCompanyList 获取英文客户列表
func GetEnglishCompanyList(condition string, pars []interface{}, order string) (list []*EnglishCompany, err error) {
	o := orm.NewOrmUsingDB("rddp")
	sql := `SELECT * FROM english_company WHERE is_deleted = 0 `
	sql += condition
	if order != "" {
		sql += order
	} else {
		sql += ` ORDER BY create_time DESC`
	}
	_, err = o.Raw(sql, pars).QueryRows(&list)
	return
}

// EnglishCompanyEditEnabledReq 禁启用请求体
type EnglishCompanyEditEnabledReq struct {
	CompanyId int `description:"公司ID"`
	Enabled   int `description:"1:有效，0:禁用"`
}
