package com.xhpc.charging.station.service;

import com.xhpc.charging.station.mapper.XhpcDownCodeMapper;
import com.xhpc.charging.station.utils.img.DownMaterialUtil;
import com.xhpc.common.core.web.service.BaseService;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.system.api.domain.SysUser;
import com.xhpc.system.api.model.LoginUser;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * program: ruoyi
 * User: HongYun
 * Date:2021-09-30 15
 */
@Service
public class XhpcDownCodeServiceImpl extends BaseService implements IXhpcDownCodeService {

    @Autowired
    private XhpcDownCodeMapper xhpcDownCodeMapper;

    @Autowired
    private Environment environment;
    @Autowired
    private TokenService tokenService;

    private static final Logger logger = LoggerFactory.getLogger(XhpcDownCodeServiceImpl.class);

    @Override
    public List<Map<String, Object>> listStations(String tenantId,Long operatorId,Long chargingStationId,String stationName) {
        LoginUser loginUser = tokenService.getLoginUser();
        List<Map<String, Object>> list =new ArrayList<>();
        SysUser sysUser = loginUser.getSysUser();

        Long sysUserId = sysUser.getUserId();
        if(!UserTypeUtil.SYS_USER_TYPE_ADMIN.equals(sysUser.getUserId())){
            startPage();
            if(UserTypeUtil.SYS_USER_TYPE_ONE.equals(sysUser.getUserType())){
                Long logOperatorId = sysUser.getOperatorId();
                //运营商看自己的场站
                list = xhpcDownCodeMapper.selectStationsBy(operatorId,chargingStationId,stationName,1,logOperatorId,tenantId);
            }else{
                //查询赋值的场站
                list = xhpcDownCodeMapper.selectStationsBy(operatorId,chargingStationId,stationName,2,sysUserId,tenantId);
            }
        }else{
            startPage();
            list = xhpcDownCodeMapper.selectStationsBy(operatorId,chargingStationId,stationName,0,sysUserId,tenantId);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> listPiles(Long stationId) {

        return xhpcDownCodeMapper.selectPilesBy(stationId);
    }

    @Override
    public String downMaterialBy(Long pileId) throws Exception {

        List<Map<String,Object>> list = xhpcDownCodeMapper.selectExcelDataByPileId(pileId);
        File file1 = new File(environment.getProperty("img.url"));
        File file2 = new File(file1, "pictures");
        if(file1.exists()){
            delFile(file1);
        }
        boolean flag = file1.mkdir();
        if(! flag) {
            System.out.println(file1.getName()+"文件夹创建失败！");
        }
        boolean flag1 = file2.mkdir();
        if(! flag1){
            System.out.println(file2.getName() + "文件夹创建失败");
        }
        //1、创建excel文档对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2、创建sheet页
        HSSFSheet sheet = workbook.createSheet("第一页");
        //3、创建头部第一行
        HSSFRow headRow = sheet.createRow(0);
        HSSFCell cell;
        String[] header = new String[]{"终端名称", "归属电站", "终端编码", "电桩编码", "终端类型(1直流（快） 2交流（慢)", "电桩功率(KM)", "二维码内容"};
        for (int i = 0; i < header.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellValue(header[i]);
        }
        //4、填写数据
        HSSFRow dataRow;
        HSSFCell dataCell;
        String[] values = {"tName", "sName", "tSN", "psn", "type", "power", "qrContent"};
        int valuesLength = values.length;
        for(int i = 1; i <= list.size(); i ++){
            Map<String,Object> map = list.get(i - 1);
            if(null != map) {
                if(map.get("qrContent") !=null){
                    map.put("qrContent",environment.getProperty("img.qrLinkContent")+map.get("qrContent").toString());
                }
                dataRow = sheet.createRow(i);
                for(int j = 0; j < valuesLength; j ++){
                    if(null != map.get(values[j])){
                        dataCell = dataRow.createCell(j);
                        String s = String.valueOf(map.get(values[j]));
                        if (j==4) {
                            if("1".equals(s)){
                                dataCell.setCellValue("直流");
                            }else{
                                dataCell.setCellValue("交流");
                            }
                        }else{
                            dataCell.setCellValue(s);
                        }
                    }
                }
            }
        }
        //5、写入
        OutputStream fos = new FileOutputStream(environment.getProperty("img.url") + "/data.xls");
        workbook.write(fos);
        workbook.close();
        fos.close();
        String imgPrefixUrl = environment.getProperty("img.imgPrefix");
        List<String> imgUrls = xhpcDownCodeMapper.selectUrlsByPile(pileId);
        List<String> fullImgUrlList = DownMaterialUtil.getDownLoadUrls(imgPrefixUrl, imgUrls);
        DownMaterialUtil.saveImageToDisk(fullImgUrlList, file2, imgUrls);
        File file = new File(environment.getProperty("img.url"));
        //储存路径
        long l = System.currentTimeMillis();
        String url = environment.getProperty("img.url") + l;

        DownMaterialUtil.fileToZip(file, url);

        return "QRcodeMaterial" + l + ".zip";
    }

    @Override
    public String downMaterialByStationId(Long stationId) throws Exception {

        //查找场站下方有图片的终端的相关的信息
        List<Map<String, Object>> list = xhpcDownCodeMapper.selectExcelDataByStationId(stationId);
        File file1 = new File(environment.getProperty("img.url"));
        File file2 = new File(file1, "pictures");
        if (file1.exists()) {
            delFile(file1);
        }
        boolean flag = file1.mkdir();
        if (!flag) {
            System.out.println(file1.getName() + "文件夹创建失败！");
        }
        boolean flag1 = file2.mkdir();
        if (!flag1) {
            System.out.println(file2.getName() + "文件夹创建失败");
        }
        //1、创建excel文档对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2、创建sheet页
        HSSFSheet sheet = workbook.createSheet("第一页");
        //3、创建头部第一行
        HSSFRow headRow = sheet.createRow(0);
        HSSFCell cell;
        String[] header = new String[]{"终端名称", "归属电站", "终端编码", "电桩编码", "终端类型(1直流（快） 2交流（慢)", "电桩功率(KM)", "二维码内容"};
        for (int i = 0; i < header.length; i++) {
            cell = headRow.createCell(i);
            cell.setCellValue(header[i]);
        }
        //4、填写数据
        HSSFRow dataRow;
        HSSFCell dataCell;
        String[] values = {"tName", "sName", "tSN", "psn", "type", "power", "qrContent"};
        int valuesLength = values.length;
        for (int i = 1; i <= list.size(); i++) {
            Map<String, Object> map = list.get(i - 1);
            if (null != map) {
                if(map.get("qrContent") !=null){
                    map.put("qrContent",environment.getProperty("img.qrLinkContent")+map.get("qrContent").toString());
                }
                dataRow = sheet.createRow(i);
                for (int j = 0; j < valuesLength; j++) {
                    if (null != map.get(values[j])) {
                        dataCell = dataRow.createCell(j);
                        String s = String.valueOf(map.get(values[j]));
                        if (j==4) {
                            if("1".equals(s)){
                                dataCell.setCellValue("直流");
                            }else{
                                dataCell.setCellValue("交流");
                            }
                        }else{
                            dataCell.setCellValue(s);
                        }
                    }
                }
            }
        }
        //5、写入
        OutputStream fos = new FileOutputStream(environment.getProperty("img.url") + "/data.xls");
        workbook.write(fos);
        workbook.close();
        fos.close();
        String imgPrefixUrl = environment.getProperty("img.imgPrefix");
        List<String> imgUrls = xhpcDownCodeMapper.selectUrlsByStation(stationId);
        List<String> fullImgUrlList = DownMaterialUtil.getDownLoadUrls(imgPrefixUrl, imgUrls);
        DownMaterialUtil.saveImageToDisk(fullImgUrlList, file2, imgUrls);
        File file = new File(environment.getProperty("img.url"));
        //储存路径
        long l = System.currentTimeMillis();
        String url = environment.getProperty("img.url") + l;

        DownMaterialUtil.fileToZip(file, url);

        return "QRcodeMaterial" + l + ".zip";
    }

    static boolean delFile(File file) {

        if (!file.exists()) {
            return false;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File f : files) {
                    delFile(f);
                }
            }
        }
        return file.delete();
    }
}
