package service

import (
	"fmt"
	systemDao "iot_manager_service/app/system/dao"
	systemService "iot_manager_service/app/system/service"
	"iot_manager_service/app/warn/dao"
	"iot_manager_service/app/warn/model"
	"strconv"
	"strings"
)

var NoticeSetService = new(noticeSetService)

type noticeSetService struct{}

func (s noticeSetService) GetList(tenantId string, searchValue string) ([]model.NoticeSetRecords, error) {
	code := dao.ViewsAllCode{TenantId: tenantId}
	deviceTypeGroups, _ := code.GetGroupByDeviceType(searchValue)
	var deviceTypeGroupsNew []model.NoticeSetRecords
	noteiceSets := s.getNoteiceSets(tenantId)
	for _, group := range deviceTypeGroups {
		var deviceNew []model.NoticeSetRecords
		code.DeviceType = group.DeviceType
		devices, _ := code.GetDatasByDeviceType(searchValue)
		for _, device := range devices {
			key := tenantId + strconv.Itoa(3) + strconv.Itoa(device.DeviceType) + strconv.Itoa(device.DeviceId)
			set := noteiceSets[key]
			deviceNew = append(deviceNew, model.NoticeSetRecords{
				Rtype:                   3,
				RtypeName:               device.DeviceName + "(" + device.Sn + ")",
				DeviceType:              device.DeviceType,
				DeviceId:                device.DeviceId,
				ID:                      device.Sn,
				DevUserNoticeModesName:  set.DevUserNoticeModesName,
				BusinessNoticeModesName: set.BusinessNoticeModesName,
				DevUserIdsName:          set.DevUserIdsName,
				BusinessUserIdsName:     set.BusinessUserIdsName,
				DevUserIds:              set.DevUserIds,
				BusinessUserIds:         set.BusinessUserIds,
			})
		}
		key := (tenantId) + strconv.Itoa(2) + strconv.Itoa(group.DeviceType) + strconv.Itoa(999999)
		set := noteiceSets[key]
		deviceTypeGroupsNew = append(deviceTypeGroupsNew, model.NoticeSetRecords{
			Rtype:                   2,
			RtypeName:               group.DeviceTypeName + "(" + strconv.Itoa(len(deviceNew)) + "台)",
			Children:                deviceNew,
			DeviceType:              group.DeviceType,
			DeviceId:                0,
			ID:                      strconv.Itoa(group.DeviceType),
			DevUserNoticeModesName:  set.DevUserNoticeModesName,
			BusinessNoticeModesName: set.BusinessNoticeModesName,
			DevUserIdsName:          set.DevUserIdsName,
			BusinessUserIdsName:     set.BusinessUserIdsName,
			DevUserIds:              set.DevUserIds,
			BusinessUserIds:         set.BusinessUserIds,
		})
	}
	key := tenantId + strconv.Itoa(1) + strconv.Itoa(0) + strconv.Itoa(999999)
	set := noteiceSets[key]
	data := []model.NoticeSetRecords{
		{
			Rtype:                   0,
			RtypeName:               "全部设备",
			Children:                deviceTypeGroupsNew,
			DeviceType:              0,
			DeviceId:                0,
			ID:                      "999999",
			DevUserNoticeModesName:  set.DevUserNoticeModesName,
			BusinessNoticeModesName: set.BusinessNoticeModesName,
			DevUserIdsName:          set.DevUserIdsName,
			BusinessUserIdsName:     set.BusinessUserIdsName,
			DevUserIds:              set.DevUserIds,
			BusinessUserIds:         set.BusinessUserIds,
		},
	}
	return data, nil
}

func (s noticeSetService) Update(post model.NoticeUpdateData, tenantId string) error {
	rtype := post.Rtype
	if rtype == 0 {
		rtype = 1
	}
	deviceId := 999999
	if rtype == 3 {
		deviceId = post.DeviceID
	}
	set := dao.NoticeSet{
		TenantId:                tenantId,
		DeviceType:              post.DeviceType,
		DeviceId:                deviceId,
		DeviceSn:                post.ID,
		RType:                   rtype,
		DevUserNoticeModes:      post.NoticeOperationType,
		BusinessNoticeModes:     post.NoticeBusinessType,
		DevUserNoticeModesName:  post.ShowOperationTypeName,
		BusinessNoticeModesName: post.ShowBusinessTypeName,
		DevUserIds:              post.NoticeOperationMan,
		BusinessUserIds:         post.NoticeBusinessMan,
		DevUserIdsName:          s.getUserName(post.NoticeOperationMan),
		BusinessUserIdsName:     s.getUserName(post.NoticeBusinessMan),
	}
	return set.UpdateOrSave()
}

func (s noticeSetService) getNoteiceSets(tenantId string) map[string]dao.NoticeSet {
	noticeSet := dao.NoticeSet{TenantId: tenantId}
	list, _ := noticeSet.GetList()
	news := make(map[string]dao.NoticeSet)
	for _, set := range list {
		key := set.TenantId + strconv.Itoa(set.RType) + strconv.Itoa(set.DeviceType) + strconv.Itoa(set.DeviceId)
		fmt.Printf("xxxkey = %v", key)
		set.BusinessUserIdsName = strings.ReplaceAll(set.BusinessUserIdsName, " | ", ",")
		set.DevUserIdsName = strings.ReplaceAll(set.DevUserIdsName, " | ", ",")
		news[key] = set
	}
	return news
}

func (s noticeSetService) GetById(id string) (*model.NoticeSetDetail, error) {
	noticeSet := dao.NoticeSet{DeviceSn: id}
	data, err := noticeSet.GetById()
	if err != nil {
		return nil, err
	}
	detail := &model.NoticeSetDetail{
		ID:                  data.DeviceSn,
		RidType:             data.RType,
		NoticeOperationType: data.DevUserNoticeModes,
		NoticeBusinessType:  data.BusinessNoticeModes,
		NoticeOperationMan:  data.DevUserIds,
		NoticeBusinessMan:   data.BusinessUserIds,
	}

	return detail, nil
}

func (s noticeSetService) UserList(account string, name string, current int, size int) ([]model.NoticeSetDUserList, error) {
	var list []model.NoticeSetDUserList
	userList, _, _ := systemService.UserService.List(account, name, current, size)
	for _, user := range userList {
		idStr := strconv.Itoa(int(user.ID))
		list = append(list, model.NoticeSetDUserList{ID: idStr, Name: user.Name})
	}
	return list, nil
}

func (s noticeSetService) getUserName(ids string) string {
	split := strings.Split(ids, ",")
	fm := make(map[string]int)
	for i, v := range split {
		fm[v] = i
	}
	//<<<<<<< HEAD
	userList, _, _ := systemService.UserService.List("", "", 0, 1000)
	//new := []string{}
	//=======
	//userList, _ := systemService.UserService.List("", "", 0, 1000)
	var nameList []string
	//>>>>>>> fdc014add9a1761732ad176375e06591f726e001
	for _, detail := range userList {
		id := strconv.Itoa(int(detail.ID))
		if _, ok := fm[id]; ok {
			nameList = append(nameList, detail.Name)
		}
	}
	return strings.Join(nameList, ",")
}

func (s noticeSetService) Remove(id string, tenantId string) error {
	noticeSet := dao.NoticeSet{DeviceSn: id, TenantId: tenantId}
	return noticeSet.Delete()
}

// GetReceiveList 查出接收人
func (s noticeSetService) GetReceiveList(deviceType int, sn string, armSource int) (map[string]model.ReceiveList, error) {
	list, _ := dao.NoticeSet{}.GetNoticeList(deviceType, sn)
	receives := make(map[string]model.ReceiveList)
	for _, set := range list {
		userIds := set.BusinessUserIds         //接收用户
		noticeModes := set.BusinessNoticeModes //接收的通知方式
		if armSource == 1 {
			userIds = set.DevUserIds
			noticeModes = set.DevUserNoticeModes
		}
		usersArr := strings.Split(userIds, ",")
		noticeModesArr := strings.Split(noticeModes, ",")

		for _, userId := range usersArr {
			var user systemDao.User
			parseInt, _ := strconv.ParseInt(userId, 10, 64)
			user.ID = parseInt
			user.GetUser()
			for _, noticeModeStr := range noticeModesArr {
				noticeModeNum, _ := strconv.ParseInt(noticeModeStr, 10, 64)
				account := user.Email
				if noticeModeStr == "1" {
					account = user.Phone
				}
				receives[userId+noticeModeStr] = model.ReceiveList{
					NoticeSetId:          int(set.ID),
					UserName:             user.Name,
					NoticeMode:           int(noticeModeNum),
					NoticeReceiveAccount: account,
				}
			}
		}
	}
	return receives, nil
}
