package services

import (
	"fmt"
	"log"
	"strconv"
	"time"

	"github.com/kataras/iris/v12"
	"github.com/shopspring/decimal"
	"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

	GetSurvey(projectId int, bidsectionId int) map[string]interface{}
	GetPending(projectId int, projectAccountId int) []viewmodels.Safe
	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
	daoApprover       *dao.ApproverDao
	daoTree           *dao.TreeDao
	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()),
		daoApprover:       dao.NewApproverDao(datasource.InstanceDbMaster()),
		daoTree:           dao.NewTreeDao(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, err := s.daoSafe.FindByCode(data.Code)
	// if err != nil {
	// 	return err
	// }
	// if has {
	// 	return errors.New("该编号已存在!")
	// }
	// _, err = s.daoSafe.InsertRecord(data)
	// if err != nil {
	// 	return err
	// }
	// counts, err := s.daoSafe.GetCountsByBid(data.BidsectionId, data.Status, true)
	// err = s.daoTree.UpdateCounts("safe_total", counts, data.BidsectionId)
	// if err != nil {
	// 	return err
	// }
	// return nil
	err := s.daoSafe.CreateSafe(data)
	return err
}

// delete请求，删除数据
func (s *safeService) Del(id int) error {
	err := s.daoSafe.DeleteRecord(id)
	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)
	uid, _ := comm.AesEncrypt(strconv.Itoa(safeData.Uid), conf.SignSecret)
	data := viewmodels.SafeDetail{}
	data.Id = safeId
	data.BidsectionId = bid
	data.Uid = uid
	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.daoApprover.GetAuditorsWithOwner(safeData.BidsectionId, int(1), safeData.Id, account.Id)
	encryptAuditors := make([]viewmodels.Auditors, 0)
	for _, item := range auditors {
		auditorVM := viewmodels.Auditors{}
		if item.Id != "" {
			id, _ := comm.AesEncrypt(item.Id, conf.SignSecret)
			auditorVM.Id = id
		}
		auditId, _ := comm.AesEncrypt(item.AuditId, conf.SignSecret)
		auditorVM.AuditId = auditId
		auditorVM.Name = item.Name
		auditorVM.Position = item.Position
		auditorVM.Mobile = item.Mobile
		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.daoApprover.GetLastedAuditor(safeData.BidsectionId, 1, safeData.Id)
	data.LatestdAuditor = latestAuditor
	data.Auditors = encryptAuditors

	return data
}

// 安全概况
func (s *safeService) GetSurvey(projectId int, bidsectionId int) map[string]interface{} {
	// 1.获得安全巡检
	year := time.Now().Year()
	safeList := s.daoSafe.GetTypeYear(bidsectionId, year)
	// 2.初始化
	rectifylist := make([]viewmodels.SafeSurveyList, 0)
	rectifyTotal := 0
	approvalTotal := 0
	rectifyedTotal := 0

	columnarData := make([]map[string]interface{}, 0)
	lineData := columnarData
	for i := 1; i <= 12; i++ {
		item := map[string]interface{}{
			"name":  "rectifyed",
			"month": fmt.Sprintf("%d-%02d", year, i),
			"count": 0,
		}
		columnarData = append(columnarData, item)
		item = map[string]interface{}{
			"name":  "submit",
			"month": fmt.Sprintf("%d-%02d", year, i),
			"count": 0,
		}
		columnarData = append(columnarData, item)
		item = map[string]interface{}{
			"month":      fmt.Sprintf("%d-%02d", year, i),
			"percentage": 0,
		}
		lineData = append(lineData, item)

	}

	// 3.当年数据初始化
	submitData := map[string]int{
		fmt.Sprintf("%d-01", year): 0,
		fmt.Sprintf("%d-02", year): 0,
		fmt.Sprintf("%d-03", year): 0,
		fmt.Sprintf("%d-04", year): 0,
		fmt.Sprintf("%d-05", year): 0,
		fmt.Sprintf("%d-06", year): 0,
		fmt.Sprintf("%d-07", year): 0,
		fmt.Sprintf("%d-08", year): 0,
		fmt.Sprintf("%d-09", year): 0,
		fmt.Sprintf("%d-10", year): 0,
		fmt.Sprintf("%d-11", year): 0,
		fmt.Sprintf("%d-12", year): 0,
	}
	rectifyedData := map[string]int{
		fmt.Sprintf("%d-01", year): 0,
		fmt.Sprintf("%d-02", year): 0,
		fmt.Sprintf("%d-03", year): 0,
		fmt.Sprintf("%d-04", year): 0,
		fmt.Sprintf("%d-05", year): 0,
		fmt.Sprintf("%d-06", year): 0,
		fmt.Sprintf("%d-07", year): 0,
		fmt.Sprintf("%d-08", year): 0,
		fmt.Sprintf("%d-09", year): 0,
		fmt.Sprintf("%d-10", year): 0,
		fmt.Sprintf("%d-11", year): 0,
		fmt.Sprintf("%d-12", year): 0,
	}
	for _, item := range safeList {
		if item.Status == 2 {
			id, _ := comm.AesEncrypt(item.Id, conf.SignSecret)
			item.Id = id
			rectifylist = append(rectifylist, item)
			rectifyTotal++
		}
		// if item.Status == 1 {
		// 	approvalTotal++
		// }
		approvalTotal++
		if item.Status == 4 {
			rectifyedTotal++
		}

		// for index, columnar := range columnarData {
		// 	rectifyedCount := 0
		// 	if columnar["month"] == item.CreateTime.Format(conf.SysTimeformMonth) {
		// 		if item.Status == 4 && columnar["name"] == "rectifyed" {
		// 			rectifyedCount++
		// 		}
		// 		columnarData[index]["count"] = columnarData[index]["count"].(int) + 1
		// 		columnarData[index]["count"] = rectifyedCount
		// 		// if item.Status == 0 && columnar["name"] == "submit" {

		// 		// }
		// 	}
		// }
		index := item.CreateTime.Format(conf.SysTimeformMonth)
		submitData[index] = submitData[index] + 1
		// if item.Status == 0 {
		// 	submitData[item.CreateTime.Format(conf.SysTimeformMonth)] = submitData[item.CreateTime.Format(conf.SysTimeformMonth)] + 1
		// }
		if item.Status == 4 {
			rectifyedData[index] = rectifyedData[index] + 1
		}

	}

	for index, columnar := range columnarData {

		if columnar["name"] == "rectifyed" {
			columnarData[index]["count"] = rectifyedData[columnar["month"].(string)]
		}
		if columnar["name"] == "submit" {
			columnarData[index]["count"] = submitData[columnar["month"].(string)]
		}
	}

	for index, line := range lineData {
		rectifyedCount := 0
		submitCount := 0
		for _, columnar := range columnarData {
			if line["month"] == columnar["month"] {
				if columnar["name"] == "rectifyed" {
					rectifyedCount = columnar["count"].(int)
				}
				if columnar["name"] == "submit" {
					submitCount = columnar["count"].(int)
				}
			}
		}
		lineData[index]["percentage"] = 0.00
		if rectifyedCount != 0 && submitCount != 0 {
			decimal.DivisionPrecision = 2
			percentage, _ := decimal.NewFromFloat(float64(rectifyedCount)).Div(decimal.NewFromFloat(float64(submitCount))).Float64()
			lineData[index]["percentage"] = percentage * 100
		}
	}

	// 整改占总数比例 - 完成整改/提交巡检
	surveryData := map[string]interface{}{
		"rectifylist":    rectifylist,
		"rectifyTotal":   rectifyTotal,
		"approvalTotal":  approvalTotal,
		"rectifyedTotal": rectifyedTotal,
		"columnarData":   columnarData,
		"lineData":       lineData,
		// "submitData":     submitData,
		// "rectifyedData":  rectifyedData,
	}

	return surveryData
}

// 获得账号下需要审批的巡检
func (s *safeService) GetPending(projectId int, projectAccountId int) []viewmodels.Safe {

	data := s.daoSafe.GetStatusByProjectAndAccount(projectId, projectAccountId, 1)

	safeList := make([]viewmodels.Safe, 0)
	for _, item := range data {
		safeVM := viewmodels.Safe{}

		Id, _ := comm.AesEncrypt(strconv.Itoa(item.Id), conf.SignSecret)
		BidsectionId, _ := comm.AesEncrypt(strconv.Itoa(item.BidsectionId), conf.SignSecret)
		// AuditId, _ := comm.AesEncrypt(item.AuditId, conf.SignSecret)
		Uid, _ := comm.AesEncrypt(strconv.Itoa(item.Uid), conf.SignSecret)
		// ProjectId, _ := comm.AesEncrypt(strconv.Itoa(item.ProjectId), conf.SignSecret)

		safeVM.Id = Id
		safeVM.BidsectionId = BidsectionId
		safeVM.Uid = Uid
		safeVM.Code = item.Code
		safeVM.CreateTime = item.CreateTime.Format(conf.SysTimeform)
		safeVM.EndTime = item.EndTime.Format(conf.SysTimeform)
		safeVM.Position = item.Position
		safeVM.Inspection = item.Inspection
		safeVM.InspectionDetail = item.InspectionDetail
		safeVM.Demand = item.Demand
		safeVM.Status = item.Status
		safeList = append(safeList, safeVM)
	}

	return safeList
}

// 规则校验
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

}
