package company

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

type CompanyDelayPermission struct {
	Id                int       `orm:"column(id);pk"`
	CompanyId         int       `description:"客户id"`
	CompanyApplyId    int       `description:"申请id"`
	ChartPermissionId int       `description:"权限id"`
	StartDate         string    `description:"开始日期"`
	EndDate           string    `description:"结束日期"`
	CreateTime        time.Time `description:"创建时间"`
	ModifyTime        time.Time `description:"修改时间"`
}

//新增客户合同
func AddCompanyDelayPermission(item *CompanyDelayPermission) (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(item)
	return
}

func ModifyCompanyDelayPermission(companyId, companyApplyId, chartPermissionId int) (err error) {
	o := orm.NewOrm()
	sql := `UPDATE company_delay_permission SET end_date=DATE_FORMAT(DATE_ADD(end_date, INTERVAL 2 MONTH),'%Y-%m-%d') WHERE company_id=? AND company_apply_id=? AND chart_permission_id=? `
	_, err = o.Raw(sql, companyId, companyApplyId, chartPermissionId).Exec()
	return
}

func GetDelayPermissionCount(companyId, companyApplyId, chartPermissionId int) (count int, err error) {
	o := orm.NewOrm()
	sql := `SELECT COUNT(1) AS count FROM company_delay_permission WHERE company_id=? AND company_apply_id=? AND chart_permission_id=? `
	err = o.Raw(sql, companyId, companyApplyId, chartPermissionId).QueryRow(&count)
	return
}

func GetApplyDelayPermission(companyApplyId int) (delay_permission string, err error) {
	o := orm.NewOrm()
	sql := ` SELECT GROUP_CONCAT(DISTINCT b.permission_name  SEPARATOR ' ') AS delay_permission FROM company_delay_permission AS a
			INNER JOIN chart_permission AS b ON a.chart_permission_id=b.chart_permission_id
			WHERE company_apply_id=? `
	err = o.Raw(sql, companyApplyId).QueryRow(&delay_permission)
	return
}

func GetDelayPermissionItems(companyId, companyApplyId int) (items []*CompanyDelayPermission, err error) {
	o := orm.NewOrm()
	sql := `SELECT * FROM company_delay_permission WHERE company_id=? AND company_apply_id=?  `
	_, err = o.Raw(sql, companyId, companyApplyId).QueryRows(&items)
	return
}

//根据合同id删除对应的权限
func DeleteCompanyDelayPermission(companyApplyId int) (err error) {
	o := orm.NewOrm()
	sql := `DELETE FROM company_delay_permission WHERE company_apply_id=? `
	_, err = o.Raw(sql, companyApplyId).Exec()
	return
}
