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

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.hutool.system.SystemUtil;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.dto.SimulateResultDto;
import com.huatek.busi.entity.DataOutputEntitySimulation;
import com.huatek.busi.entity.DataOutputEntityWarning;
import com.huatek.busi.vo.warning.BusiEqmWarningTaskVo;
import com.huatek.busi.where.SimulateResultSelectVo;
import org.springframework.util.CollectionUtils;

import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.huatek.busi.common.SiteConstants.ArresterTreeEnum;
import com.huatek.busi.common.SiteConstants.GisTreeEnum;
import com.huatek.busi.common.SiteConstants.OtherTreeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.TransfromerTreeEnum;
import com.huatek.busi.common.ValueNamePair;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.entity.DataOutputEntity;
import com.huatek.busi.vo.dataoutput.OutputEquipmentVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 工具类
 * 
 * @author anker_cheng
 * @date 2019/10/12
 */
@Slf4j
public class DataOutputUtil {
    static final String FILE_EXT = ".xml";
    static final String PATTERN_DATE = "yyyyMMdd";
    static final String SPLITOR = "_";

    public static final String RUN_STATUS = "run_status";

    public static DataOutputEntity newEntity(OutputEquipmentVo vo, LocalDate day) {
//    String dateString = DateUtil.format(day, PATTERN_DATE);
  	String dateString = DateUtil.format(LocalDate.now(), PATTERN_DATE);
      DataOutputEntity entity = new DataOutputEntity();
      if(!RUN_STATUS.equals(vo.getEquipmentType()))
      {
      	  entity.setSiteId(vo.getSiteId());
            entity.setMainTreeId(vo.getMainTreeId());
            entity.setSubTreeId(vo.getSubTreeId());
//            entity.setDay(day);
            entity.setDay(LocalDate.now());
            entity.setDownloadTimes(0);
            entity.setCreatedTime(LocalDateTime.now());
            // if (StringUtils.isEmpty(vo.getEquipmentType())) {
            // entity.setFilePath(join("/", dateString, vo.getMainEquipmentType(), vo.getMainTreeId()));
            // } else {
            // entity.setFilePath(
            // join("/", dateString, vo.getMainEquipmentType(), vo.getMainTreeId(), vo.getEquipmentType()));
            // }
            entity.setFilePath(dateString);
//            entity
//                .setFileName(join(SPLITOR, DateUtil.getFormatDate(LocalDateTime.now()),vo.getMainEquipmentType(), vo.getEquipmentType(), vo.getSystemCode(), FILE_EXT));
            
            entity
            .setFileName(join(SPLITOR, dateString,vo.getMainEquipmentType(), vo.getEquipmentType(), vo.getSystemCode())+FILE_EXT);
            
            // 数据描述
            entity.setDataDesc(getDataDesc(vo.getMainEquipmentType(), vo.getEquipmentType()));	
            return entity;
      }
      else
      {
      	return null;
      }
     
  }

    public static DataOutputEntitySimulation newEntitySimulate(SimulateResultDto vo, LocalDate day) {
//      String dateString = DateUtil.format(day, PATTERN_DATE);
        String dateString = DateUtil.format(LocalDate.now(), PATTERN_DATE);
        DataOutputEntitySimulation entity = new DataOutputEntitySimulation();
        if(!RUN_STATUS.equals(vo.getEquipmentType()))
        {
//            entity.setDay(day);
            entity.setDay(LocalDate.now());
            entity.setMainId(vo.getMainId());
            entity.setPId(vo.getPId());
            entity.setDownloadTimes(0);
            entity.setCreatedTime(LocalDateTime.now());
            entity.setSimulateResultJson(vo.getSimulateResultJson());
            // if (StringUtils.isEmpty(vo.getEquipmentType())) {
            // entity.setFilePath(join("/", dateString, vo.getMainEquipmentType(), vo.getMainTreeId()));
            // } else {
            // entity.setFilePath(
            // join("/", dateString, vo.getMainEquipmentType(), vo.getMainTreeId(), vo.getEquipmentType()));
            // }
            entity.setFilePath(dateString);
//            entity
//                .setFileName(join(SPLITOR, DateUtil.getFormatDate(LocalDateTime.now()),vo.getMainEquipmentType(), vo.getEquipmentType(), vo.getSystemCode(), FILE_EXT));

            entity.setFileName(join(SPLITOR, dateString,vo.getPId(), vo.getEquipmentType(),vo.getFileName())+FILE_EXT);

            // 数据描述
            entity.setSimulateResultJson(getDataDesc(vo.getSimulateResultJson(), vo.getFilePath()));
            return entity;
        }
        else
        {
            return null;
        }

    }

    public static DataOutputEntityWarning newEntityWarning(BusiEqmWarningTaskVo vo, LocalDate day) {
//      String dateString = DateUtil.format(day, PATTERN_DATE);
        String dateString = DateUtil.format(LocalDate.now(), PATTERN_DATE);
        DataOutputEntityWarning entity = new DataOutputEntityWarning();
        if(!RUN_STATUS.equals(vo.getWarningId()))
        {
//            entity.setDay(day);
            entity.setDay(LocalDate.now());
            entity.setEqType(vo.getEqType());
            entity.setGzType(vo.getGzType());
            entity.setSensorInstallLocation(vo.getSensorInstallLocation());
            entity.setDownloadTimes(0);
            entity.setCreatedTime(LocalDateTime.now());
            entity.setWarningInfo(vo.getWarningInfo());
            entity.setSensorId(vo.getSensorId());
            entity.setWarningId(vo.getWarningId());
            // if (StringUtils.isEmpty(vo.getEquipmentType())) {
            // entity.setFilePath(join("/", dateString, vo.getMainEquipmentType(), vo.getMainTreeId()));
            // } else {
            // entity.setFilePath(
            // join("/", dateString, vo.getMainEquipmentType(), vo.getMainTreeId(), vo.getEquipmentType()));
            // }
            entity.setFilePath(dateString);
//            entity
//                .setFileName(join(SPLITOR, DateUtil.getFormatDate(LocalDateTime.now()),vo.getMainEquipmentType(), vo.getEquipmentType(), vo.getSystemCode(), FILE_EXT));

            entity.setFileName(join(SPLITOR, vo.getWarningTime(),vo.getSensorId(),vo.getEqType(),vo.getGzType())+FILE_EXT);

            // 数据描述
            return entity;
        }
        else
        {
            return null;
        }

    }

    public static Path createFile(String basePath, String filePath, String fileName) throws Exception {
        Path path = Paths.get(basePath, filePath);
        // 创建路径
        if (!Files.exists(path)) {
            Files.createDirectories(path);
            log.error("文件加夹路径：{}",path.toString());
            setPermission(path.toString());
        }
        // 文件
        path = Paths.get(basePath, filePath, fileName);
        if (Files.exists(path)) {
            Files.delete(path);
        }
        Files.createFile(path);
        log.error("文件路径：{}",path.toString());
        setPermission(path.toString());
        return path;
    }

    private static String join(String separator, Object... parts) {
        return Joiner.on(separator).skipNulls().join(parts);
    }
    public static void main(String[] args) {
    	String string = join(SPLITOR, DateUtil.getFormatDate(LocalDateTime.now()),"111","222", "333", FILE_EXT);
    	System.out.println(string);
    }
    private static String getDataDesc(String mainEquipmentType, String equipmentType) {
//        if (RUN_STATUS.equals(equipmentType)) {
//            return join("", SiteTreeEnum.BYQ_EQM.getName(), "运行工况数据");
//        }
        SiteTreeEnum siteTreeEnum = SiteTreeEnum.fromValue(mainEquipmentType);
        if (siteTreeEnum == SiteTreeEnum.CW_HL_EQM) {
            return join("", SiteTreeEnum.CW_HL_EQM.getName(), "测温数据");
        }
        List<ValueNamePair> valueNamePairs = null;
        if (siteTreeEnum == SiteTreeEnum.BYQ_EQM) {
            valueNamePairs = TransfromerTreeEnum.EQM_LIST;
        } else if (siteTreeEnum == SiteTreeEnum.GIS_HL_EQM) {
            valueNamePairs = GisTreeEnum.EQM_LIST;
        } else if (siteTreeEnum == SiteTreeEnum.BLQ_HL_EQM) {
            valueNamePairs = ArresterTreeEnum.EQM_LIST;
        } else if (siteTreeEnum == SiteTreeEnum.OTHER_EQM) {
            valueNamePairs = OtherTreeEnum.EQM_LIST;
        }  else if (siteTreeEnum == SiteTreeEnum.GEN_EQM) {
        valueNamePairs = SiteConstants.GeneratorTreeEnum.EQM_LIST;
        } else if (siteTreeEnum == SiteTreeEnum.DL_EQM) {
            valueNamePairs = SiteConstants.CableTreeEnum.EQM_LIST;
        }

        if (CollectionUtils.isEmpty(valueNamePairs)) {
            return null;
        }
        for (ValueNamePair pair : valueNamePairs) {
            if (Objects.equal(equipmentType, pair.getValue())) {
            	if("GIS".equals(siteTreeEnum.getName()))
            	{
            		 return join("", pair.getName(), "数据");
            	}
            	else
            	{
            		return join("", siteTreeEnum.getName(), pair.getName(), "数据");
            	}
            }
        }
        return null;
    }

    public synchronized static void deleteFile(String basePath, LocalDate day) {
        Path path = Paths.get(basePath, DateUtil.format(day, PATTERN_DATE));
        if (!Files.exists(path)) {
            log.debug("文件不存在： {}", path);
            return;
        }
        try {
            Files.walk(path).forEach(file -> {
                try {
                    Files.deleteIfExists(file);
                    log.debug("删除文件：{}", file.getFileName());
                } catch (IOException e1) {
                    log.error("删除文件：{}", file.getFileName());
                }
            });
            //删除文件夹
            Files.deleteIfExists(path);
            log.debug("删除文件夹：{}", path.getFileName());
        } catch (IOException e) {
            log.error("删除文件失败：{}", e.getMessage());
            if (log.isDebugEnabled()) {
                log.error(e.getMessage(), e);
            }
        }
    }

    public static void setPermission(String path) throws IOException {
        if (System.getProperty("os.name").toLowerCase().contains("linux")){
            Runtime.getRuntime().exec("chmod 777 " + path);
        //        Runtime.getRuntime().exec("chown ftpuser:user " + path);
        }
    }




}