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

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.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningCategory;
import com.yuchen.saas.park.api.entity.park.PmgBatWarningLevel;
import com.yuchen.saas.park.api.entity.park.PmgLogPeopleCount;
import com.yuchen.saas.park.api.vo.park.HandleStatisticsVo;
import com.yuchen.saas.park.api.vo.park.PmgBatWarningCategoryVo;
import com.yuchen.saas.park.api.vo.park.WarningCategoryLevelName;
import com.yuchen.saas.park.service.service.IPeopleCountService;
import com.yuchen.saas.park.service.service.IWarningCategoryService;
import com.yuchen.saas.park.service.service.IWarningLevelService;
import com.yuchen.saas.park.service.service.PmgLogVideoEventsCountService;
import com.yuchen.saas.park.service.config.PeopleConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.nest.springwrap.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 吕海泉
 * @create 2020/12/7 16:53
 */
@RestController
@AllArgsConstructor
@RequestMapping("/category")
@Api(value = "报警类型表", tags = "报警类型管理接口")
public class WarningCategoryController {


    @Resource
    private IWarningCategoryService iWarningCategoryService;

    @Autowired
    private IWarningLevelService iWarningLevelService;

    @Autowired
    private PmgLogVideoEventsCountService pmgLogVideoEventsCountService;

    @Resource
    private IPeopleCountService iPeopleCountService;

    @Autowired
    private PeopleConfig peopleConfig;

    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入PmgBatWarningCategory")
    public R<PmgBatWarningCategory> detail(PmgBatWarningCategory pmgBatWarningCategory) {
        PmgBatWarningCategory detail = iWarningCategoryService.getOne(Condition.getQueryWrapper(pmgBatWarningCategory));
        return R.data(detail);
    }
//
//    /**
//     * 详情
//     */
//    @GetMapping("/categoryAndLevel")
//    @ApiOperationSupport(order = 1)
//    @ApiOperation(value = "详情", notes = "传入PmgBatWarningCategory")
//    public R<PmgBatWarningCategoryVo> getByIdentity(@RequestParam("identity") String identity) {
//        PmgBatWarningCategoryVo pmgBatWarningCategoryVo = iWarningCategoryService.getByIdentity1(identity);
//        return R.data(pmgBatWarningCategoryVo);
//    }

    /**
     * 详情
     */
    @GetMapping("/categoryAndLevel")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "详情", notes = "传入PmgBatWarningCategory")
    public R<PmgBatWarningCategoryVo> getByIdentity(@RequestParam("identity") String identity) {
        PmgBatWarningCategoryVo pmgBatWarningCategoryVo = null;
        PmgBatWarningCategory pmgBatWarningCategory = iWarningCategoryService
                .getOne(Wrappers.<PmgBatWarningCategory>query().lambda()
                        .eq(PmgBatWarningCategory::getIdentity, identity));
        if (null != pmgBatWarningCategory && null != pmgBatWarningCategory.getId()) {
            PmgBatWarningLevel pmgBatWarningLevel = iWarningLevelService.getById(pmgBatWarningCategory.getLevelId());
            pmgBatWarningCategoryVo = new PmgBatWarningCategoryVo();
            pmgBatWarningCategoryVo.setIdentity(identity);
            pmgBatWarningCategoryVo.setRemark(pmgBatWarningCategory.getRemark());
            pmgBatWarningCategoryVo.setLevel(pmgBatWarningLevel.getLevel());
            pmgBatWarningCategoryVo.setLevelName(pmgBatWarningLevel.getName());
            return R.data(pmgBatWarningCategoryVo);
        } else {
            pmgBatWarningCategoryVo.setIdentity(identity);
            pmgBatWarningCategoryVo.setRemark(pmgBatWarningCategory.getRemark());

            return R.data(pmgBatWarningCategoryVo);

        }
    }

    @GetMapping("/getCategoryByParkId")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取园区告警类型", notes = "获取园区告警类型")
    public R<List<PmgBatWarningCategory>> getCategoryByParkId(@RequestParam(required = false) Long parkId) {
        LambdaQueryWrapper<PmgBatWarningCategory> queryWrapper=new LambdaQueryWrapper<>();
        if(parkId==null){
            parkId=Long.parseLong(AuthUtil.getUser().getParkId());
        }
        queryWrapper.eq(PmgBatWarningCategory::getParkId,parkId);
        List<PmgBatWarningCategory> categories=iWarningCategoryService.list(queryWrapper);
        return R.data(categories);
    }

    /**
     * 分页 报警类型表
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "分页")
    public R<IPage<PmgBatWarningCategory>> list(PmgBatWarningCategory pmgBatWarningCategory, Query query) {
        LambdaQueryWrapper<PmgBatWarningCategory> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(pmgBatWarningCategory.getParkId() != null, PmgBatWarningCategory::getParkId,
                pmgBatWarningCategory.getParkId())
                .like(StringUtil.isNotBlank(pmgBatWarningCategory.getName()), PmgBatWarningCategory::getName,
                        pmgBatWarningCategory.getName())
                .like(StringUtil.isNotBlank(pmgBatWarningCategory.getIdentity()), PmgBatWarningCategory::getIdentity,
                        pmgBatWarningCategory.getIdentity())
                .eq(pmgBatWarningCategory.getLevelId() != null, PmgBatWarningCategory::getLevelId,
                        pmgBatWarningCategory.getLevelId());
        IPage<PmgBatWarningCategory> pages = iWarningCategoryService.page(Condition.getPage(query), queryWrapper);
        return R.data(pages);
    }


    /**
     * 新增 报警类型
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入parkCompany")
    public R save(@Valid @RequestBody PmgBatWarningCategory pmgBatWarningCategory) {
        PmgBatWarningCategory pmgBatWarningCategory1 = iWarningCategoryService
                .getOne(Wrappers.<PmgBatWarningCategory>query().lambda()
                        .eq(PmgBatWarningCategory::getIdentity, pmgBatWarningCategory.getIdentity()));
        if (pmgBatWarningCategory1 != null) {
            return R.error("类型已经存在");
        }
        return R.status(iWarningCategoryService.save(pmgBatWarningCategory));
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入parkCompany")
    public R update(@Valid @RequestBody PmgBatWarningCategory pmgBatWarningCategory) {
        return R.status(iWarningCategoryService.updateById(pmgBatWarningCategory));
    }

    /**
     * 删除 报警类型
     */
    @DeleteMapping("/remove")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return R.status(iWarningCategoryService.removeByIds(Func.toLongList(ids)));
        // return R.status(iWarningCategoryService.deleteLogic(Func.toLongList(ids)));
    }


    /**
     * 监控异常统计
     *
     * @param productKey
     * @return
     */
    @GetMapping("/getCameraCount")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "详情", notes = "productKey")
    public R<Map<String, Object>> getCameraCount(String productKey) {
        Map<String, Object> detail = iWarningCategoryService.getCameraCount(productKey);
        return R.data(detail);
    }


    /**
     * 异常事件近一周的统计
     */
//    @GetMapping("/abnormal/count")
//    @ApiOperationSupport(order = 8)
//    @ApiOperation(value = "异常事件趋势", notes = "异常事件趋势")
//    public com.thinkunion.park.service.manage.util.R abnormalCount() {
//        StringBuilder operateDate = new StringBuilder();
//        StringBuilder resultDate = new StringBuilder();
//        SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
//        SimpleDateFormat md = new SimpleDateFormat("MM-dd");
//
//        Calendar calendar = Calendar.getInstance();
//        for (int i = 6; i >= 0; i--) {
//            calendar.setTime(new Date());
//            calendar.add(Calendar.DATE, -i);
//            operateDate.append(ymd.format(calendar.getTime())).append(",");
//            resultDate.append(md.format(calendar.getTime())).append(",");
//        }
//
//        return com.thinkunion.park.service.manage.util.R.ok(iWarningCategoryService.getAbnormalCount(operateDate
//        .toString())).put("date", Arrays.asList(resultDate.toString().split(",")));
//    }

    /**
     * 获取分页查询报警类型接口
     * @param query 分页数据
     * @return
     */
    @GetMapping("/getWarningCategoryPage")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "获取分页查询报警类型接口", notes = "获取分页查询报警类型接口")
    public R getWarningCategoryPage(Query query) {
        IPage<WarningCategoryLevelName> pages = iWarningCategoryService
                .getWarningCategoryPage(Condition.getPage(query));
        return R.data(pages);
    }

    /**
     * 异常事件趋势 - 2021年2月3日 新
     * @return
     */
    @GetMapping("/abnormal/trend")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "异常事件趋势", notes = "异常事件趋势")
    public R<Map<String, Object>> getAbnormalTrend() {
        StringBuilder operateDate = new StringBuilder();
        StringBuilder resultDate = new StringBuilder();
        SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat md = new SimpleDateFormat("MM-dd");

        Calendar calendar = Calendar.getInstance();
        for (int i = 6; i >= 0; i--) {
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE, -i);
            operateDate.append(ymd.format(calendar.getTime())).append(",");
            resultDate.append(md.format(calendar.getTime())).append(",");
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("date", Arrays.asList(resultDate.toString().split(",")));
        map.put("data", iWarningCategoryService.getAbnormalCount(operateDate.toString()));
        return R.data(map);
    }

    /**
     * 行为事件、测温事件、异常事件（陌生人和高频人员） 的总数、已处理、未处理
     * @return
     */
    @GetMapping("/getStatistics")
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "获取统计数据", notes = "获取统计数据")
    public R<Map<String, Object>> getStatistics() {
        // 声明返回集合
        Map<String, Object> map = new HashMap<>();
        // 1、行为事件的总数、已处理，未处理
        HandleStatisticsVo handleStatisticsVo = pmgLogVideoEventsCountService.getStatistics();
        map.put("behavior", handleStatisticsVo);
        // 2、测温事件的总数、已处理、未处理
        QueryWrapper<PmgLogPeopleCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("temperature").gt("temperature", peopleConfig.getTemperature());
        map.put("temperature", iPeopleCountService.count(queryWrapper));
        // 3、异常事件的总数、已处理、未处理
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", peopleConfig.getCode10003()).or().eq("code", peopleConfig.getCode10004());
        map.put("abnormal", iPeopleCountService.count(queryWrapper));
        return R.data(map);
    }

}

