package com.ho.business.controller;

import com.alibaba.excel.EasyExcel;
import com.ho.business.constant.FileTypeConstant;
import com.ho.business.entity.DeviceTypeCol;
import com.ho.business.service.DeviceTypeColService;
import com.ho.business.vo.req.DeviceTypeColImportVO;
import com.ho.business.vo.req.deviceModel.SynchronousReqVo;
import com.ho.business.vo.req.deviceTypeCol.DeviceTypeColQueryVo;
import com.ho.business.vo.resp.DeviceTypeColExportVO;
import com.ho.business.vo.resp.DeviceTypeColRespVO;
import com.ho.common.tools.annotation.LogAnnotation;
import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.constant.ContextConstant;
import com.ho.common.tools.constant.DefineConstant;
import com.ho.common.tools.constant.RedisKeyConstant;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.common.tools.exception.DataResult;
import com.ho.common.tools.service.RedisService;
import com.ho.common.tools.util.EasyExcelUtil;
import com.ho.common.tools.util.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description device_type_col相关数据操作
 * @Author : xueweizhi
 * @Date : 2023/3/16 14:09
 */
@RestController
@RequestMapping(ContextConstant.BUSINESS + "deviceTypeCol")
@Api(tags = "点表数据操作")
@Slf4j
public class DeviceTypeColController {

    @Autowired
    DeviceTypeColService deviceTypeColService;

    @Autowired
    RedisService redisService;

    /**
     * 读取excel文件
     *
     * @param file
     */
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入点表数据")
    @LogAnnotation(title = "点表数据操作", action = "导入电表数据")
    public DataResult importExcel(@RequestBody MultipartFile file, HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader(RedisKeyConstant.User.ACCESS_TOKEN);
        SimpleUser user = redisService.getSimpleUserByToken(token);
        String msg = null;
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.lastIndexOf(".") != -1) {
            extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            extension = extension.toLowerCase();
        }
        if (!FileTypeConstant.XLS.equals(extension)) {
            throw new BusinessException(BaseResponseCode.FILE_FORMAT_ONLY);
        }
        try {
            List<DeviceTypeColImportVO> list = EasyExcel.read(file.getInputStream()).head(DeviceTypeColImportVO.class).sheet().doReadSync();
            int len = list.size();
            DeviceTypeColImportVO deviceTypeCol = null;
            Map<String, DeviceTypeColImportVO> map = new HashMap<>();
            for (int i = 0; i < len; i++) {
                deviceTypeCol = list.get(i);
                if (!CommonConstant.ONE.equals(deviceTypeCol.getIsSave()) && !CommonConstant.ZERO.equals(deviceTypeCol.getIsSave())) {
                    log.info("导入模板是否可写,第{}行填值错误填值错误，只能是0或1，{}", (i + 1), deviceTypeCol.getIsSave());
//                    msg = "导入模板是否可写,第" + (i + 1) + "行填值错误，只能是0或1";
                    msg = DefineConstant.DeviceTypeCol.IMPORT_VALUE_DEVICETYPECOL_CHECK1 + (i + 1) + DefineConstant.DeviceTypeCol.IMPORT_VALUE_DEVICETYPECOL_CHECK2;
                    break;
                }
                if (deviceTypeCol.getMaxValue() == null || deviceTypeCol.getMinValue() == null) {
                    log.info("导入模板最大值最小值,第{}行填值错误，maxValue:{},minValue:{}", (i + 1), deviceTypeCol.getMaxValue(), deviceTypeCol.getMinValue());
//                    msg = "导入模板最大值最小值,第" + (i + 1) + "行填值错误，不能为空";
                    msg = DefineConstant.DeviceTypeCol.IMPORT_VALUE_MAXVALUE_CHECK1 + (i + 1) + DefineConstant.DeviceTypeCol.IMPORT_VALUE_MAXVALUE_CHECK2;
                    break;
                }
                if (CommonConstant.THREE.equals(deviceTypeCol.getSensType()) || CommonConstant.ONE.equals(deviceTypeCol.getSensType())) {
                    if (BigDecimal.ONE.compareTo(deviceTypeCol.getMaxValue()) != 0 || BigDecimal.ZERO.compareTo(deviceTypeCol.getMinValue()) != 0) {
                        log.info("导入模板最大值最小值,第{}行填值错误，遥控最大值只能填写1,最小值只能填0，maxValue:{},minValue:{}", (i + 1), deviceTypeCol.getMaxValue(), deviceTypeCol.getMinValue());
//                        msg = "导入模板最大值最小值,第" + (i + 1) + "行填值错误，遥控最大值只能填写1,最小值只能填0";
                        msg = DefineConstant.DeviceTypeCol.IMPORT_VALUE_SENSTYPE_CHECK1 + (i + 1) + DefineConstant.DeviceTypeCol.IMPORT_VALUE_SENSTYPE_CHECK2;
                        break;
                    }
                }
                if (map.get(deviceTypeCol.getDeviceType() + "_" + deviceTypeCol.getCol()) != null) {
//                    msg = "导入模板第" + (i + 1) + "行填值错误，已存类型为" + deviceTypeCol.getDeviceType() + "且字段key为" + deviceTypeCol.getCol() + "的值";
                    msg = DefineConstant.DeviceTypeCol.IMPORT_VALUE_DEVICETYPE_CHECK1 + (i + 1) + DefineConstant.DeviceTypeCol.IMPORT_VALUE_DEVICETYPE_CHECK2 + deviceTypeCol.getDeviceType() + DefineConstant.DeviceTypeCol.IMPORT_VALUE_DEVICETYPE_CHECK3 + deviceTypeCol.getCol() + DefineConstant.DeviceTypeCol.IMPORT_VALUE_DEVICETYPE_CHECK4;
                    break;
                }
                map.put(deviceTypeCol.getDeviceType() + "_" + deviceTypeCol.getCol(), deviceTypeCol);
            }
            if (null == msg) {
                int count = deviceTypeColService.insertList(list,user.getGroupId());
            } else {
                throw new BusinessException(BaseResponseCode.SJEKK_EXCEL_DATA.getCode(), msg);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            if (msg != null) {
                throw new BusinessException(BaseResponseCode.SJEKK_EXCEL_DATA.getCode(), msg);
            }
            throw new BusinessException(BaseResponseCode.SJEKK_EXCEL_DATA);
        }
        return DataResult.success();
    }

    /**
     * 导出点表数据
     *
     * @param response
     */
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出点表数据")
    @LogAnnotation(title = "点表数据操作", action = "导出电表数据")
    public void exportExcel(@RequestBody DeviceTypeColRespVO deviceTypeColRespVO, HttpServletResponse response) {
        List<DeviceTypeCol> deviceList = deviceTypeColService.selectByDeviceType(deviceTypeColRespVO.getDeviceType(),null);
        String fileName = "点表";
        String sheetName = "点表数据";
        try {
            List<DeviceTypeColExportVO> exportList = new ArrayList<>();
            DeviceTypeColExportVO deviceTypeColExportVO = null;
            for (DeviceTypeCol typeCol : deviceList) {
                deviceTypeColExportVO = new DeviceTypeColExportVO();
                BeanUtils.copyProperties(typeCol, deviceTypeColExportVO);
                exportList.add(deviceTypeColExportVO);
            }
            EasyExcelUtil.writeExcel(response, exportList, fileName, sheetName, DeviceTypeColExportVO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("exportTemplate")
    @ApiOperation(value = "导出模板")
    @LogAnnotation(title = "点表数据操作", action = "导出模板")
    public void exportTemplate(HttpServletResponse response) {
        ServletOutputStream out = null;
        try {
            String fileName = URLEncoder.encode("deviceTypeColTemplate.xls", "utf-8");
            InputStream fis = getResourcesFileInputStream("template/deviceTypeColTemplate.xls");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            out = response.getOutputStream();
            out.write(buffer);
        } catch (Exception ex) {
            log.error("下载失败,{}", ex.getMessage());
        } finally {
            try {
                assert out != null;
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 导出模板
    private static InputStream getResourcesFileInputStream(String fileName) {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    }

    @PostMapping("/page")
    @ApiOperation(value = "分页查询点表数据")
    public DataResult<PageResult<DeviceTypeCol>> page(@RequestBody DeviceTypeColQueryVo vo) {
        PageResult<DeviceTypeCol> deviceTypeColPageResult = deviceTypeColService.selectPage(vo);
        return DataResult.success(deviceTypeColPageResult);
    }

    @PostMapping("/syPointTable")
    @ApiOperation(value = "一键同步点表")
    @LogAnnotation(title = "业务模块-点表数据操作", action = "一键同步点表功能")
    public DataResult syPointTable(@RequestBody SynchronousReqVo vo) {
        deviceTypeColService.syPointTable(vo);
        return DataResult.success();
    }
}
