package service

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"sws_xcx/models"
	"sws_xcx/utils"

	"github.com/jinzhu/gorm"
)

type CheckRecordService struct {
	rdb *gorm.DB
	wdb *gorm.DB
}

func NewCheckRecordService() *CheckRecordService {
	return &CheckRecordService{
		rdb: ReadDB(),
		wdb: WriteDB(),
	}
}

func (s *CheckRecordService) GetCheckRecordByAcc(deviceId uint64, acc int) (record models.CheckRecord, err error) {
	record = models.CheckRecord{}
	err = s.rdb.Model(&record).Where("device_id = ? and acc = ?", deviceId, acc).First(&record).Error
	if err != nil && err == gorm.ErrRecordNotFound {
		err = nil
	}

	return
}

func (s *CheckRecordService) GetCheckRecordList(pageNum, pageSize int, userid uint64) (vos []models.AppCheckRecordVO, total int, err error) {
	offset := (pageNum - 1) * pageSize
	records := make([]*models.CheckRecord, pageSize)
	err = s.rdb.Model(&models.CheckRecord{}).Where("user_id= ? and delete_flag = ?", userid, 0).Count(&total).Order("id desc").Offset(offset).Limit(pageSize).Find(&records).Error
	if len(records) > 0 {
		is := NewCheckItemService()
		cnItems, err1 := is.GetCheckItems("cn", "1")
		if err1 != nil {
			utils.ErrorLog("GetCheckItems err：%v ", err1)
		}
		mcn := make(map[int]models.CheckItem, len(cnItems))
		for _, item := range cnItems {
			mcn[item.Id] = *item
		}

		vos = make([]models.AppCheckRecordVO, len(records))
		for i, r := range records {
			vo := models.AppCheckRecordVO{}
			vo.CheckRecordId = r.Id
			vo.UserId = r.UserId
			if r.UserId > 0 {
				vo.Bind = 1
			}
			vo.CheckDate = models.Time(r.Ctime)
			vo.View = r.View
			vo.AlertCount = 0
			//vo.AlertGrade = 0

			if r.AlertItemIds != "" {
				ids := strings.Split(r.AlertItemIds, ",")
				names := make([]string, len(ids))
				for j, id := range ids {

					ii, _ := strconv.Atoi(id)
					if item, ok := mcn[ii]; ok {
						names[j] = item.NameCn
					}

				}
				vo.AlertItems = names
				vo.AlertCount = len(ids)
			}
			vo.NormalCount = len(cnItems) - vo.AlertCount

			vos[i] = vo
		}

	}

	return
}

func (s *CheckRecordService) GetCheckRecordItemReport(dataNum, itemNum int, userid uint64) (reports []*models.AppCheckRecordItemReportVO, err error) {

	item, err := NewCheckItemService().GetCheckItemByNumber(itemNum, "cn", "1")
	if err != nil {
		return
	}
	if item.Id == 0 {
		err = fmt.Errorf("系统无此检查项目 num:%v", itemNum)
		return
	}

	var items []*models.CheckRecordItem

	err = s.rdb.Raw("select i.* from  check_record_item as i inner join check_record as c on i.check_id=c.id where i.check_item_id = ? and c.user_id = ? and c.delete_flag=0", item.Id, userid).Order("id desc").Limit(dataNum).Scan(&items).Error

	if len(items) > 0 {
		var scopes []*models.CheckItemScopeVO
		json.Unmarshal([]byte(item.ScopeList), &scopes)
		reports = make([]*models.AppCheckRecordItemReportVO, len(items))
		for i, ci := range items {
			report := models.AppCheckRecordItemReportVO{}
			report.ID = item.CheckItemNumber
			report.CheckValueIndex = ci.CheckValueIndex
			report.Unit = item.Unit
			report.Date = models.Time(ci.Ctime)
			for _, scope := range scopes {
				if scope.Index == ci.CheckValueIndex {
					if scope.Num != "" {
						report.Value = scope.Num
					} else {
						report.Value = scope.Value
					}
				}
			}
			reports[i] = &report
		}
	}

	return
}

func (s *CheckRecordService) CreateCheckRecord(checkRecord *models.CheckRecord) error {
	return s.wdb.Model(checkRecord).Create(checkRecord).Error
}

func (s *CheckRecordService) CreateCheckRecordItem(checkRecordItem *models.CheckRecordItem) error {
	return s.wdb.Model(checkRecordItem).Create(checkRecordItem).Error
}

func (s *CheckRecordService) UpdateCheckRecordAlertItems(id int64, alertItemIds string) error {
	return s.wdb.Model(&models.CheckRecord{}).Where("id = ?", id).Update("alert_item_ids", alertItemIds).Error
}

func (s *CheckRecordService) GetCheckRecordItems(recordId int64) (recordItems []*models.CheckRecordItem, err error) {
	err = s.rdb.Model(&models.CheckRecordItem{}).Where("check_id = ?", recordId).Find(&recordItems).Error
	return
}

func (s *CheckRecordService) GetCheckRecordById(id int64) (record models.CheckRecord, err error) {

	err = s.rdb.Model(&record).Where("id = ?", id).First(&record).Error
	return
}
