package com.pqs9300.controller.technical;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.pqs9300.util.SocketSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.user.Depts;
import com.njcn.service.configuration.DeviceService;
import com.njcn.utils.PubUtils;
import com.pqs9300.pojo.technical.TechnicalInfo;
import com.pqs9300.pojo.transaction.OverRunLog;
import com.pqs9300.pojo.transaction.Supervise;
import com.pqs9300.service.formdata.FormDataService;
import com.pqs9300.service.technical.TechnicalInfoService;
import com.pqs9300.util.SocketSender;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("technical")
public class TechnicalInfoController {
    // 日志记录
    private static final Logger logger = LoggerFactory.getLogger(TechnicalInfoController.class);

    @Autowired
    private TechnicalInfoService technicalInfoService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private FormDataService formDataService;
    
    @Autowired
    private SocketSender socketSender;

    @RequestMapping(value = "getTechnicalInfo", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getTechnicalInfo(HttpServletRequest request, String startTime, String endTime, Integer supType, Integer progress) {
        HttpResult result = new HttpResult();
        List<TechnicalInfo> technicalInfos = new ArrayList<>();
        try {
            technicalInfos = technicalInfoService.getTechnicalInfo(startTime, endTime, progress, supType);
            result = PubUtils.assignmentResult(technicalInfos, 200, "获取数据成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取数据失败");
        }
        return result;
    }


    /**
     * 获取技术监督详情
     *
     * @param request
     * @param startTime
     * @param deptIndex
     * @return
     */
    @RequestMapping(value = "getTechnicalDetail", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getTechnicalDetail(HttpServletRequest request, String startTime, String deptIndex, Integer type) {
        HttpResult result = new HttpResult();
        List<OverRunLog> overRunLog = new ArrayList<>();

        try {
            Date start = PubUtils.string2Date(startTime, "yyyy-MM-dd");
            if (type == 0) {
                overRunLog = formDataService.getTechnicalDetail(deptIndex, start);
            } else {
                overRunLog = formDataService.getTechnicalDetail(deptIndex, start, 1);
            }
            result = PubUtils.assignmentResult(overRunLog, 200, "获取技术监督详情成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取技术监督详情失败");
        }
        return result;
    }

    /**
     * 保存技术监督详情
     *
     * @param request
     * @param startTime
     * @param deptIndex
     * @return
     */
    @RequestMapping(value = "saveTechnicalDetail", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult saveTechnicalDetail(HttpServletRequest request, String startTime, String deptIndex, Integer type, @RequestParam("indexs[]") List<String> indexs) {
        HttpResult result = new HttpResult();
        String supIndex="";
        try {
            Date start = PubUtils.string2Date(startTime, "yyyy-MM-dd");
            if (type == 0) {
            	supIndex=formDataService.saveOverRunLog(deptIndex, start, indexs);
            } else {
            	supIndex=formDataService.saveOverRunLog(deptIndex, start, indexs, 1);
            }
            socketSender.sendSocketMsg("生成"+supIndex+"技术单");
            result = PubUtils.assignmentResult("success", 200, "获取技术监督详情成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取技术监督详情失败");
        }
        return result;
    }

    /**
     * 修改技术监督详情
     *
     * @param request
     * @param startTime
     * @param deptIndex
     * @return
     */
    @RequestMapping(value = "modTechnicalDetail", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult modTechnicalDetail(HttpServletRequest request,String supIndex, String startTime, String deptIndex, Integer type, @RequestParam("indexs[]") List<String> indexs) {
        HttpResult result = new HttpResult();

        try {
            Date start = PubUtils.string2Date(startTime, "yyyy-MM-dd");
            if (type == 0) {
                formDataService.modOverRunLog(supIndex,deptIndex, start, indexs);
            } else {
                formDataService.modOverRunLog(supIndex,deptIndex, start, indexs, 1);
            }
            result = PubUtils.assignmentResult("success", 200, "获取技术监督详情成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取技术监督详情失败");
        }
        return result;
    }
    
    /**
     * 删除技术监督详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "delTechnical", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult delTechnical(HttpServletRequest request,String supIndex) {
        HttpResult result = new HttpResult();

        try {
            formDataService.delTechnical(supIndex);
            socketSender.sendSocketMsg("删除"+supIndex+"技术单");
            result = PubUtils.assignmentResult("success", 200, "删除技术监督成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "删除技术监督失败");
        }
        return result;
    }
    
    /**
     * 获取部门列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getDepts", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getDepts(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        List<Depts> depts = new ArrayList<>();

        try {
            depts = technicalInfoService.getDepts();
            result = PubUtils.assignmentResult(depts, 200, "获取部门列表成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取部门列表失败");
        }
        return result;
    }

    @PostMapping("getStartSwitch")
    @ResponseBody
    public HttpResult getStartSwitch(@RequestParam("index[]") List<String> index) {
        HttpResult result;
        if (CollectionUtils.isEmpty(index)) {
            result = PubUtils.assignmentResult(null, 500, "请选中需要开启的流程");
            return result;
        }
        try {
            int re = technicalInfoService.getStartSwitch(index);
            if (re == -1) {
                result = PubUtils.assignmentResult(re, 200, "启动成功");
            } else {
                result = PubUtils.assignmentResult(re, 500, "启动失败");
                socketSender.sendSocketMsg("开启"+index+"流程");
            }
            //下载前，清空备份
//            String item = "njcntemp/waveTemp9000";
//            FileUtil.clean(new File(appConfig.getTmppath() + item));
//            Map<String, List<String>> indexList = waveService.getEventDetailIndexList(index);
//            if (CollectionUtils.isEmpty(indexList)) {
//                result = PubUtils.assignmentResult(null, 500, "没有波形数据");
//            } else {
//                result = PubUtils.assignmentResult(indexList, 200, "波形数据准备完毕");
//                cache.set(TokenManager.getUserId() + TokenManager.getSysType() + "waveFiles9200", indexList);
//            }
        } catch (Exception e) {
            logger.error("后台获取数据出错，方法名为：downloadWave，异常为：" + e);
            result = PubUtils.assignmentResult(null, 500, "获取暂降事件数据出错，请联系管理员");
        }
        return result;
    }

    /**
     * 根据ID获取技术监督详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getTechnicalByID", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getTechnicalByID(HttpServletRequest request, String supIndex) {
        HttpResult result = new HttpResult();
        Supervise technical = new Supervise();

        try {
            technical = formDataService.getTechnicalByID(supIndex);
            result = PubUtils.assignmentResult(technical, 200, "获取技术监督详情成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取技术监督详情失败");
        }
        return result;
    }

    /**
     * 根据ID和越限时间获取越限指标
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getOptions", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getOptions(HttpServletRequest request, Long lineIndex, String time) {
        HttpResult result = new HttpResult();
        List<String> options = new ArrayList<>();

        try {
            Date start = PubUtils.string2Date(time, "yyyy-MM-dd");
            options = formDataService.getOptions(lineIndex, start);
            result = PubUtils.assignmentResult(options, 200, "获取越限指标成功");
        } catch (Exception e) {
            result = PubUtils.assignmentResult(null, 500, "获取越限指标失败");
        }
        return result;
    }

    /**
     * 获取接线方式
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getPttype", method = RequestMethod.POST)
    @ResponseBody
    public List<Integer> getPttype(HttpServletRequest request,String obj) {
        JSONArray json = JSONArray.fromObject(obj); //使用net.sf.json.JSONObject对象来解析json
        String points = (String) json.getJSONObject(0).get("point");
        String[] pointid = points.split(",");
        List<Integer> listw = new ArrayList<Integer>();
        int point;
        for (int i = 0; i < pointid.length; i++) {
            point = Integer.parseInt(pointid[i]);
            int pttype = deviceService.getConnect(Long.valueOf(point));
            listw.add(pttype);
        }
        return listw;
    }

    /**
     * @Author dhj
     * @Description 跳转技术监督
     * @Date 9:47 2020/7/14
     **/
    @GetMapping("/viewWave")
    public String ViewWave() {
        return "business/monitor/waveform";
    }

}
