package cn.iocoder.yudao.module.system.service.robot;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.module.system.controller.admin.robot.vo.RobotWarnCodeMappingPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.robot.vo.RobotWarnCodeMappingSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.robot.warn.RobotWarnCodeMappingVO;
import cn.iocoder.yudao.module.system.dal.dataobject.robot.RobotWarnCodeMappingDO;
import cn.iocoder.yudao.module.system.dal.mysql.robot.RobotWarnCodeMappingMapper;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.annotation.Validated;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.WARN_CODE_MAPPING_NOT_EXISTS;

/**
 * 机器人告警码值映射 Service 实现类
 *
 * @author 陈宾顺
 */
@Service
@Validated
@Slf4j
public class RobotWarnCodeMappingServiceImpl implements RobotWarnCodeMappingService {

    @Resource
    private RobotWarnCodeMappingMapper warnCodeMappingMapper;

    @Value("${map.file.warn-path}")
    private String warnUploadPath;

    @Override
    public Long createWarnCodeMapping(RobotWarnCodeMappingSaveReqVO createReqVO) {
        // 插入
        RobotWarnCodeMappingDO warnCodeMapping = BeanUtils.toBean(createReqVO, RobotWarnCodeMappingDO.class);
        warnCodeMappingMapper.insert(warnCodeMapping);
        // 返回
        return warnCodeMapping.getId();
    }

    @Override
    public void updateWarnCodeMapping(RobotWarnCodeMappingSaveReqVO updateReqVO) {
        // 校验存在
        validateWarnCodeMappingExists(updateReqVO.getId());
        // 更新
        RobotWarnCodeMappingDO updateObj = BeanUtils.toBean(updateReqVO, RobotWarnCodeMappingDO.class);
        warnCodeMappingMapper.updateById(updateObj);
    }

    @Override
    public void deleteWarnCodeMapping(Long id) {
        // 校验存在
        validateWarnCodeMappingExists(id);
        // 删除
        warnCodeMappingMapper.deleteById(id);
    }

    private void validateWarnCodeMappingExists(Long id) {
        if (warnCodeMappingMapper.selectById(id) == null) {
            throw exception(WARN_CODE_MAPPING_NOT_EXISTS);
        }
    }

    @Override
    public RobotWarnCodeMappingDO getWarnCodeMapping(Long id) {
        return warnCodeMappingMapper.selectById(id);
    }

    @Override
    public PageResult<RobotWarnCodeMappingDO> getWarnCodeMappingPage(RobotWarnCodeMappingPageReqVO pageReqVO) {
        return warnCodeMappingMapper.selectPage(pageReqVO);
    }

    /**
     * 机器人查询告警码值映射
     * @return
     */
    @Override
    public void agvQueryWarnCode(HttpServletResponse response) {
        List<RobotWarnCodeMappingVO> list = warnCodeMappingMapper.getAllWarnCodeList();
        if (ObjectUtil.isEmpty(list)) {
            return;
        }
        Map<String, RobotWarnCodeMappingVO> map = list.stream().collect(Collectors.toMap(RobotWarnCodeMappingVO::getWarnCode, Function.identity(), (v1, v2) -> v1));
        exportJson(response,map,"warn.json",warnUploadPath);
    }

    public void exportJson(HttpServletResponse response, Object obj, String fileName, String uploadPath) {
        try {
            String jsonString = JSON.toJSONString(obj,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteDateUseDateFormat);

            //String fullPath = "/" + fileName;
            File path = new File(uploadPath);
            if (!path.exists()) {
                path.mkdirs();
            }
            String fullPath = uploadPath + "/" + fileName;
            File file = new File(fullPath);

            Writer write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            write.write(jsonString);
            write.flush();
            write.close();

            FileInputStream fis = new FileInputStream(file);
            // force-download
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            response.setCharacterEncoding("utf-8");

            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fis.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            fis.close();
            os.close();
            boolean delete = file.delete();

//            return file;
        } catch (Exception e) {
            log.error("告警码值导出JSON文件失败");
        }
    }

}