package models

import (
	"hongze/hongze_task/utils"
	"rdluck_tools/orm"
	"time"
)

type CompanyReportPermission struct {
	CompanyReportPermissionId int64     `orm:"column(company_report_permission_id);pk"`
	CompanyId                 int       `description:"公司id"`
	ProductId                 int       `description:"产品id"`
	ProductName               string    `description:"产品名称"`
	ReportPermissionId        int       `description:"权限id(作废)"`
	Status          		  string	`description:"状态"`
	CreatedTime               time.Time `description:"创建时间"`
	LastUpdatedTime           time.Time `description:"更新时间"`
	ChartPermissionId         int       `description:"大分类ID"`
	StartDate       string    `description:"合同开始日期"`
	EndDate         string    `description:"合同结束日期"`
	ModifyTime         string    `description:"更新时间"`
}

func GetCompanyReportPermission(companyId int) (items []*CompanyReportPermission, err error) {
	sql := `SELECT * FROM company_report_permission WHERE company_id=? `
	_, err = orm.NewOrm().Raw(sql, companyId).QueryRows(&items)
	return
}

func AddCompanyReportPermission(item *CompanyReportPermission) (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(item)
	return
}

func ModifyCompanyOldPermission(startDate, endDate, productName string, companyId, productId int) (err error){
	o := orm.NewOrm()
	sql := `UPDATE company_report_permission SET start_date=?,end_date=?,product_id=?,product_name=?,modify_time=NOW() WHERE company_id=? AND start_date IS NULL `
	_,err=o.Raw(sql, startDate, endDate, productId, productName, companyId).Exec()
	return
}


//获取需要关闭的产品权益
func GetCompanyReportPermissionNeedClose(endDate string) (items []*CompanyReportPermission, err error) {
	o := orm.NewOrm()
	sql := `SELECT *
          FROM company_report_permission
			WHERE status='试用' AND end_date<=?`
	_, err = o.Raw(sql, endDate).QueryRows(&items)

	//testSql
	//sql := `SELECT *
    //       FROM company_report_permission
	//		WHERE company_id in (194,197,200,201,202) and status='试用'`
	//_, err = o.Raw(sql).QueryRows(&items)
	return
}

//关闭用户权限
func CompanyReportPermissionClose(companyReportPermissionId int64,companyId, productId int) (err error) {
	o := orm.NewOrm()
	//修改产品权限状态为关闭
	sql := `UPDATE company_report_permission SET status='关闭',modify_time=NOW() WHERE company_report_permission_id = ? AND company_id= ? AND product_id = ? `
	_, err = o.Raw(sql, companyReportPermissionId,companyId, productId).Exec()
	if err != nil {
		return err
	}
	return
}

//查询是否存在还未过期的产品权限
func GetCompanyReportPermissionCount(companyId, productId int) (count int,err error) {
	o := orm.NewOrm()
	startDate := time.Now().Format(utils.FormatDate)
	countSql := `SELECT
			COUNT(company_report_permission_id ) AS COUNT
			FROM company_report_permission WHERE status in ('试用','正式') AND end_date >= ? AND company_id= ? AND product_id = ? `

	err = o.Raw(countSql, startDate,companyId,productId).QueryRow(&count)
	return
}
