package jtznyj.engineer.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.proxy.jdbc.NClobProxyImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jtznyj.common.api.ICommonApi;
import jtznyj.engineer.entity.BWellOwnEngineer;
import jtznyj.engineer.service.IWellDataDiagnosticService;
import jtznyj.engineer.service.dataDiagnosticService.data.DrillState;
import jtznyj.engineer.service.dataDiagnosticService.data.MonitorAlarmRanges;
import jtznyj.engineer.vo.LtdRecord;
import jtznyj.engineer.service.winform.CheckEngineerWarning;
import jtznyj.engineer.service.winform.data.MonitorAlarmRecord;
import jtznyj.engineer.service.winform.data.MonitorAlarmRecords;
import jtznyj.engineer.service.winform.data.RecordHashTable;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/engineer/logic")
@Slf4j
public class LogicController {
    @Autowired
    ICommonApi iCommonApi;

    @Autowired
    IWellDataDiagnosticService wellDataDiagnosticService;

    @Deprecated
    @RequestMapping(value = "/analyse", method = RequestMethod.GET)
    public Result<?> getaAnalyseResult(String jh, String ltdTime, HttpServletRequest req) throws ParseException {
//        List<Map<String, Object>> list = iCommonApi.queryDefaultEngineerLogic();
//        BWellOwnEngineer template = new BWellOwnEngineer();
//        if (list.size() > 0) {
//            template.setLargeText(GetNClob(list.get(0).get("LARGETEXT")));
//        } else {
//            list = iCommonApi.queryWellEngineerLogic(jh);
//            template.setLargeText(GetNClob(list.get(0).get("LARGETEXT")));
//        }
//
//        CheckEngineerWarning checkLogic = new CheckEngineerWarning(template);
//        MonitorAlarmRecords monitorAlarmRecords = new MonitorAlarmRecords();
//        DrillState ds = DrillState.None;
//
//        Date ltdTimeValue = DateUtils.parseDate(ltdTime, new String[]{"yyyy-MM-dd HH:mm:ss"});
//        List<LtdRecord> ltdList = iCommonApi.queryLtdListInPeriod(jh, ltdTimeValue, -30);
//        List<RecordHashTable> dataList = ltdList.stream().map(x -> CheckEngineerWarning.LtdToRecordHashTable(x)).collect(Collectors.toList());
//        ltdList.clear();
//        //诊断分析
//        checkLogic.AnalyseDataList(dataList, monitorAlarmRecords);
//        for (LtdRecord item : ltdList) {
//            RecordHashTable recordHashTable = CheckEngineerWarning.LtdToRecordHashTable(item);
//            HashMap<String, Object> rv = checkLogic.Analyse(recordHashTable,monitorAlarmRecords, ds);
//            ds = (DrillState) rv.get("ds");
//        }
//        for (int i = 0; i < monitorAlarmRecords.size(); i++) {
//            MonitorAlarmRecord r = monitorAlarmRecords.get(i);
//            r.SetAlarmMsg(i + 1, jh);
//        }
//
//        Result<MonitorAlarmRecords> result = new Result<>();
////        result.setResult(monitorAlarmRecords);
//
        Result<String> result = new Result<>();
        result.setResult("obsolete");

        return result;
    }

    private String GetNClob(Object src) {
        String result = "";
        if (src instanceof NClobProxyImpl) {
            try {
                result = ((NClobProxyImpl) src).getSubString(1, (int) ((NClobProxyImpl) src).length());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 预警诊断
     *
     * @param jh        诊断井号
     * @param startTime
     * @return 返回null 表示没未找到诊断配置参数
     */
    @GetMapping("/test")
    public Object EngineerWarn(String jh, @RequestParam(required = false, defaultValue = "") String startTime,
                               @RequestParam(required = false, defaultValue = "10") int durationInMinute) {
        Date date = new Date();
        if (StringUtils.isNotEmpty(startTime)) {
            try {
                date = org.jeecg.common.util.DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm:ss");
            } catch (ParseException e) {
            }
        }

        //监控预警记录--检查出的异常记录集
        Map<String, MonitorAlarmRanges> monitorAlarmRangeMap = wellDataDiagnosticService.test(jh, date, durationInMinute, true);
        return monitorAlarmRangeMap;
    }

    /**
     * 预警诊断
     *
     * @param jh        诊断井号
     * @param startTime
     * @return 返回null 表示没未找到诊断配置参数
     */
    @Deprecated
    @GetMapping("/test1")
    public Object EngineerWarn1(String jh, @RequestParam(required = false, defaultValue = "") String startTime) {
//        Date ltdTime = new Date();
//        if (StringUtils.isNotEmpty(startTime)) {
//            try {
//                ltdTime = org.jeecg.common.util.DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm:ss");
//            } catch (ParseException e) {
//                ltdTime = new Date();
//            }
//        }
//
//        List<Map<String, Object>> list = iCommonApi.queryDefaultEngineerLogic();
//        //预警配置参数
//        BWellOwnEngineer template = new BWellOwnEngineer();
//        if (list.size() == 0) {
//            //如果不存在该井的配置参数就去默认参数配置
//            list = iCommonApi.queryWellEngineerLogic(jh);
//        }
//        if (list.size() == 0) {
//            return null;
//        }
//        //从NClob获得配置参数信息
//        template.setLargeText(GetNClob(list.get(0).get("LARGETEXT")));
//
//        //初始化预警引擎需要的参数
//        CheckEngineerWarning checkLogic = new CheckEngineerWarning(template);
//        //监控预警记录--检查出的异常记录集
//        MonitorAlarmRecords monitorAlarmRecords = new MonitorAlarmRecords();
//
//        //提取需要诊断的数据--按照时间顺序排列提取
//        List<LtdRecord> ltdList = iCommonApi.queryLtdListInPeriod(jh, ltdTime, -30);
//        List<RecordHashTable> dataList = ltdList.stream().map(x -> CheckEngineerWarning.LtdToRecordHashTable(x)).collect(Collectors.toList());
//        ltdList.clear();
//        //诊断分析
//        checkLogic.AnalyseDataList(dataList, monitorAlarmRecords);
//
//        for (int i = 0; i < monitorAlarmRecords.size(); i++) {
//            MonitorAlarmRecord r = monitorAlarmRecords.get(i);
//            r.SetAlarmMsg(i + 1, jh);
//        }
//
//        return monitorAlarmRecords;
        return "obsolete";
    }

    /**
     * Deprecated 202210
     */
    @Deprecated
    @GetMapping("/test2")
    private void test_2022_Deprecated() {
//        log.info(String.format(" 备份井号的定时任务  时间:" + org.jeecg.common.util.DateUtils.getTimestamp()));
//        String sql = " select jh, jh id ,  max(t1.g_cname) ejdw, max(t2.g_cname) sjdw, max(t3.key) dt , max(t4.key) sgyq,  \n" +
//                "       max(t.dh) dh , max(t.kzrq) kzrq , max(t.jjrq) jjrq from v_yw_zjrb t \n" +
//                "  left join v_sys_group t1 on t1.groupid = t.ejdw\n" +
//                "  left join v_sys_group t2 on t2.groupid = t.sjdw\n" +
//                "  left join v_sys_constant t3 on t3.id = t.dt\n" +
//                "  left join v_sys_constant t4 on t4.id = t.sgyq" +
//                "                             where to_char(t.lrsj, 'yyyy/MM/dd') >= to_char(sysdate-1 , 'yyyy/MM/dd')  \n" +
//                "                             group by t.jh order by t.jh ";
//        List<Map<String, Object>> list = iLjrbService.querySql(sql, null);
//
//        List<Ajh> beanList = new ArrayList<Ajh>();
//        // 查询 录井仪、钻井液 标志
//        // TODO: 如果慢的话增加记录表 进行记录
//        List<String> wells = new ArrayList<>();
//        for (Map<String, Object> row : list) {
//            if (row.get("JH") != null) {
//                String wellName = row.get("JH").toString().trim();
//                row.put("JH", wellName);
//                wells.add(wellName);
//                try {
//                    List<Map<String, Object>> testObj = iCommonApi.queryJhLastDayOnLtd(wellName);
//                    row.put("ltd", 1);
//                    row.put("ltdDay", testObj.get(0).get("DAY").toString().split(" ")[0]);
//                } catch (Exception ex) {
//                    System.out.println(ex.getMessage());
//                    row.put("ltd", 0);
//                }
//                try {
//                    List<Map<String, Object>> testObj = iCommonApi.queryJhLastDayOnZjy(wellName);
//                    row.put("zjy", 1);
//                    row.put("zjyDay", testObj.get(0).get("DAY").toString().split(" ")[0]);
//                } catch (Exception ex) {
//                    System.out.println(ex.getMessage());
//                    row.put("zjy", 0);
//                }
//                Ajh jhRes = BeanUtil.toBean(row, Ajh.class);
//                beanList.add(jhRes);
//            }
//        }
//
//        updateJh(beanList);
    }

//    @Deprecated
//    public void updateJh(List<Ajh> beanList) {
//        if (beanList.size() > 0) {
//            QueryWrapper<Ajh> queryWrapper = new QueryWrapper<Ajh>();
//            queryWrapper.last(" where 1=1");
//            ajhService.remove(queryWrapper);
//            ajhService.saveBatch(beanList);
//
//            //删除关注井中没有总井表的数据
//            String jhs = "";
//            for (Ajh jh : beanList) {
//                jhs += "'" + jh.getJH() + "'" + " ,";
//            }
//            jhs = jhs.substring(0, jhs.length() - 1);
//
//            log.info(String.format(" 删除关注井号定时任务  井号:" + jhs));
//
//            QueryWrapper<AFocusjh> aFocusjhQueryWrapper = new QueryWrapper<AFocusjh>();
//            aFocusjhQueryWrapper.last(" where jh not in (" + jhs + ")");
//            focusjhService.remove(aFocusjhQueryWrapper);
//        }
//    }
}
