/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.community.accessrecord.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springblade.common.Constants;
import org.springblade.community.accessrecord.entity.AccessRecord;
import org.springblade.community.accessrecord.vo.AccessRecordVO;
import org.springblade.community.accessrecord.mapper.AccessRecordMapper;
import org.springblade.community.accessrecord.service.IAccessRecordService;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.enterprise.entity.Enterprise;
import org.springblade.community.enterprise.service.IEnterpriseService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.staff.entity.EnterpriseStaff;
import org.springblade.community.staff.service.IEnterpriseStaffService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.estate.guest.entity.Guest;
import org.springblade.estate.guest.service.IGuestService;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-01-14
 */
@Service
public class AccessRecordServiceImpl extends BaseServiceImpl<AccessRecordMapper, AccessRecord> implements IAccessRecordService {

	@Autowired
	private IAgencyService agencyService;
	@Autowired
	private IResidentialService residentialService;
	@Autowired
	private IEnterpriseService enterpriseService;
	@Autowired
	private IEnterpriseStaffService staffService;
	@Autowired
	private IFaceDeviceService faceDeviceService;
	@Autowired
	private IGuestService guestService;

	@Override
	public IPage<AccessRecordVO> selectAccessRecordPage(IPage<AccessRecordVO> page, AccessRecordVO accessRecord) {
		return page.setRecords(baseMapper.selectAccessRecordPage(page, accessRecord));
	}

	@Override
	public AccessRecord getByCommandSeq(String serialNum, String commandSeq) {
		LambdaUpdateWrapper<AccessRecord> lambda = new LambdaUpdateWrapper<>();
		lambda.eq(AccessRecord::getDeviceMac, serialNum);
		lambda.eq(AccessRecord::getCommandSeq, commandSeq);
		return baseMapper.selectOne(lambda);
	}

	@Override
	public R generateAccessRecord(String serialNum, Long userId, String userFace, Integer userType, Integer openType,
								  Integer openSuccess, String failReason, String commandSeq, String temperature, Date openDate) {
		Agency agency = null;
		Residential residential = null;
		Enterprise enterprise = null;
		Long enterpriseId = null;
		String enterpriseName = null;
		String userName = null;
		FaceDevice faceDevice = faceDeviceService.selectByMacAddress(serialNum);
		if(userType.intValue() == Constants.UserType.STAFF.getType()){
			EnterpriseStaff staff = staffService.getById(userId);
			Assert.notNull(staff, "企业员工不存在");
			agency = agencyService.getById(staff.getAgencyId());
			residential = residentialService.getById(staff.getResidentialId());
			enterprise = enterpriseService.getById(staff.getEnterpriseId());
			enterpriseId = enterprise.getId();
			enterpriseName = enterprise.getEnterpriseName();
			faceDevice = faceDeviceService.selectByMacAddress(serialNum);
			userName = staff.getRealName();
		}else if(userType.intValue() == Constants.UserType.GUEST.getType()){
			Guest guest = guestService.getById(userId);
			Assert.notNull(guest, "访客记录不存在");
			agency = agencyService.getById(guest.getAgencyId());
			residential = residentialService.getById(guest.getResidentialId());
			enterprise = enterpriseService.getById(guest.getEnterpriseId());
			enterpriseId = enterprise.getId();
			enterpriseName = enterprise.getEnterpriseName();
			userName = guest.getGuestName();
		}else if(userType.intValue() == Constants.UserType.ADMIN.getType()){
			agency = agencyService.getById(faceDevice.getAgencyId());
			residential = residentialService.getById(faceDevice.getResidentialId());
			BladeUser user = AuthUtil.getUser();
			if(user != null){
				userName = user.getUserName();
			}
		}
		AccessRecord record = new AccessRecord();
		record.setAgencyId(agency.getId());
		record.setAgencyName(agency.getAgencyName());
		record.setResidentialId(residential.getId());
		record.setResidentialName(residential.getName());
		record.setEnterpriseId(enterpriseId);
		record.setEnterpriseName(enterpriseName);
		record.setUserName(userName);
		record.setTenantId(residential.getTenantId());
		record.setFaceUrl(userFace);
		record.setOpenType(String.valueOf(openType));
		record.setOpenSuccess(openSuccess);
		record.setFailReason(failReason);
		record.setDeviceAddress(faceDevice.getAddress());
		record.setDeviceMac(faceDevice.getMacAddress());
		record.setDeviceId(faceDevice.getId());
		record.setOrgPosition(residential.getOrgPosition());
		record.setCommandSeq(commandSeq);
		record.setTemperature(StringUtil.isNoneBlank(temperature) ? new BigDecimal(temperature).compareTo(BigDecimal.ZERO) == 1 ? temperature : null : null);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		record.setOpenTime(sdf.format(openDate));
		return R.status(this.save(record));
	}

}
