/*
 *      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 com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.common.constant.CommonConstant;
import org.springblade.community.entity.Agency;
import org.springblade.community.entity.Residential;
import org.springblade.community.feign.IAgencyClient;
import org.springblade.community.feign.IResidentialClient;
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.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.enterprise.entity.Staff;
import org.springblade.estate.entity.AccessRecord;
import org.springblade.estate.feign.IUserAccessPermissionsClient;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springblade.system.expand.util.QueryWrapperUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.enterprise.entity.Enterprise;
import org.springblade.enterprise.feign.IEnterpriseClient;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.estate.entity.GuestRecord;
import org.springblade.estate.vo.GuestRecordVO;
import org.springblade.estate.wrapper.GuestRecordWrapper;
import org.springblade.estate.service.IGuestRecordService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.*;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-03-30
 */
@RestController
@AllArgsConstructor
@RequestMapping("/guestrecord")
@Api(value = "", tags = "接口")
public class GuestRecordController extends BladeController {

	private final IGuestRecordService guestRecordService;
	private final IAgencyClient agencyClient;
	private final IResidentialClient residentialClient;
	private final IEnterpriseClient enterpriseClient;
	private final IConfClient confClient;
	private final IUserAccessPermissionsClient userAccessPermissionsClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入guest")
	public R<GuestRecordVO> detail(GuestRecord guestRecord) {
		GuestRecord detail = guestRecordService.getOne(Condition.getQueryWrapper(guestRecord));
		return R.data(GuestRecordWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入guest")
	public R<IPage<GuestRecordVO>> list(@RequestParam Map<String, Object> guestRecord, Query query, BladeUser bladeUser) {
		QueryWrapper<GuestRecord> queryWrapper = Condition.getQueryWrapper(guestRecord, GuestRecord.class);
		queryWrapper.lambda().orderByDesc(GuestRecord::getCreateTime);
		IPage<GuestRecord> pages = guestRecordService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(GuestRecord::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(GuestRecordWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入guest")
	public R<IPage<GuestRecordVO>> page(GuestRecordVO guest, Query query) {
		IPage<GuestRecordVO> pages = guestRecordService.selectGuestPage(Condition.getPage(query), guest);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入guest")
	public R save(@Valid @RequestBody GuestRecord guestRecord) {
		if(StringUtil.isNotBlank(guestRecord.getFaceUrl())){
			guestRecord.setFaceUrl(confClient.removePrefix(guestRecord.getFaceUrl()));
		}
		guestRecord.setAuditStatus(1);
		boolean save = guestRecordService.save(guestRecord);
		if(save){
			if(guestRecord.getAuditStatus() == 1 && StringUtil.isNotBlank(guestRecord.getFaceUrl())){
				R result = this.guestRecordService.pushFace(guestRecord.getId());
				return result;
			}
		}
		return R.status(save);
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入guest")
	public R update(@Valid @RequestBody GuestRecord guestRecord) {
		if(StringUtil.isNotBlank(guestRecord.getFaceUrl())){
			guestRecord.setFaceUrl(confClient.removePrefix(guestRecord.getFaceUrl()));
		}
		guestRecordService.updateById(guestRecord);
		if(guestRecord.getAuditStatus() == 1){
			guestRecordService.pushFace(guestRecord.getId());
		}else if(guestRecord.getAuditStatus() == 2) {
			guestRecordService.deleteFace(guestRecord.getId());
		}
		return R.status(true);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入guest")
	public R submit(@Valid @RequestBody GuestRecord guestRecord) {
		return R.status(guestRecordService.saveOrUpdate(guestRecord));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		for(Long id : idList){
			return this.guestRecordService.deleteGuestRecord(id);
		}
		return R.status(true);
	}


	/**
	 * 申请
	 */
	@PostMapping("/application")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "申请", notes = "guest")
	public R application(@Valid @RequestBody GuestRecord guest, BladeUser bladeUser) {
		//用企业id判断访问的是企业还是园区
		if (guest.getEnterpriseId() != null) {
			Enterprise enterprise = this.enterpriseClient.getById(guest.getEnterpriseId());
			Assert.notNull(enterprise, "选择的企业不存在");
			guest.setEnterpriseName(enterprise.getEnterpriseName());
			//区域信息
			Residential residential = this.residentialClient.getById(enterprise.getResidentialId());
			guest.setResidentialId(residential.getId());
			guest.setResidentialName(residential.getName());
			//园区信息
			Agency agency = this.agencyClient.getById(enterprise.getAgencyId());
			guest.setAgencyId(agency.getId());
			guest.setAgencyName(agency.getName());
			guest.setOrgPosition(enterprise.getOrgPosition());
		} else {
			Agency agency = this.agencyClient.getById(guest.getAgencyId());
			Assert.notNull(agency, "选择的园区不存在");
			guest.setAgencyName(agency.getName());
			guest.setOrgPosition(agency.getOrgPosition());
		}
		guest.setTenantId(bladeUser.getTenantId());
		return R.status(guestRecordService.save(guest));
	}

	/**
	 * 审核
	 */
	@PostMapping("/audit")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "审核", notes = "传入guest")
	public R audit(@Valid @RequestBody GuestRecord guestRecord) {
		return this.guestRecordService.audit(guestRecord.getId(), guestRecord.getAuditStatus(), guestRecord.getOpinion());
	}


	/**
	 * 园区小程序访客获取自己的申请记录，无需鉴权
	 */
	@GetMapping("/getByGuestOpenId")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增或修改", notes = "传入guest")
	public R<IPage<GuestRecordVO>> submit(GuestRecord guest,Query query) {
		IPage<GuestRecord> pages = guestRecordService.page(Condition.getPage(query), Condition.getQueryWrapper(guest).lambda().orderByDesc(GuestRecord::getCreateTime));
		return R.data(GuestRecordWrapper.build().pageVO(pages));
	}

	/**
	 * 下发人脸
	 */
	@PostMapping("/pushGuestFace")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "审核", notes = "传入guest")
	public R pushGuestFace(@Valid @RequestBody GuestRecord guestRecord) {
		return this.guestRecordService.pushFace(guestRecord.getId());
	}

	/**
	 * 禁用人脸
	 */
	@PostMapping("/deleteGuestFace")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "审核", notes = "传入guest")
	public R deleteGuestFace(@Valid @RequestBody GuestRecord guestRecord) {
		return this.guestRecordService.deleteFace(guestRecord.getId());
	}

	/**
	 * 当日访客统计，默认是当天
	 */
	@GetMapping("/guestStat")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "当日访客统计", notes = "传入guest")
	public R guestStat(@RequestParam(value = "beginDate", required = false) String beginDate, @RequestParam(value = "endDate", required = false) String endDate) {
		return R.data(this.guestRecordService.guestStat(beginDate, endDate));
	}


	/**
	 * 【web端】一联通-人脸权限-访客人员下发列表
	 * 获取访客人员，下发列表
	 * type:0待下发,1已下发
	 */
	@GetMapping("/getGuestXFList")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "下发列表", notes = "传入staff")
	public R getStaffDXFList(Query query,@RequestParam Integer type) {
		List<Long> userIdList = userAccessPermissionsClient.getUserIdsByUserType(CommonConstant.UserFlag.GUEST_FLAG.getValue());
		LambdaQueryWrapper<GuestRecord> queryWrapper = null;
		if (type.equals(0)) {
			//访客人员待下发列表
			queryWrapper = Condition.getQueryWrapper(new GuestRecord()).lambda().eq(GuestRecord::getAuditStatus,CommonConstant.UserAuditStatus.pass.getValue()).notIn(CollUtil.isNotEmpty(userIdList), GuestRecord::getId,userIdList);
		}else if(type.equals(1)){
			//访客人员已下发列表
			queryWrapper = Condition.getQueryWrapper(new GuestRecord()).lambda().eq(GuestRecord::getAuditStatus,CommonConstant.UserAuditStatus.pass.getValue()).in(CollUtil.isNotEmpty(userIdList), GuestRecord::getId,userIdList);
		}
		IPage<GuestRecord> guestRecordIPage = guestRecordService.page(Condition.getPage(query), queryWrapper);
		return R.data(guestRecordIPage);
	}

}
