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

package dao

import (
	"fmt"
	"time"

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

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

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

// 添加审批人
func (d *SafeAuditDao) AddAuditor(safeId int, bId int, auditId int, times int) error {
	auditOrder := d.GetNewOrder(safeId, times)
	auditor := &models.CmSafeAudit{SafeId: safeId, BidsectionId: bId, AuditId: auditId, Times: times, AuditOrder: auditOrder, CreateTime: time.Now()}
	_, err := d.engine.InsertOne(auditor)
	return err
}

// 获取最新审批顺序
func (d *SafeAuditDao) GetNewOrder(safeId int, times int) int {
	var max_order int
	_, err := d.engine.Sql("select Max(`audit_order`) as max_order from cm_safe_audit where safe_id = ? and times = ?", safeId, times).Get(&max_order)
	fmt.Println(err)
	if max_order == 0 {
		return 1
	} else {
		return max_order + 1
	}
}

// 根据当前times，获取审批人
func (d *SafeAuditDao) GetAuditors(id int, times int) []viewmodels.Auditors {
	auditors := make([]viewmodels.Auditors, 0)
	d.engine.Sql("select pa.`name` from `cm_project_account` as pa, `cm_safe_audit` as ca where ca.`safe_id` = ? and ca.`times` = ? and ca.audit_id = pa.id order by `audit_order`", id, times).Find(&auditors)
	return auditors
}

// 根据当前times，获取审批人(包括原报)
func (d *SafeAuditDao) GetAuditorsWithOwner(id int, times int, cur_uid int) []viewmodels.Auditors {
	auditors := make([]viewmodels.Auditors, 0)
	auditor := viewmodels.Auditors{Progress: ""}

	_, err := d.engine.Sql("select name, company, position, id as `audit_id` from `cm_project_account` where id = ?", cur_uid).Get(&auditor)

	if err != nil {
		fmt.Println(err)
	}
	auditors = append(auditors, auditor)

	d.engine.Sql("select pa.`company`, pa.`name`, pa.`account_group`, pa.`position`,ca.`audit_id` as `auditor_id`, ca.`id` as `audit_id`, ca.`status`, ca.`audit_order`, ca.`progress` from `cm_project_account` as pa, `cm_safe_audit` as ca where ca.`safe_id` = ? and ca.`times` = ? and ca.audit_id = pa.id order by `audit_order`", id, times).Find(&auditors)
	// 原报
	return auditors
}

// times从1开始循环，往history里面push
func (d *SafeAuditDao) GetAuditHistory(id int, times int) map[int][]viewmodels.HistorySafeAudit {
	auditorHistory := make(map[int][]viewmodels.HistorySafeAudit, 0)
	for i := 1; i <= times; i++ {
		auditors := make([]viewmodels.HistorySafeAudit, 0)
		d.engine.Sql("select ca.`id`, pa.`name`, pa.`position`, ca.`create_time` as createTime, ca.`end_time` as endTime, ca.`progress`, ca.`opinion`, ca.`status` from `cm_project_account` as pa, `cm_safe_audit` as ca where ca.`safe_id` = ? and ca.audit_id = pa.id and times = ? order by `audit_order`", id, i).Find(&auditors)
		auditorsArr := make([]viewmodels.HistorySafeAudit, 0)
		for _, auditor := range auditors {
			auditorVM := viewmodels.HistorySafeAudit{}
			id, _ := comm.AesEncrypt(auditor.Id, conf.SignSecret)
			auditorVM.Id = id
			auditorVM.Createtime = auditor.Createtime
			auditorVM.EndTime = auditor.EndTime
			auditorVM.Name = auditor.Name
			auditorVM.Position = auditor.Position
			auditorVM.Status = auditor.Status
			auditorVM.Opinion = auditor.Opinion
			auditorVM.Progress = auditor.Progress
			auditorsArr = append(auditorsArr, auditorVM)
		}
		auditorHistory[i] = auditorsArr
	}
	return auditorHistory
}

// 根据id获取记录
func (d *SafeAuditDao) FindById(id int) (*models.CmSafeAudit, error) {
	data := &models.CmSafeAudit{Id: id}
	_, err := d.engine.Get(data)
	return data, err
}

// 改变审批记录状态
func (d *SafeAuditDao) ChangeStatusById(id int, opinion string, status int, rectifiedInfo string) error {
	data := &models.CmSafeAudit{EndTime: time.Now(), Opinion: opinion, Status: status, Rectifiedinfo: rectifiedInfo}
	_, err := d.engine.ID(id).Cols("end_time", "opinion", "status").Update(data)
	return err
}

// 拷贝新的审批流程
func (d *SafeAuditDao) CopyAuditors(safeId int, times int, auditType string, uid int) error {
	oldAuditors := make([]models.CmSafeAudit, 0)
	err := d.engine.Where("safe_id = ? and times = ?", safeId, times).Find(&oldAuditors)
	if err != nil {
		return err
	}

	var copyStatus = true
	fmt.Println("auditType", auditType)
	newAuditors := make([]models.CmSafeAudit, 0)
	for _, auditor := range oldAuditors {
		auditorVM := models.CmSafeAudit{}
		auditorVM.SafeId = auditor.SafeId
		auditorVM.BidsectionId = auditor.BidsectionId
		auditorVM.Times = auditor.Times + 1
		auditorVM.AuditId = auditor.AuditId
		auditorVM.AuditOrder = auditor.AuditOrder
		auditorVM.Progress = auditor.Progress
		auditorVM.CreateTime = time.Now()
		auditorVM.Status = auditor.Status
		// 上报人
		if auditType == "uncheck" {
			auditorVM.Status = 0
		} else {
			if auditor.AuditId == uid {
				auditorVM.Status = 0
				copyStatus = false
			}
		}
		if !copyStatus {
			auditorVM.Status = 0
		}
		newAuditors = append(newAuditors, auditorVM)
	}
	_, err = d.engine.Insert(&newAuditors)
	return err
}

// 增加整改人
func (d *SafeAuditDao) AddCheckWorker(id int, auditId int, opinion string) error {
	auditor, err := d.FindById(id)
	if err != nil {
		return err
	}

	data := &models.CmSafeAudit{SafeId: auditor.SafeId, BidsectionId: auditor.BidsectionId, AuditOrder: auditor.AuditOrder + 1, Times: auditor.Times, AuditId: auditId, Status: 0, Progress: 1, CreateTime: time.Now(), Opinion: opinion}
	_, err = d.engine.Insert(data)
	if err != nil {
		return err
	}
	return nil
}

// 查找最新的整改单
func (d *SafeAuditDao) GetLastedOrder(safeId int) ([]viewmodels.CheckOrderVM, error) {
	data := make([]viewmodels.CheckOrderVM, 0)
	err := d.engine.Sql("select cm.`opinion`, cm.`status`, cm.`end_time`, pa.`name` from `cm_safe_audit` as cm left join `cm_project_account` as pa on pa.`id` = cm.`audit_id` where cm.`safe_id` = ? and cm.`progress` = ?", safeId, 1).Find(&data)
	return data, err
}

// 获取当前的审核人
func (d *SafeAuditDao) GetLastedAuditor(times int, safeId int) (*viewmodels.LatestAuditorVM, error) {
	data := &viewmodels.LatestAuditorVM{}
	_, err := d.engine.Sql("select audit_id, progress, status from cm_safe_audit where times = ? and safe_id = ? and status = 0 order by `audit_order` limit 1", times, safeId).Get(data)
	auditId, _ := comm.AesEncrypt(data.AuditId, conf.SignSecret)
	data.AuditId = auditId
	return data, err
}

//
func (d *SafeAuditDao) InsertData(data []models.CmSafeAudit) error {
	_, err := d.engine.Insert(&data)
	return err
}
