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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.lang.Assert;
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.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.enterprise.entity.Enterprise;
import org.springblade.enterprise.service.IEnterpriseService;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.enterprise.service.IUserService;
import org.springblade.estate.entity.GuestRecord;
import org.springblade.estate.feign.IUserAccessPermissionsClient;
import org.springblade.system.expand.feign.IConfClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.enterprise.entity.Staff;
import org.springblade.enterprise.vo.StaffVO;
import org.springblade.enterprise.wrapper.StaffWrapper;
import org.springblade.enterprise.service.IStaffService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

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

	private final IStaffService staffService;
	private final IEnterpriseService enterpriseService;
	private final IUserAccessPermissionsClient userAccessPermissionsClient;
	private final IConfClient confClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入staff")
	public R<StaffVO> detail(Staff staff) {
		Staff detail = staffService.getOne(Condition.getQueryWrapper(staff));
		return R.data(StaffWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入staff")
	public R<IPage<StaffVO>> list(@RequestParam Map<String,Object> staff, Query query) {
		QueryWrapper<Staff> queryWrapper = Condition.getQueryWrapper(staff,Staff.class);
		queryWrapper.lambda().orderByDesc(Staff::getCreateTime);
		IPage<Staff> pages = staffService.page(Condition.getPage(query), queryWrapper);
		return R.data(StaffWrapper.build().pageVO(pages));
	}


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

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入staff")
	public R save(@Valid @RequestBody Staff staff) {
		return R.status(staffService.save(staff));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入staff")
	public R update(@Valid @RequestBody Staff staff) {
		String faceUrl = staff.getFaceUrl();
		if (StrUtil.isNotBlank(faceUrl)) {
			staff.setFaceUrl(confClient.removePrefix(staff.getFaceUrl()));
		}
		return R.status(staffService.updateById(staff));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入staff")
	public R submit(@Valid @RequestBody Staff staff) {
		String faceUrl = staff.getFaceUrl();
		staff.setFaceUrl(confClient.removePrefix(staff.getFaceUrl()));
		if (staff.getEnterpriseId() != null) {
			Enterprise search = new Enterprise();
			search.setId(staff.getEnterpriseId());
			Enterprise enterprise = enterpriseService.getById(search);
			Assert.notNull(enterprise, "找不到所属企业");
			staff.setTenantId(enterprise.getTenantId());
			staff.setResidentialId(enterprise.getResidentialId());
			staff.setAgencyId(enterprise.getAgencyId());
			staff.setEnterpriseName(enterprise.getEnterpriseName());
		}
		if(staff.getId() == null){
			//后台保存,默认审核通过
			staff.setAuditStatus(1);
			boolean save = staffService.save(staff);
			if(save && StrUtil.isNotBlank(faceUrl)){
				this.staffService.pushAddUserFace(staff.getId());
			}
			return R.status(save);
		}else{
			//更新
			boolean update = staffService.updateById(staff);
			return R.status(update);
		}
	}


	/**
	 * 删除
	 */
	@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.staffService.deleteUser(id);
		}
		return R.status(true);
	}

	/**
	 * 园区小程序访客提交访客记录后获取具有审核该记录权限的管理员列表
	 *
	 * @param agencyId 园区id
	 * @param enterpriseId   企业id
	 * @return
	 */
	@GetMapping(value = "/app/getManagerList")
	@ApiOperationSupport(order = 9)
	public R<List<String>> getManagerList(@RequestParam(required = false) Long agencyId,@RequestParam(required = false) String enterpriseId) {
		if(agencyId != null){//获取园区管理员openid集合
			List<Staff> enterpriseStaffs = staffService.getBaseMapper().selectList(new QueryWrapper<>(new Staff()).lambda()
				.eq(Staff::getAgencyId, agencyId)
				.eq(Staff::getIsAgencyManager, 1));
			List<String> openIdList = enterpriseStaffs.stream().map(Staff::getOpenId).collect(Collectors.toList());
			return R.data(openIdList);
		}

		if(enterpriseId != null){
			List<Staff> enterpriseStaffs = staffService.getBaseMapper().selectList(new QueryWrapper<>(new Staff()).lambda()
				.eq(Staff::getEnterpriseId, enterpriseId)
				.eq(Staff::getIsEnterpriseManager, 1));
			List<String> openIdList = enterpriseStaffs.stream().map(Staff::getOpenId).collect(Collectors.toList());
			return R.data(openIdList);
		}
		return  R.data(null);
	}

	/**
	 * 企业员工审核接口
	 */
	@PostMapping("/review")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "企业员工审核接口", notes = "传入staff")
	public R review(@RequestBody Staff enterpriseStaff) {
		boolean review = staffService.review(enterpriseStaff);
		if(review){
			if(StringUtil.isNotBlank(enterpriseStaff.getFaceUrl())){
				return this.staffService.pushAddUserFace(enterpriseStaff.getId());
			}else{
				return R.success("审核成功");
			}
		}else{
			return R.fail("审核失败");
		}
	}

	/**
	 * 新增下发员工人脸到设备
	 */
	@PostMapping("/pushUserFace")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "新增下发员工人脸到设备", notes = "传入staff")
	public R pushFace(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		for(Long id : idList){
			return this.staffService.pushAddUserFace(id);
		}
		return R.status(true);
	}

	/**
	 * 更新下发员工人脸到设备
	 */
	@PostMapping("/pushUpdateUserFace")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "更新下发员工人脸到设备", notes = "传入staff")
	public R pushUpdateUserFace(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		for(Long id : idList){
			return this.staffService.pushUpdateUserFace(id);
		}
		return R.status(true);
	}

	/**
	 * 下发删除员工人脸指令到设备
	 */
	@PostMapping("/deleteUserFace")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "下发删除员工人脸指令到设备", notes = "传入staff")
	public R deleteUserFace(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		for(Long id : idList){
			return this.staffService.deleteUserFace(id);
		}
		return R.status(true);
	}

	/**
	 * 常驻员工统计
	 */
	@GetMapping("/staffStat")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "常驻员工统计", notes = "传入staff")
	public R staffStat() {
		return R.data(this.staffService.staffStat());
	}

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



}
