/*
 *      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.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
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.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springblade.common.constant.EstateConstant;
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.excel.util.ExcelUtil;
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.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.enterprise.entity.Enterprise;
import org.springblade.enterprise.feign.IEnterpriseClient;
import org.springblade.estate.dto.SnapRecordDTO;
import org.springblade.estate.excel.SnapRecordExcel;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.system.feign.ISysClient;
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.SnapRecord;
import org.springblade.estate.vo.SnapRecordVO;
import org.springblade.estate.wrapper.SnapRecordWrapper;
import org.springblade.estate.service.ISnapRecordService;
import org.springblade.core.boot.ctrl.BladeController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 控制器
 *
 * @author BladeX
 * @since 2022-01-05
 */
@RestController
@AllArgsConstructor
@RequestMapping("/snaprecord")
@Api(value = "", tags = "接口")
public class SnapRecordController extends BladeController {

	private final ISnapRecordService snapRecordService;
	private final ISysClient sysClient;
	private final IConfClient confClient;
	private final IAgencyClient agencyClient;
	private final IResidentialClient residentialClient;
	private final IEnterpriseClient enterpriseClient;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入snapRecord")
	public R<SnapRecordVO> detail(SnapRecord snapRecord) {
		SnapRecord detail = snapRecordService.getOne(Condition.getQueryWrapper(snapRecord));
		return R.data(SnapRecordWrapper.build().entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入snapRecord")
	public R<IPage<SnapRecordVO>> list(SnapRecordDTO snapRecordDTO, Query query, BladeUser bladeUser) {
		QueryWrapper<SnapRecord> queryWrapper = Condition.getQueryWrapper(snapRecordDTO);
		queryWrapper.lambda().orderByDesc(SnapRecord::getCreateTime);
		if (StringUtil.isNotBlank(snapRecordDTO.getQueryDate())) {
			queryWrapper.lambda().like(SnapRecord::getCreateTime, snapRecordDTO.getQueryDate());
		}
		IPage<SnapRecord> pages = snapRecordService.page(Condition.getPage(query), (!bladeUser.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(SnapRecord::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(SnapRecordWrapper.build().pageVO(pages));
	}

	/**
	 * 分页筛选高温记录
	 *
	 * @param snapRecord 查询条件
	 * @param query      分页参数
	 * @param isHigh     是否筛选高温记录
	 * @return
	 */
	@GetMapping("/list2")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入snapRecord")
	public R<IPage<SnapRecordVO>> list2(SnapRecord snapRecord, Query query, @RequestParam Boolean isHigh) {
		BigDecimal highTemperature = Convert.toBigDecimal(sysClient.getParamValue(EstateConstant.HIGH_TEMPERATURE_NAME).getData());
		LambdaQueryWrapper<SnapRecord> queryWrapper = Condition.getQueryWrapper(snapRecord).ge(isHigh, "temperature+0", highTemperature).lambda().orderByDesc(SnapRecord::getCreateTime);
		IPage<SnapRecord> pages = snapRecordService.page(Condition.getPage(query), queryWrapper);
		return R.data(SnapRecordWrapper.build().pageVO(pages));
	}


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

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

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

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


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

	/**
	 * 导出excel
	 *
	 * @param type 1：今日记录 2：所有记录
	 * @return
	 */
	@GetMapping("/exportExcel")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "导出excel", notes = "传入type")
	public void exportExcel(@RequestParam Integer type, HttpServletResponse response) {
		String prefixTitle = Objects.equals(type, 1) ? DateUtil.format(new Date(), "yyyy年MM月dd日") : "";
		String fileName = prefixTitle + "测温异常记录";
		//获取异常记录
		List<SnapRecordExcel> list = new ArrayList<>();
		BigDecimal highTemperature = Convert.toBigDecimal(sysClient.getParamValue(EstateConstant.HIGH_TEMPERATURE_NAME).getData());
		LambdaQueryWrapper<SnapRecord> queryWrapper = Condition.getQueryWrapper(new SnapRecord())
			.ge("temperature+0", highTemperature)
			.lambda()
			.between(Objects.equals(type, 1), SnapRecord::getCreateTime, LocalDateTimeUtil.beginOfDay(LocalDateTime.now()), LocalDateTimeUtil.endOfDay(LocalDateTime.now()))
			.orderByDesc(SnapRecord::getCreateTime);
		List<SnapRecord> snapRecords = snapRecordService.list(queryWrapper);
		snapRecords.forEach(item -> getSnapRecordExcelList(item, list));
		ExcelUtil.export(response, fileName, "测温异常数据表", list, SnapRecordExcel.class);
	}


	/**
	 * 获取体温异常数量
	 */
	@GetMapping("/getTemperatureAnomaliesCount")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入snapRecord")
	public R temperatureAnomaliesCount() {
		//体温异常临界点
		BigDecimal highTemperature = Convert.toBigDecimal(sysClient.getParamValue(EstateConstant.HIGH_TEMPERATURE_NAME).getData());
		int count = snapRecordService.count(Condition.getQueryWrapper(new SnapRecord())
			.ge("temperature+0", highTemperature));
		return R.data(count);
	}

	/**
	 * 组装snapRecordExcels对象
	 *
	 * @param snapRecord
	 * @param snapRecordExcels
	 * @return
	 */
	private List<SnapRecordExcel> getSnapRecordExcelList(SnapRecord snapRecord, List<SnapRecordExcel> snapRecordExcels) {
		snapRecord.setFaceUrl(confClient.addPrefix(snapRecord.getFaceUrl()));

		SnapRecordExcel snapRecordExcel = new SnapRecordExcel();
		BeanUtil.copyProperties(snapRecord, snapRecordExcel);

		snapRecordExcel.setTemperature(snapRecord.getTemperature() + "℃");
		snapRecordExcel.setScore(snapRecord.getScore() + "分");

		if (Objects.equals(snapRecord.getIsOut(), 1)) {
			snapRecordExcel.setIsOutType("进");
		} else if (Objects.equals(snapRecord.getIsOut(), 2)) {
			snapRecordExcel.setIsOutType("出");
		} else {
			snapRecordExcel.setIsOutType("未知");
		}
		//获取园区信息
		Agency agency = agencyClient.getById(snapRecord.getAgencyId());
		String agencyName = Optional.ofNullable(agency).map(Agency::getName).orElse("暂无园区信息");
		snapRecordExcel.setAgencyName(agencyName);
		//获取区域信息
		Residential residential = residentialClient.getById(snapRecord.getResidentialId());
		String residentialName = Optional.ofNullable(residential).map(Residential::getName).orElse("暂无区域信息");
		snapRecordExcel.setResidentialName(residentialName);
		//获取企业信息
		Enterprise enterprise = enterpriseClient.getById(snapRecord.getEnterpriseId());
		String enterpriseName = Optional.ofNullable(enterprise).map(Enterprise::getEnterpriseName).orElse("暂无企业信息");
		snapRecordExcel.setEnterpriseName(enterpriseName);
		snapRecordExcels.add(snapRecordExcel);
		return snapRecordExcels;
	}


}
