package com.ruoyi.web.controller.shate;

import ch.qos.logback.core.pattern.color.MagentaCompositeConverter;
import com.mysql.cj.x.protobuf.MysqlxResultset;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.UrlFileUpload;
import com.ruoyi.common.utils.shate.PageUtils;
import com.ruoyi.system.domain_shate.*;
import com.ruoyi.system.service_shate.IDateUploadService;
import com.sun.jna.platform.win32.OaIdl;
import com.sun.jna.platform.win32.ShTypes;
import io.swagger.annotations.Api;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import oshi.driver.mac.net.NetStat;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: JinSheng Song
 * @Date: 2022/7/11 15:46
 */
@RestController
@RequestMapping(value = "/api/Upload", produces = "application/json;charset=UTF-8")
@Api(tags = "文件上传记录")

public class DateUploadController
{
    @Resource
    private IDateUploadService service;

    private  String FilePathName;

    private  String ExePathName;

    private  String FilePaths;


    @RequestMapping(value = "/SelectUpload",method = {RequestMethod.POST})
    public AjaxResult SelectUpload(@RequestBody paging paging)
    {
        String type1=paging.getType1().replace(" ","");
        String type=paging.getType().replace(" ","");
        String type2="";
        if (paging.getType2()!=null)
        {
            type2= paging.getType2().toUpperCase();
        }
        String date=paging.getUploadTime();
        String dateTime=paging.getDateTime();
        String name=paging.getType3();


        if ( name!=null && name!="")
        {
            if (name.equals("1"))
            {
                name="Medium%";
            }
            else if(name.equals("2"))
            {
                name="High%";
            }

        }
        List<DateUpload> Seeding= service.selectUpload(paging.getZone(),type.toUpperCase(), type1.toUpperCase(),
                type2,paging.getYear(),date,name,dateTime);
        pageVO vaue=new pageVO();
        List<?> value= PageUtils.getListPaging(Seeding,paging.getPageNum(),paging.getPageSize());
        vaue.setValue(value);
        vaue.setTotal(Seeding.size());
        return AjaxResult.success(vaue);
    }






    @RequestMapping(value = "/delUpload",method = {RequestMethod.POST})
    public AjaxResult DelUpload(@RequestBody UplodFile uplodFile)
    {

        return  delUploadFile(uplodFile.getId());
//        List<Integer> ids=uplodFile.getId();
//        Integer Seeding=0;
//       UploadFile file=new UploadFile();
//        for (int i=0; i<ids.size();i++)
//        {
//            DateUpload value= service.selectDel(ids.get(i));
//
//          String[] strs2=value.getFileName().split("\\_");
//
////           file.UploadFile1(strs2[1],value.getZone(),value.getDataTime());
//
//            Seeding= service.DelUpload(ids.get(i));
//            if (Seeding==0){return  AjaxResult.error("没有此id单据！"+ids.get(i));}
//        }
//
//        return AjaxResult.success(Seeding);

    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delUpload1",method = {RequestMethod.DELETE})
    public AjaxResult DelUpload1(@RequestParam("id") List<Integer> id)
    {
        List<Integer> ids=id;
        Integer Seeding=0;
        for (int i=0; i<ids.size();i++)
        {
            Seeding= service.DelUpload(ids.get(i));
            if (Seeding==0){return  AjaxResult.error("没有此id单据！"+ids.get(i));}
        }
        return AjaxResult.success(Seeding);

    }


    /**
     * 添加
     * @param uplodFile
     * @return
     */
    @RequestMapping(value = "/InitUpload",method = {RequestMethod.POST})
    public AjaxResult InitUpload(@RequestBody UplodFile uplodFile)
    {

        readXml();

        List<DateUpload> dateUploads=infr(uplodFile.getDateUploads());

        for (int i=0; i<dateUploads.size();i++)
        {
            Integer Seeding= service.IntoUpload(dateUploads.get(i));

        }

        return AjaxResult.success("成功");
    }

    /**
     * 解析添加实体类
     * @param dateUpload
     * @return
     */
    private  List<DateUpload> infr(List<DateUpload> dateUpload)
    {
        for (int i=0;i<dateUpload.size();i++)
        {

            String [] typesList=dateUpload.get(i).getType1().split("\\/");

            String type1=typesList[1].replace(" ","").toUpperCase();

            String type=typesList[0].replace(" ","").toUpperCase();


            Date d=new Date();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            String dateNowStr = sdf.format(d);
             if(type1.equals("EVALUATIONINDICATORS"))
            {
                String[] strs = dateUpload.get(i).getFileName().split("\\.");

                String name=strs[0];

                String[] strs2=name.split("\\_");

                String[] typeValue=name.split("2");

                String type2=typeValue[0];

                String name1=strs2[strs2.length-1];

                String name2=strs2[strs2.length-2];

                dateUpload.get(i).setDataTime(name2);

                dateUpload.get(i).setZone(name1);

                dateUpload.get(i).setCreatedTime(dateNowStr);

                dateUpload.get(i).setType(type);

                dateUpload.get(i).setType1(type1);

                dateUpload.get(i).setYear(name2.substring(0,4));

                dateUpload.get(i).setType2(type2.substring(0,type2.length()-1).toUpperCase());

                dateUpload.get(i).setExtent1(dateUpload.get(i).getExtent().toString());

                DateUpload uploadValue=service.selectShp(name1,type,"");
                MyThread1 demo=new MyThread1(name.replace(".tif",""),
                        dateUpload.get(i).getRoute(),
                        uploadValue.getRoute());
                demo.run();

            }
            else if(type1.equals("LANDUSE"))
            {
                String[] strs = dateUpload.get(i).getFileName().split("\\.");

                String name=strs[0];

                String[] strs2=name.split("\\_");

                String[] typeValue=name.split("2");

                String type2=typeValue[0];

                String name1=strs2[strs2.length-1];

                String name2=strs2[strs2.length-2];

                dateUpload.get(i).setDataTime(name2);

                dateUpload.get(i).setZone(name1);

                dateUpload.get(i).setCreatedTime(dateNowStr);

                dateUpload.get(i).setType(type);

                dateUpload.get(i).setType1(type1);

                dateUpload.get(i).setYear(name2.substring(0,4));

                dateUpload.get(i).setType2(type2.substring(0,type2.length()-1).toUpperCase());

                dateUpload.get(i).setExtent1(dateUpload.get(i).getExtent().toString());

                DateUpload uploadValue=service.selectShp(name1,type,"");
                MyThread1 demo=new MyThread1(name.replace(".tif",""),
                        dateUpload.get(i).getRoute(),
                        uploadValue.getRoute());
                demo.run();

            }
             else if(type1.equals("SUITABILITY"))
             {
                 String[] strs = dateUpload.get(i).getFileName().split("\\.");

                 String name=strs[0];

                 String[] strs2=name.split("\\_");

                 String[] typeValue=name.split("2");

                 String type2=typeValue[0];

                 String name1=strs2[strs2.length-1];

                 String name2=strs2[strs2.length-2];

                 dateUpload.get(i).setDataTime(name2);

                 dateUpload.get(i).setZone(name1);

                 dateUpload.get(i).setCreatedTime(dateNowStr);

                 dateUpload.get(i).setType(type);

                 dateUpload.get(i).setType1(type1);

                 dateUpload.get(i).setYear(name2.substring(0,4));

                 dateUpload.get(i).setType2(type2.substring(0,type2.length()-1).toUpperCase());

                 dateUpload.get(i).setExtent1(dateUpload.get(i).getExtent().toString());

                 DateUpload uploadValue=service.selectShp(name1,type,"");

                 MyThread1 demo=new MyThread1(name.replace(".tif",""),
                         dateUpload.get(i).getRoute(),
                         uploadValue.getRoute());
                 demo.run();
             }
             else if(type1.equals("BOUNDARIES"))//Boundaries
             {
                 String[] strs = dateUpload.get(i).getFileName().split("\\.");

                 String name=strs[0];

                 String[] strs2=name.split("\\_");

                 String name1=strs2[strs2.length-1];

                 dateUpload.get(i).setZone(name1);

                 dateUpload.get(i).setCreatedTime(dateNowStr);

                 dateUpload.get(i).setYear(dateNowStr.substring(0,4));

                 dateUpload.get(i).setType(type);

                 dateUpload.get(i).setType1(type1);


                 dateUpload.get(i).setExtent1(dateUpload.get(i).getExtent().toString());

             }
            else
            {
                String[] strs = dateUpload.get(i).getFileName().split("\\.");

                String name=strs[0];

                String[] strs2=name.split("\\_");

                String name1=strs2[strs2.length-1];

                String name2=strs2[strs2.length-2];

                dateUpload.get(i).setDataTime(name2);

                Integer month=Integer.parseInt(name2.substring(4,6));

                dateUpload.get(i).setYear(name2.substring(0,4));

                dateUpload.get(i).setMonth(month);

                dateUpload.get(i).setZone(name1);

                dateUpload.get(i).setCreatedTime(dateNowStr);

                dateUpload.get(i).setType(type);

                dateUpload.get(i).setType1(type1);

                dateUpload.get(i).setExtent1(dateUpload.get(i).getExtent().toString());


                DateUpload uploadValue=service.selectShp(name1,type,"");
                MyThread1 demo=new MyThread1(name.replace(".tif",""),
                        dateUpload.get(i).getRoute(),
                        uploadValue.getRoute());
                demo.run();

            }

        }
        return  dateUpload;
    }

    /**
     * 调用exe
     * @param fileName 文件名称
     * @param filePath tif文件路径
     * @param shpPath shp文件路径
     */
    @RequestMapping(value = "/callExe",method = {RequestMethod.GET})
    public  void callExe(String fileName,String filePath,String shpPath)
    {
        BufferedReader bufferedReader=null;
        Process proc=null;
        try {

            String til = UrlFileUpload.fileUpload(filePath,FilePathName);

            String shp = UrlFileUpload.fileUpload(shpPath,FilePathName);

            String[] cmd = {ExePathName,
                    fileName,
                    til.replace("\\","/"),
                    shp.replace("\\","/")};
            System.out.println("调用exe执行算法");
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(cmd);
            proc=pb.start();
            bufferedReader =new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String aa=null;
            String line=null;
            while ((line=bufferedReader.readLine())!=null){
                aa=aa+line;
            }
//            打印错误日志
            System.out.println(aa);
//            Process process=Runtime.getRuntime().exec("cmd /c start"+" E:\\沙特\\~\\exe\\后台统计分析.exe \"Seed_Success_20220604_01\" \"E:\\沙特\\~\\temp\\Seed_Success_20220604_01.tif\" \"E:\\沙特\\~\\temp\\Seed_01.zip\"");


        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行地图数据解析
     */
    public class MyThread1 extends Thread{

        private String FileName;

        private String FilePath;

        private String ShpPath;

        public MyThread1(String fileName,String filePath,String shpPath){
            this.FileName = fileName;
            this.FilePath = filePath;
            this.ShpPath = shpPath;

        }
        @Override
        public void run(){
            callExe(FileName,FilePath,ShpPath);
        }
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "/delUploadFile",method = {RequestMethod.DELETE})
    public   AjaxResult delUploadFile(List<Integer> id) {


        List<Integer> ids = id;

        UploadFile file = new UploadFile();


        for (int i = 0; i < ids.size(); i++) {

            Integer Seeding=0;
            DateUpload value = service.selectDel(ids.get(i));

            String type1=value.getType1();
            String type= value.getType();

            if (type1.equals("EVALUATIONINDICATORS")) {

                //value.getType2();

                String[] typeValue = value.getFileName().split("2");
                String type2 = typeValue[0];
                type2=type2.substring(0,type2.length()-1);
                file.UploadFile1(type2, value.getZone(), value.getDataTime(),service,"");
                Seeding= service.DelUpload(ids.get(i));
                if (Seeding==0){return  AjaxResult.error("没有此id单据！"+ids.get(i));}

            }
            // &&
            //                    (type1.equals("RSIMAGES") || type1.equals("PLANTINGDISTRIBUTION") || type1.equals("VEGETATIONHEALTH"))
            else if (type.equals("VEGETATIONHEALTH"))
            {
                String[] typeValue = value.getFileName().split("_");
                String resolution=typeValue[0];
                String type2 = "Healthy";
                file.UploadFile1(type2, value.getZone(), value.getDataTime(),service,resolution);
                Seeding= service.DelUpload(ids.get(i));
                if (Seeding==0){return  AjaxResult.error("没有此id单据！"+ids.get(i));}
            }
            else
            {

                String[] typeValue = value.getFileName().split("_");
                String type2 = typeValue[0];
                file.UploadFile1(type2, value.getZone(), value.getDataTime(),service,"");
                Seeding= service.DelUpload(ids.get(i));
                if (Seeding==0){return  AjaxResult.error("没有此id单据！"+ids.get(i));}
            }

        }

        return AjaxResult.success("成功！");
    }


    public  void readXml() {
        try {
            // 创建解析器工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            // 创建一个Document对象
            String parent = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParentFile().getParent();
            File file = new File("route.xml");
            Document doc =db.parse(file);
            NodeList routeList = doc.getElementsByTagName("Rodel");
            // 遍历每个book节点
            for (int i = 0; i < routeList.getLength(); i++) {
                System.out.println("*******************************");
                // 索引从零开始
                org.w3c.dom.Node book = routeList.item(i);
                // 获取book节点所有属性集合
                org.w3c.dom.NamedNodeMap attrs = book.getAttributes();


                NodeList childNodes = book.getChildNodes();
                for (int k = 0; k < childNodes.getLength(); k++) {
                    // 区分,去掉空格和换行符
                    if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {


                        this.ExePathName=childNodes.item(1).getTextContent().trim();

                        this.FilePathName=childNodes.item(3).getTextContent().trim();

                        this.FilePaths=childNodes.item(5).getTextContent().trim();
                    }
                }
            }



        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
