package com.yuchen.saas.park.service.controller.datav;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yuchen.saas.park.api.entity.park.PmgBatDeviceData;
import com.yuchen.saas.park.api.entity.park.PmgLogPeopleCount;
import com.yuchen.saas.park.api.entity.park.PmgLogVideoEventsCount;
import com.yuchen.saas.park.api.vo.park.DeviceOnLineCountVo;
import com.yuchen.saas.park.service.config.PeopleConfig;
import com.yuchen.saas.park.service.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 吕海泉
 * @create 2020/12/22 11:24
 */

@RestController
@RequestMapping("/analysis")
@Api(value = "人员数据分析表", tags = "人员数据分析接口")
public class DataAnalysisController {

    @Resource
    private IPeopleCountService iPeopleCountService;

    @Autowired
    private ParkDeviceDataService parkDeviceDataService;

    @Autowired
    private IWarningInfoService iWarningInfoService;

    @Autowired
    private PmgBatSmartEquipmentService pmgBatSmartEquipmentService;

    @Value("${people.temperature}")
    private String temperature;

    @Autowired
    private PeopleConfig peopleConfig;

    /**
     * 视频事件
     */
    @Autowired
    private PmgLogVideoEventsCountService pmgLogVideoEventsCountService;

    /**
     *  站点信息表
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页", notes = "传入parkCompany")
    public R<IPage<PmgLogPeopleCount>> list(Long timeStamp, Query query) {
        LambdaQueryWrapper<PmgLogPeopleCount> peopleCountWrapper = Wrappers.lambdaQuery();
        IPage<PmgLogPeopleCount> pages = iPeopleCountService.page(Condition.getPage(query),
                peopleCountWrapper.gt(PmgLogPeopleCount::getTimeStamp, timeStamp).orderByDesc(PmgLogPeopleCount::getTimeStamp));
        return  R.data(pages);
    }

    /**
     * 分页 站点信息表
     */
    @GetMapping("/people/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入parkCompany")
    public R<IPage<PmgLogPeopleCount>> list(PmgLogPeopleCount pmgLogPeopleCount, Query query) {

        return R.data(iPeopleCountService.pagePeople(pmgLogPeopleCount, query));
    }

    /**
     *
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "新增", notes = "")
    public R save(@Valid @RequestBody PmgLogPeopleCount pmgLogPeopleCount) {
        return R.status(iPeopleCountService.save(pmgLogPeopleCount));
    }

    /**
     *  设备数据入库
     */
    @PostMapping("/save/device_data")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "新增", notes = "")
    public R saveDevice( @RequestBody PmgBatDeviceData pmgBatDeviceData) {
        return R.status(parkDeviceDataService.save(pmgBatDeviceData));
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "修改", notes = "传入parkCompany")
    public R update(@Valid @RequestBody PmgLogPeopleCount pmgLogPeopleCount) {
        return R.status(iPeopleCountService.updateById(pmgLogPeopleCount));
    }

    /**
     * 人员进入统计 24小时入园统计
     * @return
     */
    @GetMapping("/getCountTime24")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "统计近24小时每小时的入园人数")
    public R<Map<String, Object>> getEnterParkPeopleCount() {
        return R.data(iPeopleCountService.getCountTime24());
    }

    /**
     * 统计
     * @return
     */
    @GetMapping("/statistics")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "")
    public R<Map<String, Object>> getStatisticsime() {
        return R.data(iWarningInfoService.getTotal());
    }

    /**
     * 统计已处理何未处理
     * @return
     */
    @GetMapping("/getWarningHandlerResult")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "")
    public R<Map<String,Long>> getWarningHandlerResult() {
        return R.data(iWarningInfoService.getWarningHandlerResult());
    }

    /**
     * 各类人员统计结果
     * @return
     */
    @GetMapping("/person/count")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "")
    public R<Map<String,Long>> getPersonResult() {
        return R.data(iPeopleCountService.getPersonResult());
    }

    /**
     * 设备总数、在线设备数、告警设备数
     * @return
     */
    @GetMapping("/device/count")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "")
    public R<DeviceOnLineCountVo> getDeviceAnalysis() {
        /*List<PmgBatSmartEquipmentVo> pmgBatSmartEquipmentVos =  pmgBatSmartEquipmentService.getDetailAll();
        long deviceCount = pmgBatSmartEquipmentVos.size();
        int onlineDevice = pmgBatSmartEquipmentService.getAllDevice();

        List<WarningDeviceVo> list = iWarningInfoService.getWarningDevice();
        int warningDevice = list.size();
        Map<String,Long> map = new HashMap<>(3);
        map.put("deviceCount",deviceCount);
        map.put("onlineDevice", (long) onlineDevice);
        map.put("warningDevice", (long) warningDevice);
        */
        return R.data(pmgBatSmartEquipmentService.getOnLineCount());
    }

    /**
     * 安防告警事件趋势
     * 一级、二级、三级、四级
     * @return
     */
    @GetMapping("/device/warning/count")
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "")
    public R<Map<String, Object>> getWarningByLevel() {
        return R.data(iWarningInfoService.getWarningByLevel());
    }

    /**
     * 通过人员类型获取相关人员所属楼宇分布
     * @param code
     * @return
     */
    @GetMapping("/visitorBuildingSpread")
    @ApiOperationSupport(order = 13)
    @ApiOperation(value = "")
    public R<List<Map<String, Object>>> visitorBuildingSpread(String code) {
        return R.data(iPeopleCountService.visitorBuildingSpread(code));
    }
    /**
     * 通过人员类型获取相关人员今日入园总数
     * eg: 传入 code = 10001(人员类型)， 返回人员类型为10001对应的今日入园人员总数
     * @param code
     * @return
     */
    @GetMapping("/getToDayCountByCode")
    @ApiOperationSupport(order = 14)
    @ApiOperation(value = "")
    public R<Long> getToDayCountByCode(String code) {
        return R.data(iPeopleCountService.getToDayCountByCode(code));
    }

//    /**
//     * 查询历史异常人员和陌生人
//     *
//     */
//
//    @GetMapping("/getListAbnormalAndStranger")
//    @ApiOperationSupport(order = 6)
//    @ApiOperation(value = "")
//    public R<List<PmgLogPeopleCount>> getListAbnormalAndStranger() {
//        return R.data(iPeopleCountService.getListAbnormalAndStranger());
//    }

    /**
     * 查询历史异常人员和陌生人
     *
     */
    @GetMapping("/getListAbnormalAndStranger")
    @ApiOperationSupport(order = 15)
    @ApiOperation(value = "")
    public R<IPage<PmgLogPeopleCount>> getListAbnormalAndStranger(PmgLogPeopleCount pmgLogPeopleCount, Query query) {
        LambdaQueryWrapper<PmgLogPeopleCount> peopleWrapper = Wrappers.lambdaQuery();
        IPage<PmgLogPeopleCount> pages = iPeopleCountService.page(Condition.getPage(query),
                peopleWrapper.like(StringUtils.isNotBlank(pmgLogPeopleCount.getEquipmentName()),
                                PmgLogPeopleCount::getEquipmentName, pmgLogPeopleCount.getEquipmentName())
                            .and(pmgLogPeopleCount.getTemperature() != null && pmgLogPeopleCount.getTemperature() > 0,
                                wrapper -> wrapper.likeRight(PmgLogPeopleCount::getTemperature, pmgLogPeopleCount.getTemperature())
                                        .or().eq(PmgLogPeopleCount::getTemperature, pmgLogPeopleCount.getTemperature()))
                            .and(wrapper -> wrapper.gt(PmgLogPeopleCount::getTemperature, peopleConfig.getTemperature())
                            .or().eq(PmgLogPeopleCount::getCode,peopleConfig.getCode10003())).orderByDesc(PmgLogPeopleCount::getTimeStamp)
                        );
        return  R.data(pages);
    }
    /**
     * 查询历史温度正常人员
     */
    @GetMapping("/getListNormalAbnormal")
    @ApiOperationSupport(order = 16)
    @ApiOperation(value = "")
    public R<IPage<PmgLogPeopleCount>> getListNormalAbnormal(PmgLogPeopleCount pmgLogPeopleCount, Query query) {
        LambdaQueryWrapper<PmgLogPeopleCount> peopleWrapper = Wrappers.lambdaQuery();
        IPage<PmgLogPeopleCount> pages = iPeopleCountService.page(Condition.getPage(query),
                peopleWrapper.isNotNull(PmgLogPeopleCount::getTemperature)
                        .and(pmgLogPeopleCount.getTemperature() != null && pmgLogPeopleCount.getTemperature() > 0,
                                wrapper -> wrapper.likeRight(PmgLogPeopleCount::getTemperature, pmgLogPeopleCount.getTemperature())
                                        .or().eq(PmgLogPeopleCount::getTemperature, pmgLogPeopleCount.getTemperature()))
                        .like(StringUtils.isNotBlank(pmgLogPeopleCount.getEquipmentName()),
                                PmgLogPeopleCount::getEquipmentName, pmgLogPeopleCount.getEquipmentName())
                        .le(PmgLogPeopleCount::getTemperature, peopleConfig.getTemperature())
                        .gt(PmgLogPeopleCount::getTemperature, peopleConfig.getZero()).orderByDesc(PmgLogPeopleCount::getTimeStamp));
        return  R.data(pages);
    }
    /**
     * 查询陌生人和高频人员列表
     *
     */
    @GetMapping("/getHighFrequencyAndStranger")
    @ApiOperationSupport(order = 17)
    @ApiOperation(value = "")
    public R<IPage<PmgLogPeopleCount>> getHighFrequencyAndStranger(PmgLogPeopleCount pmgLogPeopleCount, Query query) {
        return R.data(iPeopleCountService.getHighFrequencyAndStranger(pmgLogPeopleCount, query));
    }
    /**
     * 分页查询历史温度异常人员
     */
    @GetMapping("/getListAbnormal")
    @ApiOperationSupport(order = 18)
    @ApiOperation(value = "")
    public R<IPage<PmgLogPeopleCount>> getListAbnormal(PmgLogPeopleCount pmgLogPeopleCount, Query query) {

        return  R.data(iPeopleCountService.pagePeopleAbnormal(pmgLogPeopleCount, query));
    }
    /**
     * 首页-人员图像接口返回数据
     * @return
     */
    @GetMapping("/getPersonImage")
    @ApiOperationSupport(order = 19)
    @ApiOperation(value = "")
    public R<Map<String, Long>> getPersonImage(){
        return R.data(iPeopleCountService.getPersonImage());
    }

    /**
     * 今日体温正常人员分页查询
     * @param pmgLogPeopleCount 人员信息
     * @param query 分页信息
     * @return
     */
    @GetMapping("/getNormalDayPage")
    @ApiOperationSupport(order = 21)
    @ApiOperation(value = "")
    public R<IPage<PmgLogPeopleCount>> getNormalDayPage(PmgLogPeopleCount pmgLogPeopleCount, Query query){
        return R.data(iPeopleCountService.getNormalDayPage(pmgLogPeopleCount, query));
    }

    /**
     * 今日体温异常人员分页查询
     * @param pmgLogPeopleCount 人员信息
     * @param query 分页信息
     * @return
     */
    @GetMapping("/getAbnormalDayPage")
    @ApiOperationSupport(order = 22)
    @ApiOperation(value = "")
    public R<IPage<PmgLogPeopleCount>> getAbnormalDayPage(@RequestParam String parkId, PmgLogPeopleCount pmgLogPeopleCount, Query query){
        return R.data(iPeopleCountService.getAbnormalDayPage(parkId, pmgLogPeopleCount, query));
    }

    /**
     * 私有方法 获取今日最早时间
     * @return
     */
    private Date startOfDay() {
        Calendar todayStart = Calendar.getInstance();
        int year = todayStart.get(Calendar.YEAR);
        int month = todayStart.get(Calendar.MONTH);
        int day = todayStart.get(Calendar.DATE);
        todayStart.set(year, month, day, 0, 0, 0);
        return todayStart.getTime();
    }

    /**
     * 私有方法 获取今日最晚时间
     * @return
     */
    private Date endOfDay() {
        Calendar todayEnd = Calendar.getInstance();
        int year = todayEnd.get(Calendar.YEAR);
        int month = todayEnd.get(Calendar.MONTH);
        int day = todayEnd.get(Calendar.DATE);
        todayEnd.set(year, month, day, 23, 59, 59);
        return todayEnd.getTime();
    }

    /**
     * 今日陌生人分页查询
     * @param pmgLogPeopleCount 人员信息
     * @param query 分页信息
     * @return
     */
    @GetMapping("/getStrangerDayPage")
    @ApiOperationSupport(order = 23)
    @ApiOperation(value = "")
    public R<IPage<PmgLogPeopleCount>> getStrangerDayPage(PmgLogPeopleCount pmgLogPeopleCount, Query query){
        return R.data(iPeopleCountService.getStrangerDayPage(pmgLogPeopleCount, query));
    }

    /**
     * 今日行为事件分页查询
     * @param query 分页信息
     * @return
     */
    @GetMapping("/getVideoDayPage")
    @ApiOperationSupport(order = 23)
    @ApiOperation(value = "")
    public R<IPage<PmgLogVideoEventsCount>> getVideoDayPage(PmgLogVideoEventsCount pmgLogVideoEventsCount, Query query){
        IPage<PmgLogVideoEventsCount> iPage = pmgLogVideoEventsCountService.page(Condition.getPage(query),
                Condition.getQueryWrapper(pmgLogVideoEventsCount).between("time_stamp",startOfDay()
                        .getTime(),endOfDay().getTime()).orderByDesc("time_stamp"));
        return R.data(iPage);
    }
}
