package com.yuchen.saas.park.service.fault.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.park.api.entity.fault.*;
import com.yuchen.saas.park.api.vo.fault.EquipmentPictureAnalyseVo;
import com.yuchen.saas.park.service.fault.mapper.EquipmentBreakdownAnalyseHistoryMapper;
import com.yuchen.saas.park.service.fault.mapper.EquipmentPictureAnalyseMapper;
import com.yuchen.saas.park.service.fault.service.EquipmentBreakdownHistoryService;
import com.yuchen.saas.park.service.fault.service.EquipmentPictureAnalyseService;
import com.yuchen.saas.park.service.fault.service.EquipmentPictureRuleService;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.BeanUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 肖润飞
 * @CreateTime: 2022/10/18 15:44
 * @Description: 设备画像分析
 * @Version: 1.0
 */
@Service
public class EquipmentPictureAnalyseServiceImpl extends BaseServiceImpl<EquipmentPictureAnalyseMapper, EquipmentPictureAnalyse> implements EquipmentPictureAnalyseService {

    @Resource
    private EquipmentBreakdownHistoryService historyService;

    @Resource
    private EquipmentPictureRuleService pictureRuleService;

    @Resource
    private EquipmentPictureAnalyseMapper analyseMapper;

    @Resource
    private EquipmentBreakdownAnalyseHistoryMapper analyseHistoryMapper;

    /**
     * 根据analyseId查询设备故障历史
     *
     * @param id 设备状态id
     * @return
     */
    @Override
    public R pageHistory(Page page, Long id) {
        if (id != null) {
            EquipmentBreakdownAnalyseHistory analyseHistory = new EquipmentBreakdownAnalyseHistory();
            analyseHistory.setAnalyseId(id);
            IPage<EquipmentBreakdownAnalyseHistory> pageList = analyseHistoryMapper.selectPage(page, Condition.getQueryWrapper(analyseHistory));
            IPage<EquipmentBreakdownHistory> pageResult = new Page<>();
            BeanUtil.copyProperties(pageList, pageResult);
            if (pageList.getTotal() > 0) {
                List<Long> collect = pageList.getRecords().stream().map(ah -> ah.getHistoryId()).collect(Collectors.toList());
                List<EquipmentBreakdownHistory> equipmentBreakdownHistories = historyService.listByIds(collect);

                pageResult.setRecords(equipmentBreakdownHistories);
                return R.data(pageResult);
            }
        }
        return R.data(null);
    }

    /**
     * 保存设备画像分析数据
     *
     * @param equipmentStatus 设备异常状态信息
     * @return
     */
    @Override
    public EquipmentPictureAnalyse saveAnalyse(EquipmentStatus equipmentStatus, EquipmentBreakdownHistory history) {
        // 1.检测设该异常是否存在对应的画像规则
        EquipmentPictureRule pictureRule = pictureRuleService.checkEquipmentPictureRule(equipmentStatus);
        if (pictureRule != null) {
            //表示存在该规则,使用规则进行次数统计,看是否触发画像分析
            EquipmentPictureAnalyse analyse = pictureRuleService.pictureCount(pictureRule, equipmentStatus, history);
            return analyse;
        }
        return null;
    }


    /**
     * 画像分析分页查询
     *
     * @param page
     * @param vo
     * @return
     */
    @Override
    public R analysePage(Page page, EquipmentPictureAnalyseVo vo) {
        IPage<EquipmentPictureAnalyseVo> res = analyseMapper.conditionPage(page, vo);
        return R.data(res);
    }

    /**
     * 根据园区统计设备画像数据
     *
     * @param parkId
     * @return
     */
    @Override
    public R pictureRate(Long parkId) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> list = analyseMapper.analyseCount(parkId);
        int sum = list.stream().filter(map -> map.get("isShow").toString().equals("1")).mapToInt(map -> Integer.valueOf(map.get("count") == null ? "0" : map.get("count").toString())).sum();
        DecimalFormat format = new DecimalFormat("0.00");
        Iterator<Map<String, Object>> iterator = list.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> map = iterator.next();
            String isShow = map.get("isShow").toString();
            if (isShow.equals("0")) {
                iterator.remove();
                continue;
            }
            Object numMap = map.get("count");
            long num = 0;
            if (numMap == null) {
                map.put("count", 0);
            } else {
                num = (long) map.get("count");
            }
            String rate = format.format(((float) num / sum) * 100);
            map.put("rate", rate);
        }
        resultMap.put("list", list);
        resultMap.put("total", sum);
        return R.data(resultMap);
    }


}