package com.huatek.busi.service.impl.dataoutput.impls;

import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.huatek.busi.dto.SimulateResultDto;
import com.huatek.busi.entity.DataOutputEntityWarning;
import com.huatek.busi.init.SftpInit;
import com.huatek.busi.service.ISimulateResultService;
import com.huatek.busi.service.WarningResultService;
import com.huatek.busi.service.cac.CacEtlFactoryService;
import com.huatek.busi.service.dataoutput.DataOutputSimulateExecutor;
import com.huatek.busi.service.dataoutput.DataOutputWarningExecutor;
import com.huatek.busi.service.pointtable.PointTableEtlFactoryService;
import com.huatek.busi.service.transformer.TransformerRunStatusService;
import com.huatek.busi.vo.warning.BusiEqmWarningTaskVo;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * 数据输出接口抽象实现
 * 
 * @author anker_cheng
 * @date 2019/10/14
 */
public abstract class AbstractDataWarningOutputExecutor implements DataOutputWarningExecutor {
    static final String PART_START = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

    static String PART_ONE =
        "<output><body><equipinfo><id>%s</id><equipmentName>%s</equipmentName><cheatingName>%s</cheatingName><sensorId>%s</sensorId><warningTime>%s</warningTime><SensorInstallLocation>%s</SensorInstallLocation><WarningInfo>%s</WarningInfo><faultMessage>%s</faultMessage></equipinfo><day>%s</day></body></output>";

    static String PART_END = "</body></output>";


    static final Joiner JOINER = Joiner.on("").skipNulls();
    @Resource
    private SftpInit sftpInit;
    @Value("${warning.base.path}")
    private String baseFTP;
    @Autowired
    private WarningResultService warningResultService;
    @Autowired
    protected CacEtlFactoryService<?> cacEtlFactoryService;
    @Autowired
    protected TransformerRunStatusService transformerRunStatusService;
    @Autowired
    protected PointTableEtlFactoryService pointTableEtlFactoryService;

    @Override
    public void execute(Path path, BusiEqmWarningTaskVo vo, LocalDate day, String fileName) throws Exception {
        Map<String, Object> params = getParams(vo, day);
        List<Map<String, Object>> dataList = queryDataList(params);

        OutputStream opt = Files.newOutputStream(path);
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(opt, StandardCharsets.UTF_8))) {
            writer.append(PART_START);
            writer.append(String.format(PART_ONE, vo.getId(), vo.getEqType(), vo.getGzType(),vo.getSensorId(),vo.getWarningTime(),vo.getSensorInstallLocation(),vo.getWarningInfo(),vo.getThreeRatio(),day.toString()));
            if (!CollectionUtils.isEmpty(dataList)) {
                List<String> keys = getKeys();
                for (Map<String, Object> item : dataList) {
                    writer.append("<item>");
                    for (String key : keys) {
                        writer.append(String.format("<attr name=\"%s\" value=\"%s\"/>", key));
                    }
                    writer.append("</item>");
                }
            }
            writer.append(PART_END);
            String filePaths =String.format(PART_ONE, vo.getId(), vo.getEqType(), vo.getGzType(),vo.getSensorId(),vo.getWarningTime(),vo.getSensorInstallLocation(),vo.getWarningInfo(),vo.getThreeRatio(),day.toString());
            byte [] bytes = filePaths.getBytes();
            String status = "warningXml";
            int count = 1;
            String rootPath = baseFTP;
            InputStream inputStream = new ByteArrayInputStream(bytes);
            MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
            file.getInputStream();
            sftpInit.upload(rootPath,baseFTP,file.getInputStream(),fileName,count,status);
        }
    }
    
    /**
     * 数据输出只取最新一条数据
     * @param vo
     * @param day
     * @return
     */
    protected Map<String, Object> getParams(BusiEqmWarningTaskVo vo, LocalDate day) {
//        String date = day.toString();
        Map<String, Object> params = Maps.newLinkedHashMap();
        params.put("warningId", vo.getWarningId());
//        params.put("pId", vo.getPId());
//        params.put("timeStamp", date);
//        params.put("timeStampEnd", date);
//        params.put("page", "1");
//        params.put("limit", "1");
        return params;
    }

    protected List<String> getKeys() {
        return Collections.emptyList();
    }


    @SuppressWarnings("unchecked")
    protected List<Map<String, Object>> queryDataList(Map<String, Object> params) {
        Map<String, Object> result = null;
        if (!StringUtils.isEmpty(params.get("cacMonitorTypeCode"))) {
//            result = cacEtlFactoryService.findCACPageData(params);
            result = warningResultService.warningEqm(params);
        }

        return (List<Map<String, Object>>)result.get("data");
    }


}
