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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.Constants;
import org.springblade.community.accessrecord.entity.AccessRecord;
import org.springblade.community.accessrecord.service.IAccessRecordService;
import org.springblade.community.accessrecord.vo.AccessRecordVO;
import org.springblade.community.accessrecord.wrapper.AccessRecordWrapper;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.houseuser.entity.Houseuser;
import org.springblade.community.houseuser.service.IHouseuserService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
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.core.tool.utils.StringUtil;
import org.springblade.smartapplication.facedevice.entity.FaceDevice;
import org.springblade.smartapplication.facedevice.service.IFaceDeviceService;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.utils.AESPlus;
import org.springblade.utils.QueryWrapperUtil;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 *  控制器 - 园区人员通行控制器
 *
 * @author BladeX
 * @since 2021-01-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("community/accessrecord")
@Api(value = "出入记录", tags = "出入记录")
public class AccessRecordController extends BladeController {

	private IAccessRecordService accessRecordService;
	private IResidentialService residentialService;
	private IOrgPositionService orgPositionService;
	private IFaceDeviceService faceDeviceService;
	private IAgencyService agencyService;
	private IHouseuserService houseuserService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入accessRecord")
	public R<AccessRecordVO> detail(AccessRecord accessRecord) {
		AccessRecord detail = accessRecordService.getOne(Condition.getQueryWrapper(accessRecord));
		/*LambdaQueryWrapper<Houseuser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.select(Houseuser::getId, Houseuser::getName, Houseuser::getIdCard, Houseuser::getTel,
			Houseuser::getImageUri, Houseuser::getAgencyName, Houseuser::getResidentialName, Houseuser::getBuildingName,
			Houseuser::getUnitName, Houseuser::getRoomName);
		lambdaQueryWrapper.isNotNull(Houseuser::getAgencyName);
		lambdaQueryWrapper.isNotNull(Houseuser::getImageUri);
		lambdaQueryWrapper.orderByDesc(Houseuser::getCreateTime);
		lambdaQueryWrapper.last("limit 30");
		List<Houseuser> houseuserList = houseuserService.list(lambdaQueryWrapper);
		try{
			for(Houseuser user : houseuserList){
				if(StringUtil.isNotBlank(user.getAgencyName())){
					user.setAgencyName(AESPlus.encrypt(Constants.encryptKey, user.getAgencyName()));
				}
				if(StringUtil.isNotBlank(user.getResidentialName())){
					user.setResidentialName(AESPlus.encrypt(Constants.encryptKey, user.getResidentialName()));
				}
				if(StringUtil.isNotBlank(user.getBuildingName())){
					user.setBuildingName(AESPlus.encrypt(Constants.encryptKey, user.getBuildingName()));
				}
				if(StringUtil.isNotBlank(user.getUnitName())){
					user.setUnitName(AESPlus.encrypt(Constants.encryptKey, user.getUnitName()));
				}
				if(StringUtil.isNotBlank(user.getFloorName())){
					user.setFloorName(AESPlus.encrypt(Constants.encryptKey, user.getFloorName()));
				}
				if(StringUtil.isNotBlank(user.getRoomName())){
					user.setRoomName(AESPlus.encrypt(Constants.encryptKey, user.getRoomName()));
				}
				houseuserService.updateById(user);
			}
		}catch (Exception e){

		}*/
		return R.data(AccessRecordWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入accessRecord")
	public R<IPage<AccessRecordVO>> list(@RequestParam Map accessRecord, Query query, BladeUser bladeUser) {

		LambdaQueryWrapper<AccessRecord> wrapper = new QueryWrapperUtil<AccessRecord>().getBasicQueryWrapperByMap(AccessRecord::getOrgPosition, accessRecord, new AccessRecord(), bladeUser, orgPositionService);
		Object residentialId = accessRecord.get("residentialId");
		if (residentialId != null){
			Residential residential = this.residentialService.getById(Long.parseLong(residentialId.toString()));
			accessRecord.put("orgPosition", residential.getOrgPosition());
			accessRecord.remove("residentialId");
		}
		query.setDescs("create_time");
		IPage<AccessRecord> pages = accessRecordService.page(Condition.getPage(query), wrapper);
		return R.data(AccessRecordWrapper.build().pageVO(pages));
	}


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

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

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入accessRecord")
	public R update(@Valid @RequestBody AccessRecord accessRecord) {
		return R.status(accessRecordService.updateById(accessRecord));
	}

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


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(accessRecordService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 生成记录
	 */
	@PostMapping("/initRecord")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "生成记录", notes = "传入accessRecord")
	public R initRecord(@Valid @RequestBody AccessRecord accessRecord) {
		String userNames[] = {"肖志凤","肖志凤","买涛","马秀花","丁娅蓉","王媛媛","王学林","杨红梅","苏小海","马晓刚","马晓刚","马晓刚","王建国","马欣","杨春梅","田穆峰","马铁军","马红霞","马红霞","周文花","周文花","周海军","周海军","田玉国","丁振楠","陈梦瑶","陈梦瑶","陈梦瑶"};
		String images[] = {"/7d25e8c9-b6ed-4d93-b7ab-7276490b1c20-1613034002208.png","/90e64a03-7dcc-43fd-b45b-bdbc8f6ae9d0-1613034002484.png","/19ccc4ff-a796-4bed-a2e7-19dbd524746e-1613034003869.png","/05f858a0-be14-4585-9836-437f2e020e7f-1613034601428.png","/7177e1d0-4b6f-49af-afd9-8abd510a4bc5-1613034601762.png","/60d5b6db-c296-450d-b7ed-420019a8df72-1613034602045.png","/512bbc29-a188-41d5-bab0-dab70a48fa73-1613034602403.png","/8aa480d9-6de5-41be-a475-fc4727da60b3-1613034602753.png","/63002ece-3f10-4195-bd6b-e3d1946f0500-1613034604096.png","/ff69f061-d400-49ee-884e-69d99d02527d-1613034606989.png","/28aa8ee7-0251-4b2b-8989-093317632a9b-1613034608775.png","/f07d917c-491f-4f86-9c9a-7b2ef9545231-1613034609862.png","/5df26255-dbe8-47c1-9551-0c739e5c1dae-1613035201111.png","/35e34e9b-ef83-4c63-9b2d-0ebc0c3df204-1613035201438.png","/af4864ee-6a6d-49bf-afc4-5edad1977d3b-1613035203233.png","/c1c9e532-719b-4579-9c3f-0c6639765186-1613035203476.png","/f5a8cc1a-3626-47dd-b8a2-c1e269016df3-1613035206607.png","/eb6372c7-3de8-4f20-bdb4-ac002ab2fce7-1613035207594.png","/1c27ccbc-2c0e-4845-9256-0382096daa97-1613035209375.png","/13e56041-af9e-4283-a148-519fffa752c5-1613035801240.png","/690a38b8-ce10-4a3c-a8cd-b715e4bbec82-1613035801558.png","/1539be80-6581-471f-90c6-eddc37299935-1613035803301.png","/a55e866d-0bab-4e63-a0de-3ddfd0a78bbd-1613035803601.png","/e5a34cda-981c-4fcd-9e67-9d047a6ec13f-1613035806068.png","/9966cd71-fbe7-4624-bc91-f5b30b404ee3-1613035806401.png","/5e9aa4d3-8d24-4304-ad42-30c72d1d0700-1613036401214.png","/9e85df63-6eec-4780-b9b3-6cf9857e970e-1613036401469.png","/8b6effd1-6d3c-4acf-ac70-cd0c9044d557-1613036401704.png"};
		String baseUrl = "http://139.9.103.171:1888/miniofile/cyzhyc";

		Residential residential = residentialService.getById(accessRecord.getResidentialId());
		Agency agency = agencyService.getById(residential.getAgencyId());

		List<FaceDevice> faceDevices = faceDeviceService.list(new QueryWrapper<>(new FaceDevice()).lambda().eq(FaceDevice::getResidentialId, accessRecord.getResidentialId()));

		Random rand = new Random();
		Integer ran15_30 = rand.nextInt(15) + 15; // 记录条数
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		if (faceDevices.size() > 0){
			for (int i = 0; i < ran15_30; i++) {
				FaceDevice faceDevice = faceDevices.get(rand.nextInt(faceDevices.size()));
				AccessRecord record = new AccessRecord();
				Integer ran28 = rand.nextInt(27) + 1; // 记录条数
				Integer ran9 = rand.nextInt(9); // 体温小数

				record.setResidentialId(residential.getId());
				record.setResidentialName(residential.getName());
				record.setAgencyId(residential.getAgencyId());
				record.setAgencyName(agency.getAgencyName());
				record.setTenantId(residential.getTenantId());
				record.setOrgPosition(residential.getOrgPosition());
				record.setTemperature("36." + ran9);
				record.setUserName(userNames[ran28]);
				record.setFaceUrl(baseUrl + images[ran28]);
				record.setDeviceMac(faceDevice.getMacAddress());
				record.setOpenType("1");

				//开门时间
				Integer ran12h = (rand.nextInt(12) + 8);  // 小时
				String hour = (ran12h >= 10 )? ran12h + "" : "0" + ran12h;
				Integer ran59m = rand.nextInt(59) + 1; //
				String min = (ran59m >= 10 )? ran59m + "" : "0" + ran59m;
				Integer ran59s = rand.nextInt(59) + 1; // 秒
				String second = (ran59s >= 10 )? ran59s + "" : "0" + ran59s;

				String openTime = accessRecord.getOpenTime() + " " + hour + ":" + min + ":" + second;
				record.setOpenTime(openTime);
				try{
					record.setCreateTime(sdf.parse(openTime));
				}catch (Exception e){

				}

				accessRecordService.save(record);
			}



		}else{
			return R.fail("该小区没有人脸设备");
		}


		return R.status(true);
	}


}
