/*
 *      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.estate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.CommonConstant;
import org.springblade.community.entity.*;
import org.springblade.community.feign.*;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.device.entity.DoorDevice;
import org.springblade.device.feign.IDoorDeviceClient;
import org.springblade.enterprise.entity.Enterprise;
import org.springblade.enterprise.entity.Staff;
import org.springblade.enterprise.feign.IEnterpriseClient;
import org.springblade.enterprise.feign.IStaffClient;
import org.springblade.estate.entity.AuthorizeRecords;
import org.springblade.estate.entity.GuestRecord;
import org.springblade.estate.entity.ServerUser;
import org.springblade.estate.service.IGuestRecordService;
import org.springblade.estate.service.IServerUserService;
import org.springblade.estate.vo.AuthorizeRecordsVO;
import org.springblade.estate.mapper.AuthorizeRecordsMapper;
import org.springblade.estate.service.IAuthorizeRecordsService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.List;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2022-01-06
 */
@Service
@Slf4j
public class AuthorizeRecordsServiceImpl extends BaseServiceImpl<AuthorizeRecordsMapper, AuthorizeRecords> implements IAuthorizeRecordsService {

	@Autowired
	private IAgencyClient agencyClient;
	@Autowired
	private IResidentialClient residentialClient;
	@Autowired
	private IBuildingClient buildingClient;
	@Autowired
	private IUnitClient unitClient;
	@Autowired
	private IRoomClient roomClient;
	@Autowired
	private IEnterpriseClient enterpriseClient;
	@Autowired
	private IDoorDeviceClient doorDeviceClient;

	@Override
	public IPage<AuthorizeRecordsVO> selectAuthorizeRecordsPage(IPage<AuthorizeRecordsVO> page, AuthorizeRecordsVO authorizeRecords) {
		return page.setRecords(baseMapper.selectAuthorizeRecordsPage(page, authorizeRecords));
	}

	@Override
	public R generateAuthRecord(String serialNum, String userId, String userName, String userType, String authNo, String authCmd, String reqData, Integer smartDeviceType, String respMsg, String tenantId) {
		if(StringUtil.isBlank(serialNum) || StringUtil.isBlank(userId) || StringUtil.isBlank(reqData) || smartDeviceType == null){
			log.error("==============授权记录设备序列号|用户ID|请求数据不能为空===============");
		}
		AuthorizeRecords authRecord = new AuthorizeRecords();
		authRecord.setDeviceSerialNum(serialNum);
		authRecord.setAuthReqData(reqData);
		authRecord.setAuthReqNo(authNo);
		authRecord.setAuthCmd(authCmd);
		authRecord.setAuthStatus(CommonConstant.AuthStatus.WAIT.getValue());
		authRecord.setAuthRespMsg(respMsg);
		String deviceName = null;
		String deviceAddress = null;
		String agencyName = null;
		String residentialName = null;
		String buildingName = null;
		String unitName = null;
		String roomName = null;
		String enterpriseName = null;
		Long agencyId = null;
		Long residentialId = null;
		Long buildingId = null;
		Long unitId = null;
		Long roomId = null;
		Long enterpriseId = null;
		try{
			if(smartDeviceType.intValue() == CommonConstant.SmartDeviceType.DOOR_DEVICE.getValue()){
				DoorDevice doorDevice = doorDeviceClient.getBySerialNum(serialNum);
				deviceName = doorDevice.getName();
				deviceAddress = doorDevice.getAddress();
				Agency agency = agencyClient.getById(doorDevice.getAgencyId());
				agencyId = doorDevice.getAgencyId();
				agencyName = agency.getName();
				if(doorDevice.getResidentialId() != null){
					Residential residential = residentialClient.getById(doorDevice.getResidentialId());
					residentialId = doorDevice.getResidentialId();
					residentialName = residential.getName();
				}
				if(doorDevice.getBuildingId() != null){
					Building building = buildingClient.getById(doorDevice.getBuildingId());
					buildingId = doorDevice.getBuildingId();
					buildingName = building.getName();
				}
				if(doorDevice.getUnitId() != null){
					Unit unit = unitClient.getById(doorDevice.getUnitId());
					unitId = doorDevice.getUnitId();
					unitName = unit.getName();
				}
				if(doorDevice.getRoomId() != null){
					Room room = roomClient.getById(doorDevice.getRoomId());
					roomId = doorDevice.getRoomId();
					roomName = room.getName();
				}
				if(doorDevice.getEnterpriseId() != null){
					Enterprise enterprise = enterpriseClient.getById(doorDevice.getEnterpriseId());
					enterpriseId = enterprise.getId();
					enterpriseName = enterprise.getEnterpriseName();
				}
			}else if(smartDeviceType.intValue() == CommonConstant.SmartDeviceType.MONITOR_DEVICE.getValue()){

			}else if(smartDeviceType.intValue() == CommonConstant.SmartDeviceType.PARKING_DEVICE.getValue()){

			}
			authRecord.setDeviceName(deviceName);
			authRecord.setDeviceAddress(deviceAddress);
			authRecord.setAgencyName(agencyName);
			authRecord.setResidentialName(residentialName);
			authRecord.setBuildingName(buildingName);
			authRecord.setUnitName(unitName);
			authRecord.setRoomName(roomName);
			authRecord.setEnterpriseName(enterpriseName);
			authRecord.setAgencyId(agencyId);
			authRecord.setResidentialId(residentialId);
			authRecord.setBuildingId(buildingId);
			authRecord.setUnitId(unitId);
			authRecord.setRoomId(roomId);
			authRecord.setEnterpriseId(enterpriseId);

			authRecord.setUserId(userId);
			authRecord.setUserName(userName);
			authRecord.setUserType(userType);
//			authRecord.setTenantId(tenantId);
			return R.status(this.save(authRecord));
		}catch (Exception e){
			log.error(reqData);
			e.printStackTrace();
			authRecord.setAuthStatus(CommonConstant.AuthStatus.FAIL.getValue());
			authRecord.setAuthRespMsg(e.getMessage());
			this.save(authRecord);
			return R.status(this.save(authRecord));
		}
	}

	@Override
	public List<AuthorizeRecords> getAuthRecord(String serialNum, String authReqNo, String authCmd) {
		LambdaQueryWrapper<AuthorizeRecords> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(AuthorizeRecords::getDeviceSerialNum, serialNum);
		lambdaQueryWrapper.eq(AuthorizeRecords::getAuthReqNo, authReqNo);
		lambdaQueryWrapper.eq(StringUtil.isNotBlank(authCmd), AuthorizeRecords::getAuthCmd, authCmd);
		lambdaQueryWrapper.orderByDesc(AuthorizeRecords::getCreateTime);
		return this.list(lambdaQueryWrapper);
	}

}
