/*
 *      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.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.EstateConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.enterprise.entity.Staff;
import org.springblade.enterprise.feign.IStaffClient;
import org.springblade.estate.entity.GuestRecord;
import org.springblade.estate.entity.ServerUser;
import org.springblade.estate.entity.SnapRecord;
import org.springblade.estate.entity.UserAccessPermissions;
import org.springblade.estate.mapper.UserAccessPermissionsMapper;
import org.springblade.estate.service.IGuestRecordService;
import org.springblade.estate.service.IServerUserService;
import org.springblade.estate.service.ISnapRecordService;
import org.springblade.estate.service.IUserAccessPermissionsService;
import org.springblade.estate.vo.UserAccessPermissionsVO;
import org.springblade.estate.vo.UserFacePermissionsStatisticsVO;
import org.springblade.estate.wrapper.UserAccessPermissionsWrapper;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.feign.IHouseUserClient;
import org.springblade.system.feign.ISysClient;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 人脸权限
 *
 * @author cy-computer
 */
@RestController
@AllArgsConstructor
@RequestMapping("/userfacepermissions")
@Api(value = "", tags = "接口")
public class UserFacePermissionsController extends BladeController {

	private final IStaffClient staffClient;
	private final IHouseUserClient houseUserClient;
	private final IUserAccessPermissionsService userAccessPermissionsService;
	private final IGuestRecordService guestRecordService;
	private final IServerUserService serverUserService;
	private final ISnapRecordService snapRecordService;
	private final ISysClient sysClient;

	/**
	 * 【web端】人脸权限 数据统计
	 */
	@GetMapping("/statistics")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入userAccessPermissions")
	public R statistics(@RequestParam Integer tenantType, @RequestParam Integer type) {
		UserFacePermissionsStatisticsVO vo = null;
		if (type.equals(0)) {
			if(tenantType == 0){
				//获取常驻人员的数据统计
				vo = getHouseUserStatisticsVO();
			}else{
				//获取常驻人员的数据统计
				vo = getStaffUserStatisticsVO();
			}
		} else if (type.equals(1)) {
			//获取来访人员的数据统计
			vo = getGuestUserStatisticsVO();
		} else if (type.equals(2)) {
			//获取服务人员的数据统计
			vo = getServerUserStatisticsVO();
		} else if (type.equals(3)) {
			//获取抓拍记录的数据统计
			vo = getSnapStatisticsVO();
		}
		return R.data(vo);
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入userAccessPermissions")
	public R<UserAccessPermissionsVO> detail(UserAccessPermissions userAccessPermissions) {
		UserAccessPermissions detail = userAccessPermissionsService.getOne(Condition.getQueryWrapper(userAccessPermissions));
		return R.data(UserAccessPermissionsWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入userAccessPermissions")
	public R<IPage<UserAccessPermissionsVO>> list(UserAccessPermissions userAccessPermissions, Query query) {
		IPage<UserAccessPermissions> pages = userAccessPermissionsService.page(Condition.getPage(query), Condition.getQueryWrapper(userAccessPermissions));
		return R.data(UserAccessPermissionsWrapper.build().pageVO(pages));
	}

	/**
	 * 【web端】人脸权限==>获取常驻人员的数据统计
	 *
	 * @return
	 */
	private UserFacePermissionsStatisticsVO getStaffUserStatisticsVO() {
		//获取已下发的id列表
		List<Long> ids = userAccessPermissionsService.getUserIdsByUserType(CommonConstant.UserFlag.ENTERPRISE_STAFF_FLAG.getValue());
		//待审核
		Staff staff = new Staff();
		staff.setAuditStatus(CommonConstant.UserAuditStatus.wait.getValue());
		Integer waitCount = staffClient.staffCount(staff);
		//已审核
		staff.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
		Integer passCount = staffClient.staffCount(staff);
		//已下发
		Integer yxfCount = staffClient.yxfCount(ids);
		//待下发【已审核数量-已下发数量】
		int dxfCount = passCount - yxfCount;

		UserFacePermissionsStatisticsVO statisticsVO = UserFacePermissionsStatisticsVO.builder()
			.waitCount(waitCount)
			.passCount(passCount)
			.dxfCount(dxfCount)
			.yxfCount(yxfCount).build();
		return statisticsVO;
	}

	/**
	 * 【web端】人脸权限==>获取常驻人员的数据统计
	 *
	 * @return
	 */
	private UserFacePermissionsStatisticsVO getHouseUserStatisticsVO() {
		//获取已下发的id列表
		List<Long> ids = userAccessPermissionsService.getUserIdsByUserType(CommonConstant.UserFlag.HOUSE_USER_FLAG.getValue());
		//待审核
		HouseUser houseUser = new HouseUser();
		houseUser.setAuditStatus(CommonConstant.UserAuditStatus.wait.getValue());
		Integer waitCount = houseUserClient.houseUserCount(houseUser);
		//已审核
		houseUser.setAuditStatus(CommonConstant.UserAuditStatus.pass.getValue());
		Integer passCount = houseUserClient.houseUserCount(houseUser);
		//已下发
		Integer yxfCount = houseUserClient.yxfCount(ids);
		//待下发【已审核数量-已下发数量】
		int dxfCount = passCount - yxfCount;

		UserFacePermissionsStatisticsVO statisticsVO = UserFacePermissionsStatisticsVO.builder()
			.waitCount(waitCount)
			.passCount(passCount)
			.dxfCount(dxfCount)
			.yxfCount(yxfCount).build();
		return statisticsVO;
	}

	/**
	 * 【web端】人脸权限==>获取拜访人员的数据统计
	 *
	 * @return
	 */
	private UserFacePermissionsStatisticsVO getGuestUserStatisticsVO() {
		//获取已下发的id列表
		List<Long> ids = userAccessPermissionsService.getUserIdsByUserType(CommonConstant.UserFlag.GUEST_FLAG.getValue());
		//待审核
		int waitCount = guestRecordService.count(Condition.getQueryWrapper(new GuestRecord()).lambda()
			.eq(GuestRecord::getAuditStatus, CommonConstant.UserAuditStatus.wait.getValue()));
		//已审核
		int passCount = guestRecordService.count(Condition.getQueryWrapper(new GuestRecord()).lambda()
			.eq(GuestRecord::getAuditStatus, CommonConstant.UserAuditStatus.pass.getValue()));
		//已下发
		int yxfCount = guestRecordService.count(Condition.getQueryWrapper(new GuestRecord()).lambda()
			.in(CollUtil.isNotEmpty(ids), GuestRecord::getId, ids));
		//待下发【已审核数量-已下发数量】
		int dxfCount = passCount - yxfCount;
		UserFacePermissionsStatisticsVO statisticsVO = UserFacePermissionsStatisticsVO.builder()
			.waitCount(waitCount)
			.passCount(passCount)
			.dxfCount(dxfCount)
			.yxfCount(yxfCount).build();
		return statisticsVO;
	}

	/**
	 * 【web端】人脸权限==>获取服务人员的数据统计
	 *
	 * @return
	 */
	private UserFacePermissionsStatisticsVO getServerUserStatisticsVO() {
		//获取已下发的id列表
		List<Long> ids = userAccessPermissionsService.getUserIdsByUserType(CommonConstant.UserFlag.SERVER_USER_FLAG.getValue());
		//获取数据总数
		int totalCount = serverUserService.count();
		//已下发
		int yxfCount = serverUserService.count(Condition.getQueryWrapper(new ServerUser()).lambda()
			.in(ServerUser::getId, ids));
		//待下发【总数-已下发数量】
		int dxfCount = totalCount - yxfCount;

		UserFacePermissionsStatisticsVO statisticsVO = UserFacePermissionsStatisticsVO.builder()
			.totalCount(totalCount)
			.yxfCount(yxfCount)
			.dxfCount(dxfCount)
			.build();
		return statisticsVO;
	}


	/**
	 * 【web端】人脸权限==>获取抓拍记录的数据统计
	 *
	 * @return
	 */
	private UserFacePermissionsStatisticsVO getSnapStatisticsVO() {
		//获取高温临界点
		BigDecimal highTemperature = Convert.toBigDecimal(sysClient.getParamValue(EstateConstant.HIGH_TEMPERATURE_NAME).getData());
		//异常记录("temperature+0"将字符串类型的数据转为数字类型再比较大小)
		List<SnapRecord> list = snapRecordService.list(Condition.getQueryWrapper(new SnapRecord()).ge("temperature+0",highTemperature));
		long totalCount = list.size();
		//今日异常总数
		long todayCount = list.stream().filter(item -> isNow(item.getCreateTime())).count();

		return UserFacePermissionsStatisticsVO.builder()
			.totalCount(Convert.toInt(totalCount))
			.todayCount(Convert.toInt(todayCount))
			.build();
	}

	private Boolean isNow(Date date) {
		String format = "yyyy-MM-dd";
		String now = DateUtil.format(new Date(), format);
		String createTime = DateUtil.format(date, format);
		return now.equals(createTime);
	}
}
