package com.miyzh.controller;

import com.alibaba.fastjson.JSONObject;
import com.miyzh.entity.UploadExceptionLog;
import com.miyzh.service.UploadService;
import com.miyzh.service.WebSocketService;
import com.miyzh.utils.CsvUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Slf4j
@Controller
@RequestMapping("upload")
public class UploadController {
    @Autowired
    private UploadService uploadService;

    @Autowired
    private WebSocketService webSocketService;

    @Value(value = "${scheduling.rootDir}")
    private String rootDir;

    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        request.setAttribute("name", "111");
        return "index";
    }

    @RequestMapping("/upload")
    public String toIndex(){
        return "upload";
    }

    @RequestMapping("/runservice")
    @ResponseBody
    public String runservice(@RequestBody String param){
        UploadExceptionLog uploadExceptionLog = new UploadExceptionLog();
        uploadExceptionLog.setUploadInfo(param);
        return uploadService.runservice(uploadExceptionLog);
    }

    @RequestMapping("/searchBySerialNo")
    @ResponseBody
    public String searchBySerialNo(@RequestParam String serialNo){
        return uploadService.searchBySerialNo(serialNo);
    }

    @RequestMapping("/searchDocBySerialNo")
    @ResponseBody
    public String searchDocBySerialNo(@RequestParam String serialNo){
        return uploadService.searchDocBySerialNo(serialNo);
    }

    @RequestMapping("/searchErrBySerialNo")
    @ResponseBody
    public String searchErrBySerialNo(@RequestParam String serialNo){
        return uploadService.searchErrBySerialNo(serialNo);
    }

    @RequestMapping("/retryUpload")
    @ResponseBody
    public Integer retryUpload(){
        return uploadService.retryUpload();
    }


    @RequestMapping("/init")
    @ResponseBody
    public String init(){
        return JSONObject.toJSONString(uploadService.init());
    }

    @RequestMapping("/initY")
    @ResponseBody
    public String initY(){
        return JSONObject.toJSONString(uploadService.initY());
    }

    @RequestMapping("/uploadByFile")
    @ResponseBody
    public Integer uploadByFile(String[] fileNames, String sid){
        System.out.println(System.currentTimeMillis());
        final CountDownLatch latch = new CountDownLatch(fileNames.length);
//        Session session = webSocketService.generateSession(sid);
        List <Integer> count = new ArrayList<>();
        for(String fileName : fileNames) {
            new Thread(() -> {
                List<String> result = CsvUtil.readCsv(rootDir, fileName);
                    for(String s : result) {
                        try {
                            UploadExceptionLog uploadExceptionLog = new UploadExceptionLog();
                            Document doc = DocumentHelper.parseText(s);
                            log.info(doc.getRootElement().element("SERIAL_NUMBER").getTextTrim());
                            uploadExceptionLog.setClinicNo(doc.getRootElement().element("YLJGDM").getTextTrim());
                            uploadExceptionLog.setUploadInfo(s);
                            uploadService.runservice(uploadExceptionLog);
                            count.add(result.size());
                            latch.countDown();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
        }
        try{
            latch.await();
            int result = count.stream().reduce(Integer::sum).orElse(0);
            System.out.println(count);
            System.out.println(System.currentTimeMillis());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
//        try{
//            webSocketService.sendMessage(session, "上传结束");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }




}
