package services

import (
	"errors"
	"log"
	"strconv"

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

type SafeService interface {
	Get(id int, pid int, pageNo int, pageSize int) ([]viewmodels.SafeList, int64)
	Post(data models.CmSafe) error
	Del(id int) error
	GetDetail(id int, pid int) viewmodels.SafeDetail
	ValidRule(ctx iris.Context) (viewmodels.Safe, error)
}

// //返回service操作类
type safeService struct {
	daoSafe           *dao.SafeDao
	daoSafeAudit      *dao.SafeAuditDao
	daoProjectAccount *dao.ProjectAccountDao
	daoAnnex          *dao.AnnexDao
	daoRule           *dao.RuleDao
	validDetail       string
}

//创建项目用户service
func NewSafeService() SafeService {
	return &safeService{
		validDetail:       "/api/safe/detail",
		daoSafe:           dao.NewSafeDao(datasource.InstanceDbMaster()),
		daoAnnex:          dao.NewAnnexDao(datasource.InstanceDbMaster()),
		daoSafeAudit:      dao.NewSafeAuditDao(datasource.InstanceDbMaster()),
		daoProjectAccount: dao.NewProjectAccountDao(datasource.InstanceDbMaster()),
	}
}
func (s *safeService) Get(id int, pid int, pageNo int, pageSize int) ([]viewmodels.SafeList, int64) {
	datalist, total := s.daoSafe.GetListByBid(id, pageNo, pageSize)
	safeList := make([]viewmodels.SafeList, 0)
	for _, item := range datalist {
		safeVM := viewmodels.SafeList{}
		safeVM.Code = item.Code
		account := s.daoProjectAccount.Get(item.Uid, pid)
		safeVM.AuditName = account.Name
		safeVM.CreateTime = item.CreateTime.Format(conf.SysTimeform)
		safeVM.Demand = item.Demand
		id, _ := comm.AesEncrypt(strconv.Itoa(item.Id), conf.SignSecret)
		safeVM.Id = id
		safeVM.Inspection = item.Inspection
		safeVM.InspectionDetail = item.InspectionDetail
		safeVM.Position = item.Position
		safeVM.Status = item.Status
		counts, _ := s.daoAnnex.GetCount(3, item.Id)
		safeVM.FileCounts = counts
		safeList = append(safeList, safeVM)
	}
	return safeList, total
}

// post请求，插入单条数据
func (s *safeService) Post(data models.CmSafe) error {
	has := s.daoSafe.FindByCode(data.Code)
	if has {
		return errors.New("该编号已存在!")
	}
	Inserted, err := s.daoSafe.InsertRecord(data)
	if Inserted == true {
		return nil
	}
	return err
}

// delete请求，删除数据
func (s *safeService) Del(id int) error {
	Deleted, err := s.daoSafe.DeleteRecord(id)
	if Deleted == true {
		return nil
	}
	return err
}

// 详情页数据拼装
func (s *safeService) GetDetail(id int, pid int) viewmodels.SafeDetail {

	safeData := s.daoSafe.FindById(id)
	// fmt.Println(safeData)
	safeId, _ := comm.AesEncrypt(strconv.Itoa(safeData.Id), conf.SignSecret)
	bid, _ := comm.AesEncrypt(strconv.Itoa(safeData.BidsectionId), conf.SignSecret)
	data := viewmodels.SafeDetail{}
	data.Id = string(safeId)
	data.BidsectionId = string(bid)
	data.Code = safeData.Code
	data.Inspection = safeData.Inspection
	data.InspectionDetail = safeData.InspectionDetail
	data.Demand = safeData.Demand
	account := s.daoProjectAccount.Get(safeData.Uid, pid)
	data.AuditName = account.Name
	data.CreateTime = safeData.CreateTime
	data.Times = safeData.Times
	data.Status = safeData.Status
	fileList, total := s.daoAnnex.GetList(3, safeData.Id, 1, conf.PageSize)
	// 加密id
	fileArr := make([]viewmodels.AnnexListView, 0)
	for _, item := range fileList {
		fileListVM := viewmodels.AnnexListView{}
		fileId, _ := comm.AesEncrypt(item.Id, conf.SignSecret)
		fileListVM.Id = fileId
		uid, _ := comm.AesEncrypt(item.AccountId, conf.SignSecret)
		fileListVM.AccountId = uid
		fileListVM.AccountName = item.AccountName
		fileListVM.CreateTime = item.CreateTime
		fileListVM.FileName = item.FileName
		fileListVM.FilePath = item.FilePath
		fileArr = append(fileArr, fileListVM)
	}
	fileVM := viewmodels.FileStruct{}
	fileVM.FileList = fileArr
	fileVM.Total = total
	data.File = fileVM
	auditors := s.daoSafeAudit.GetAuditorsWithOwner(safeData.Id, safeData.Times, account.Id)
	encryptAuditors := make([]viewmodels.Auditors, 0)
	for _, item := range auditors {
		auditorVM := viewmodels.Auditors{}
		auditorId, _ := comm.AesEncrypt(item.AuditorId, conf.SignSecret)
		auditId, _ := comm.AesEncrypt(item.AuditId, conf.SignSecret)
		auditorVM.AuditorId = auditorId
		auditorVM.AuditId = auditId
		auditorVM.Name = item.Name
		auditorVM.Position = item.Position
		auditorVM.AuditOrder = item.AuditOrder
		auditorVM.AccountGroup = item.AccountGroup
		auditorVM.Progress = item.Progress
		auditorVM.Company = item.Company
		auditorVM.Status = item.Status
		encryptAuditors = append(encryptAuditors, auditorVM)
	}
	auditHistory := s.daoSafeAudit.GetAuditHistory(safeData.Id, safeData.Times)
	data.AuditHistory = auditHistory
	rectifiedInfo, _ := s.daoSafeAudit.GetLastedOrder(safeData.Id)
	data.RectifiedInfo = rectifiedInfo

	latestAuditor, _ := s.daoSafeAudit.GetLastedAuditor(safeData.Times, safeData.Id)
	data.LatestdAuditor = latestAuditor
	data.Auditors = encryptAuditors

	return data
}

// 规则校验
func (s *safeService) ValidRule(ctx iris.Context) (viewmodels.Safe, error) {
	safeVaild := viewmodels.Safe{}
	// fmt.Println("---------------------------safeVaild", safeVaild)
	if ctx.Method() == "GET" {
		err := ctx.ReadForm(&safeVaild)
		if err != nil {
			log.Println("safe-ValidRule-ReadForm转换异常, error=", err)
			return safeVaild, err
		}
		if ctx.Path() == s.validDetail {
			// 一样要传id，所以用delete的方法判断
			err = safeVaild.ValidateDelete()
		} else {
			err = safeVaild.ValidateList()
		}
		return safeVaild, err
	}

	if ctx.Method() == "POST" {
		err := ctx.ReadJSON(&safeVaild)
		if err != nil {
			log.Println("safe-ValidRule-ReadJson转换异常, error=", err)
			return safeVaild, err
		}
		err = safeVaild.ValidateCreate()
		return safeVaild, err
		// if ctx.Path() == s.validCreate {
		// }
		// if ctx.Path() == s.validFile {
		// 	err = safeVaild.ValidateFile()
		// 	return safeVaild, err
		// }
	}

	if ctx.Method() == "PUT" {
		err := ctx.ReadForm(&safeVaild)
		if err != nil {
			log.Println("safe-ValidRule-ReadForm转换异常, error=", err)
			return safeVaild, err
		}
		err = safeVaild.ValidateDelete()
		return safeVaild, err
	}
	return safeVaild, nil

}
