/*
 * @description: 安全巡检审批相关
 * @Author: LanJianRong
 * @Date: 2020-12-18
 * @FilePath: \construction_management\web\api\safe_rpc_api.go
 */
package services

import (
	"errors"
	"log"
	"time"

	"github.com/kataras/iris/v12"
	"go.mod/dao"
	"go.mod/datasource"
	"go.mod/models"
	"go.mod/web/viewmodels"
)

type SafeAuditService interface {
	ValidRule(ctx iris.Context) (viewmodels.SafeAudit, error)
	ValidStart(ctx iris.Context) (viewmodels.AuditStart, error)
	AddAuditor(safeId int, bId int, auditId int, times int) error
	CloseAudit(id int, opinion string, curUid int, saveId int) error
	BackAudit(id int, opinion string, curUid int, saveId int, auditId int, progress string) error
	PassAudit(id int, uid int, auditId int, opinion string, rectifiedInfo string) error
	StartAudit(safeId int, bidsectionId int, times int, auditors []int, reAuditors []int, uid int) error
}

type safeAuditService struct {
	validAdd     string
	validPass    string
	validClose   string
	validBack    string
	daoSafeAudit *dao.SafeAuditDao
	daoSafe      *dao.SafeDao
}

//创建项目用户service
func NewSafeAuditService() SafeAuditService {
	return &safeAuditService{
		validBack:    "/api/safe_audit/back",
		validAdd:     "/api/safe_audit/add",
		validClose:   "/api/safe_audit/close",
		validPass:    "/api/safe_audit/pass",
		daoSafeAudit: dao.NewSafeAuditDao(datasource.InstanceDbMaster()),
		daoSafe:      dao.NewSafeDao(datasource.InstanceDbMaster()),
	}
}

// 增加审批人
func (s *safeAuditService) AddAuditor(safeId int, bId int, auditId int, times int) error {
	err := s.daoSafeAudit.AddAuditor(safeId, bId, auditId, times)
	return err
}

// 关闭审批流程
func (s *safeAuditService) CloseAudit(id int, opinion string, curUid int, saveId int) error {
	auditor, err := s.daoSafeAudit.FindById(id)
	if err != nil {
		return err
	}
	if auditor.AuditId != curUid {
		return errors.New("该用户没有审批权限!")
	}
	// 更改cm_safe_audit的记录
	err = s.daoSafeAudit.ChangeStatusById(id, opinion, 3, "")
	if err != nil {
		return err
	}
	// 更改cm_safe的记录
	err = s.daoSafe.ChangeStatus(saveId, 3, auditor.Times)
	if err != nil {
		return err
	}
	return nil
}

// 审批退回
func (s *safeAuditService) BackAudit(id int, opinion string, curUid int, saveId int, auditId int, progress string) error {
	auditor, err := s.daoSafeAudit.FindById(id)
	if err != nil {
		return err
	}
	if auditor.AuditId != curUid {
		return errors.New("该用户没有审批权限!")
	}
	// 更改cm_safe_audit的记录
	err = s.daoSafeAudit.ChangeStatusById(id, opinion, 2, "")
	if err != nil {
		return err
	}

	safeData := s.daoSafe.FindById(saveId)
	// 拷贝审批流程
	// 退回检查人-uncheck
	// 整改人审批退回-checking
	// 复查人审批退回-checkNo
	// 审批组退回-checked
	err = s.daoSafeAudit.CopyAuditors(saveId, safeData.Times, progress, auditId)
	if err != nil {
		return err
	}
	// 更改cm_safe的记录
	err = s.daoSafe.ChangeStatus(saveId, 2, auditor.Times+1)
	if err != nil {
		return err
	}
	return nil
}

// 审批通过
func (s *safeAuditService) PassAudit(id int, uid int, auditId int, opinion string, rectifiedInfo string) error {
	auditor, err := s.daoSafeAudit.FindById(id)
	if err != nil {
		return err
	}
	if auditor.AuditId != uid {
		return errors.New("该用户没有审批权限!")
	}
	if auditId != 0 {
		// 审批人选择了整改人
		err := s.daoSafeAudit.ChangeStatusById(auditor.Id, "", 1, rectifiedInfo)
		if err != nil {
			return err
		}
		err = s.daoSafeAudit.AddCheckWorker(id, auditId, opinion)
		if err != nil {
			return err
		}
	} else {
		err := s.daoSafeAudit.ChangeStatusById(auditor.Id, "", 1, rectifiedInfo)
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *safeAuditService) StartAudit(safeId int, bidsectionId int, times int, auditors []int, reAuditors []int, uid int) error {
	safe := s.daoSafe.FindById(safeId)
	if safe.Uid != uid {
		return errors.New("该用户没有操作权限!")
	}
	data := make([]models.CmSafeAudit, 0)
	for i, item := range auditors {
		auditVM := models.CmSafeAudit{}
		auditVM.AuditId = item
		auditVM.BidsectionId = bidsectionId
		auditVM.SafeId = safeId
		auditVM.AuditOrder = i + 1
		auditVM.CreateTime = time.Now()
		auditVM.Progress = 0
		auditVM.Status = 0
		auditVM.Times = times
		data = append(data, auditVM)
	}
	for i, item := range reAuditors {
		auditVM := models.CmSafeAudit{}
		auditVM.AuditId = item
		auditVM.BidsectionId = bidsectionId
		auditVM.SafeId = safeId
		auditVM.AuditOrder = i + 2 + len(auditors)
		auditVM.CreateTime = time.Now()
		auditVM.Progress = 2
		auditVM.Status = 0
		auditVM.Times = times
		data = append(data, auditVM)
	}
	err := s.daoSafeAudit.InsertData(data)
	if err != nil {
		return err
	}
	err = s.daoSafe.ChangeStatus(safeId, 1, times)
	if err != nil {
		return err
	}
	return nil
}

// 规则校验
func (s *safeAuditService) ValidRule(ctx iris.Context) (viewmodels.SafeAudit, error) {
	safeAuditVaild := viewmodels.SafeAudit{}
	if ctx.Method() == "POST" {
		err := ctx.ReadJSON(&safeAuditVaild)
		if err != nil {
			log.Println("safe-ValidRule-ReadJson转换异常, error=", err)
			return safeAuditVaild, err
		}
		if ctx.Path() == s.validAdd {
			err = safeAuditVaild.ValidateAddAuditor()
			return safeAuditVaild, err
		} else if ctx.Path() == s.validClose {
			err = safeAuditVaild.ValidateClose()
			return safeAuditVaild, err
		} else if ctx.Path() == s.validBack {
			err = safeAuditVaild.ValidateBack()
			return safeAuditVaild, err
		} else if ctx.Path() == s.validPass {
			err = safeAuditVaild.ValidatePass()
			return safeAuditVaild, err
		}
		return safeAuditVaild, err
	}
	return safeAuditVaild, nil
}

// 校验审批开始
func (s *safeAuditService) ValidStart(ctx iris.Context) (viewmodels.AuditStart, error) {
	startAuditValid := viewmodels.AuditStart{}
	err := ctx.ReadJSON(&startAuditValid)
	if err != nil {
		log.Println("safe-ValidRule-ReadJson转换异常, error=", err)
		return startAuditValid, err
	}
	err = startAuditValid.ValidateStart()
	return startAuditValid, err
}
