/*
 * @description: 安全巡检数据库操作相关
 * @Author: LanJianRong
 * @Date: 2020-11-20
 * @FilePath: \construction_management\dao\safe_dao.go
 */

package dao

import (
	"fmt"

	"github.com/go-xorm/xorm"
	"go.mod/models"
	"go.mod/web/viewmodels"
)

// 数据库操作引擎
type AnnexDao struct {
	engine *xorm.Engine
}

// 获得一个DAO对象
func NewAnnexDao(engine *xorm.Engine) *AnnexDao {
	return &AnnexDao{
		engine: engine,
	}
}

// 获取附件列表
func (d *AnnexDao) GetList(dataType int, dataId int, pageNo int, pageSize int) ([]viewmodels.AnnexListView, int64) {
	dataList := make([]viewmodels.AnnexListView, 0)
	start := (pageNo - 1) * pageSize
	total, err := d.engine.Table("`cm_annex` as f").
		Select("f.`id`, f.`account_id`, f.`create_time`, f.`name` as file_name, f.`oss_url` as file_path, a.`name` as account_name").
		Join("LEFT", "`cm_project_account` as a", "a.id = f.account_id").
		Where("f.data_id = ? and f.data_type = ?", dataId, dataType).
		Limit(pageSize, start).
		FindAndCount(&dataList)
	if err != nil {
		return dataList, 0
	}
	return dataList, total
}

// 获取总数
func (d *AnnexDao) GetCount(dataType int, dataId int) (int64, error) {
	file := models.CmAnnex{DataType: dataType, DataId: dataId}
	total, err := d.engine.Count(&file)
	fmt.Println(err)
	if err != nil {
		return 0, err
	}
	return total, nil
}

// 批量插入数据
func (d *AnnexDao) InsertByList(data []models.CmAnnex) error {
	_, err := d.engine.Insert(&data)
	// fmt.Println("__________________________________", data)
	return err
}

// 删除数据（记录id）
func (d *AnnexDao) DeleteById(id int) error {
	file := models.CmAnnex{Id: id}
	_, err := d.engine.Delete(&file)
	return err
}
