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

package dao

import (
	"errors"
	"fmt"
	"time"

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

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

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

func (d *QualityDao) FindById(id int) *models.CmQuality {
	data := &models.CmQuality{Id: id}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

// id获得数据
func (d *QualityDao) GetListByBid(id int, pageNo int, pageSize int) ([]models.CmQuality, int64) {
	dataList := make([]models.CmQuality, 0)
	start := (pageNo - 1) * pageSize
	total, err := d.engine.
		Where("bidsection_id=?", id).
		Asc("id").
		Limit(pageSize, start).
		FindAndCount(&dataList)
	if err != nil {
		return dataList, 0
	}
	return dataList, total
}

// 插入单条记录
func (d *QualityDao) InsertRecord(data models.CmQuality) (bool, error) {
	affected, err := d.engine.InsertOne(data)
	return affected > 0, err
}

// 删除记录
func (d *QualityDao) DeleteRecord(id int) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		session.Rollback()
		return err
	}

	quality := &models.CmQuality{Id: id}
	_, err = session.Get(quality)
	if err != nil {
		session.Rollback()
		return err
	}
	bidsectionId := quality.BidsectionId
	_, err = session.ID(id).Delete(quality)
	if err != nil {
		session.Rollback()
		return err
	}
	// 计算当前安全巡检总数
	_, err = session.Exec("update `cm_tree` set `quality_total` = if(`quality_total` >= 1, `quality_total` - 1, 0),  `quality_rectification` = if(`quality_rectification` >= 1, `quality_rectification` - 1, 0) where `bidsection_id` = ?", bidsectionId)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	return err
}

// 根据code获取记录
func (d *QualityDao) FindByCode(code string) bool {
	data := &models.CmQuality{Code: code}
	has, _ := d.engine.Get(data)
	return has
}

// 筛选出应用了当前规则的条数
func (d *QualityDao) CountRuleCode(bid int) (int64, error) {
	data := &models.CmQuality{}
	total, err := d.engine.Where("`bidsection_id` = ?", bid).Count(data)
	if err != nil {
		total = 0
	}
	return total, err
}

// 更改status
func (d *QualityDao) ChangeStatus(id int, status int, inspection string, inspectionDetail string, demand string, createTime time.Time) error {
	data := &models.CmQuality{Status: status, Inspection: inspection, InspectionDetail: inspectionDetail, Demand: demand, CreateTime: createTime}
	_, err := d.engine.ID(id).Cols("status", " inspection", "inspection_detail", "demand", "create_time").Update(data)
	return err
}

// 获得某状态下的安全
func (d *QualityDao) GetStatus(bidsectionId int, status int) []models.CmQuality {
	datalist := make([]models.CmQuality, 0)
	_ = d.engine.
		Where("bidsection_id = ? and status=? ", bidsectionId, status).
		Desc("id").
		Find(&datalist)
	return datalist
}

// 获得某年份下的安全
func (d *QualityDao) GetTypeYear(bidsectionId int, year int) []viewmodels.QualitySurveyList {

	startYear := fmt.Sprintf("%d-01-01:00.00.00", year)
	endYear := fmt.Sprintf("%d-12-31:23.59.59", year)

	datalist := make([]viewmodels.QualitySurveyList, 0)
	_ = d.engine.Table("`cm_quality` as cs").
		Select("cs.id, cs.`create_time`, cs.`inspection_detail`, cs.status, pa.`name` as `audit_name`").
		Where("cs.bidsection_id = ? and cs.create_time>='"+startYear+"' and cs.create_time<='"+endYear+"' ", bidsectionId).
		Join("left", "cm_project_account as pa", "pa.id = cs.uid").
		Desc("id").
		Find(&datalist)
	// _ = d.engine.
	// 	Where("bidsection_id = ? and create_time>='"+startYear+"' and create_time<='"+endYear+"' ", bidsectionId).
	// 	Desc("id").
	// 	Find(&datalist)
	return datalist
}

// 获得某状态下的安全
func (d *QualityDao) GetStatusByProjectAndAccount(projectId int, projectAccountId int, status int) []models.CmQuality {
	datalist := make([]models.CmQuality, 0)
	_ = d.engine.
		Where("project_id = ? and audit_id= ? and status=? ", projectId, projectAccountId, status).
		Desc("id").
		Find(&datalist)
	return datalist
}

// 事务-创建新的安全巡检记录
func (d *QualityDao) CreateQuality(data models.CmQuality) error {
	session := d.engine.NewSession()
	defer session.Close()
	err := session.Begin()
	if err != nil {
		session.Rollback()
		return err
	}
	has, err := session.Where("code = ?", data.Code).Get(&data)
	// err或者code存在都回滚
	if err != nil {
		session.Rollback()
		return err
	}
	if has == true {
		session.Rollback()
		return errors.New("该编号已存在!")
	}
	_, err = session.Insert(data)
	if err != nil {
		session.Rollback()
		return err
	}
	// 更新cm_tree中的quality_total、quality_rectification
	_, err = session.Exec("update `cm_tree` set `quality_total` = `quality_total` + 1 , `quality_rectification` = `quality_rectification` + 1 where `bidsection_id` = ?", data.BidsectionId)
	if err != nil {
		session.Rollback()
		return err
	}
	err = session.Commit()
	if err != nil {
		return err
	}
	return nil
}
