package com.zcxk.rmcp.web.service.impl;

import cn.hutool.extra.cglib.CglibUtil;
import com.github.pagehelper.PageHelper;
import com.zcxk.core.common.exception.BusinessException;
import com.zcxk.core.common.util.BeanCopyUtils;
import com.zcxk.core.mysql.pageing.Pagination;
import com.zcxk.core.oauth2.util.UserUtil;
import com.zcxk.core.utils.export.EasyExcelUtil;
import com.zcxk.rmcp.api.dto.BasePageDto;
import com.zcxk.rmcp.api.dto.alarm.DeviceAlarmQueryDto;
import com.zcxk.rmcp.api.enums.DeviceStatusEnum;
import com.zcxk.rmcp.api.enums.RmcpErrorEnum;
import com.zcxk.rmcp.api.enums.ValveStatusEnum;
import com.zcxk.rmcp.api.vo.DeviceAlarmVo;
import com.zcxk.rmcp.api.vo.DeviceVo;
import com.zcxk.rmcp.api.vo.DownloadAlarmVo;
import com.zcxk.rmcp.api.vo.DownloadDeviceVo;
import com.zcxk.rmcp.core.dao.DeviceAlarmMapper;
import com.zcxk.rmcp.web.service.DeviceAlarmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author linqingwei
 * @date 2021-08-10 15:44
 */
@Slf4j
@Service
public class DeviceAlarmServiceImpl implements DeviceAlarmService {

    @Resource
    private DeviceAlarmMapper deviceAlarmMapper;

    @Override
    public Pagination<DeviceAlarmVo> getPage(DeviceAlarmQueryDto dto, BasePageDto page) {
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<DeviceAlarmVo> list = deviceAlarmMapper.findList(dto, UserUtil.getCurrentUser().getUserCondition());
        return new Pagination<>(list);
    }

    @Override
    public void exportExcel(DeviceAlarmQueryDto dto, HttpServletResponse httpServletResponse) {
        try {
            List<DeviceAlarmVo> list = deviceAlarmMapper.findList(dto, UserUtil.getCurrentUser().getUserCondition());

            EasyExcelUtil.excelWrite(httpServletResponse, DownloadAlarmVo.class,"告警列表",convert(list));
        }catch (Exception e){
            throw BusinessException.builder(RmcpErrorEnum.RMCP_DOWNLOAD_ERROR);
        }
    }

    private List<DownloadAlarmVo> convert (List<DeviceAlarmVo> list){
        List<DownloadAlarmVo> results = new ArrayList<>();
        for (DeviceAlarmVo deviceAlarmVo : list) {
            DownloadAlarmVo vo = CglibUtil.copy(deviceAlarmVo,DownloadAlarmVo.class);
            vo.setDeviceTypeName(deviceAlarmVo.getManufacturerName()+"/"+deviceAlarmVo.getProductName()+"/"+deviceAlarmVo.getProductModel());
            results.add(vo);
        }
        return results;
    }
}
