package org.jeecg.modules.dataVue.task;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import jtznyj.engineer.api.IEngineerApi;
import jtznyj.engineer.dto.WarnItemDto;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.dataVue.controller.FocusJhController;
import jtznyj.common.api.vo.AFocusWarn;
import org.jeecg.modules.dataVue.service.*;
import org.jeecg.modules.newWarning.service.RealTimeZjService;
import org.jeecg.modules.warning.entity.Ltd;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class FocusWarnJob implements Job {

    @Autowired
    IAjhService ajhService;
    @Autowired
    ILjrbService iLjrbService;
    @Autowired
    IZjfzService iZjfzService;
    @Autowired
    IAFocusWarnService iaFocusWarnService;
    @Autowired
    IMasterService iLogicService;
    @Autowired
    ILtdSourceService iLtdSourceService;
    @Autowired
    IZjyService iZjyService;
    @Autowired
    FocusJhController focusJhController;
    @Autowired
    IEngineerApi iEngineerApi;
    @Autowired
    RealTimeZjService realTimeZjService;

    @Value("${server.port}")
    private String port;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("port " + port);
        if (!port.equals("8090")) {
            return;
        }
        /**
         * 2022.3.17由关注井预警改为所有井都预警
         */
        log.info(String.format(" 后台计算预警信息定时任务  时间:" + org.jeecg.common.util.DateUtils.getTimestamp()));
        String sql = " select * from A_JH where jh is not null ";
        List<Map<String, Object>> jhList = new ArrayList<>();
        jhList = ajhService.querySql(sql, null);
        if (jhList.size() > 0) {
            for (Map<String, Object> itemMap : jhList) {
                String ltd = itemMap.get("LTD").toString();
                String zjy = itemMap.get("ZJY").toString();
                String jh = itemMap.get("JH").toString();
                if (ltd.equals("1")) {
                    try {

                        Map<String,Object> dateMap=new HashMap<>();
                        String table = iLogicService.getTableCodeNew(jh);
                        dateMap.put("table",table);

                        Ltd ltdEntity = realTimeZjService.selectDate(dateMap);
                        if (ltdEntity != null) {
//                        String js = date.get(0).get("DEPTH").toString();
                            //getCassByJs(jh,"5000",js);
                            getGc2(jh);
                        }
                    } catch (Exception e) {
                        log.warn(e.getMessage());
                    }

                }
                try {
                    if (zjy.equals("1")) {
                        getZjy(jh);
                    }
                } catch (Exception e) {
                    log.warn(e.getMessage());
                }

            }
        }
    }

    //复杂情况
    @Deprecated
    private void getCassByJs(String jh, String distance, String js) {

        BigDecimal jsNum = new BigDecimal(js);
        String warnHisSql = "select * from (select * from A_FOCUS_WARN where JH='%s' and SOURCE='临井复杂' order by WARN_TIME desc) where rownum=1";
        warnHisSql = String.format(warnHisSql, jh);
        List<Map<String, Object>> warnHisList = iaFocusWarnService.querySql(warnHisSql, null);
        if (warnHisList.size() > 0) {
            BigDecimal dsjsHis = new BigDecimal(warnHisList.get(0).get("DSJS").toString());
            if ((dsjsHis.subtract(jsNum)).compareTo(new BigDecimal("1")) == -1 && (dsjsHis.subtract(jsNum)).compareTo(new BigDecimal("-1")) == 1) {
                return;
            }
        }
        long startTime = System.currentTimeMillis();
        String sql = " select  xzb x, yzb y  "
                + " from v_scdt_jwxx t " +
                " where xzb is not null and yzb is not null "
                + String.format(" and jh = '%s' ", jh);
        List<Map<String, Object>> data = iLjrbService.querySql(sql, null);
        if (data.size() == 0) {
            sql = " select t2.sjjwzzbx x, t2.SJJWZZBY y from mv_azj01 t2 " +
                    " where sjjwzzbx is not null and sjjwzzby is not null "
                    + String.format(" and jh = '%s' ", jh);
            data = iZjfzService.querySql(sql, null);
        }
        String[] x = new String[2];
        if (data.size() > 0) {
            x[0] = data.get(0).get("X").toString();
            x[1] = data.get(0).get("Y").toString();
        }

        if (data.size() == 0) {
            return;
        }
        String zzbX = x[0]; // 4xxxxxx
        String hzbY = x[1]; // 2yyyyyyyy
        sql = "select t1.ID,t1.JH, SGXH, SGMC, DSJS, t3.name as caselevel, t2.sjjwzzbx, t2.sjjwhzby\n" +
                "                      from jsra t1\n" +
                "                      left join jjbxx t2\n" +
                "                        on t2.jh = t1.jh\n" +
                "                      left join Text_cl t3\n" +
                "                        on t3.id = t1.sgdjbh\n" +
                "                     where sglbid is not null\n" +
                "                       and sqrt(power((t2.sjjwzzbx - %s), 2) +\n" +
                "                                power((t2.sjjwhzby - %s), 2)) < %s\n" +
                "                     order by t1.dsjs ";
        sql = String.format(sql, zzbX, hzbY, distance);
        List<Map<String, Object>> list = iZjfzService.querySql(sql, null);
        List<AFocusWarn> warnList = new ArrayList<>();

        for (Map<String, Object> itemMap : list) {
            BigDecimal dsjs = new BigDecimal(itemMap.get("DSJS").toString());
            if ((dsjs.subtract(jsNum)).compareTo(new BigDecimal("1")) == -1 && (dsjs.subtract(jsNum)).compareTo(new BigDecimal("-1")) == 1) {
                AFocusWarn record = new AFocusWarn();
                record.setSource("邻井复杂");
                record.setJh(jh);
                record.setCatogary(itemMap.get("SGMC").toString());
                record.setWarnTime(new Date());
                record.setBjnr(itemMap.get("FSJGJYY").toString());
                record.setServercost(System.currentTimeMillis() - startTime);
                record.setDsjs(itemMap.get("DSJS").toString());
                record.setKey(jh + jh);
                warnList.add(record);
            }
        }
        iaFocusWarnService.saveBatch(warnList);
    }

    //工程预警
    @Deprecated
    private void getGc(String jh) {
//        String warnHisSql = "select * from A_FOCUS_WARN where JH='%s' and SOURCE='工程预警' order by WARN_TIME desc";
//        warnHisSql = String.format(warnHisSql, jh);
//        List<Map<String, Object>> warnHisList = iaFocusWarnService.querySql(warnHisSql, null);
//        long startTime = System.currentTimeMillis();
//        List<AFocusWarn> warnList = new ArrayList<>();
//        if (warnHisList.size() > 0) {
//            String warnTime = warnHisList.get(0).get("WARN_TIME").toString().substring(0, 19);
//            Date warnTimeValue = DateUtil.parse(warnTime);
//            Date now = new Date();
//            long minute = DateUtil.between(warnTimeValue, now, DateUnit.MINUTE);
//            if (minute >= 1) {
//                MonitorAlarmRecords warn = EngineerWarn(jh, new Date());
//                warn.forEach(m -> {
//                    String key = Double.toString(m._realDepthEnd) + m._name + Double.toString(m._realDepthEnd);
//                    Boolean exist = false;
//                    for (Map<String, Object> item : warnHisList) {
//                        if (item.get("KEY").toString().equals(key)) {
//                            exist = true;
//                        }
//                    }
//                    for (AFocusWarn item2 : warnList) {
//                        if (item2.getKey().equals(key)) {
//                            exist = true;
//                        }
//                    }
//                    if (!exist) {
//                        AFocusWarn record = new AFocusWarn();
//                        record.setSource("工程预警");
//                        record.setJh(jh);
//                        record.setCatogary(m._name);
//                        record.setWarnTime(m._dtEnd);
//                        record.setBjnr(StringUtils.isEmpty(m.warnMsg) ? "" : m.warnMsg.replace("<br/>", "\r\n"));
//                        record.setServercost(System.currentTimeMillis() - startTime);
//                        record.setDsjs(Double.toString(m._realDepthEnd));
//                        record.setKey(Double.toString(m._realDepthEnd) + m._name + Double.toString(m._realDepthEnd));
//                        warnList.add(record);
//                    } else {
//                        //如果井深一样,则update时间
//                        Map<String, Object> warn_one = warnHisList.get(0);
//
//                        AFocusWarn focusWarn = new AFocusWarn();
//                        focusWarn.setId(warn_one.get("ID").toString());
//                        focusWarn.setJh(jh);
//                        focusWarn.setCatogary(m._name);
//                        focusWarn.setWarnTime(m._dtEnd);
//                        focusWarn.setBjnr(StringUtils.isEmpty(m.warnMsg) ? "" : m.warnMsg.replace("<br/>", "\r\n"));
//                        focusWarn.setServercost(System.currentTimeMillis() - startTime);
//                        focusWarn.setDsjs(Double.toString(m._realDepthEnd));
//                        focusWarn.setKey(Double.toString(m._realDepthEnd) + m._name + Double.toString(m._realDepthEnd));
//                        iaFocusWarnService.updateById(focusWarn);
//                    }
//
//                });
//                iaFocusWarnService.saveBatch(warnList);
//            }
//        } else {
//            MonitorAlarmRecords warn = EngineerWarn(jh, new Date());
//            warn.forEach(m -> {
//                AFocusWarn record = new AFocusWarn();
//                record.setSource("工程预警");
//                record.setJh(jh);
//                record.setCatogary(m._name);
//                record.setWarnTime(new Date());
//                record.setBjnr(StringUtils.isEmpty(m.warnMsg) ? "" : m.warnMsg.replace("<br/>", "\r\n"));
//                record.setServercost(System.currentTimeMillis() - startTime);
//                record.setDsjs(Double.toString(m._realDepthEnd));
//                record.setKey(Double.toString(m._realDepthEnd) + m._name + Double.toString(m._realDepthEnd));
//                warnList.add(record);
//            });
//            iaFocusWarnService.saveBatch(warnList);
//        }
    }

    //钻井液
    private void getZjy(String jh) {
        List<AFocusWarn> warnList = new ArrayList<>();
        long startTime = System.currentTimeMillis();
        List<WarnItemDto> zjyList = new ArrayList<>();
        String t = String.format("ZJYCS_%s_BJ", jh.replace('-', '_'));
        // region
        String sql = " with t1 as (\n" +
                "                             select  sj, bjlx, to_char(sj, 'yyyyMMDD') || bjlx || '_' ||substr(bjxx, 0, 12)  bjpart, bjxx " +
                "           from %s\n  " +
                "               where %s \n" +
                "                        ),\n" +
                "\n" +
                "                        tt1 as (\n" +
                "                        select row_number() over (partition by  bjpart order by sj ) pn,  t1.* from t1),\n" +
                "\n" +
                "                        tt5 as (\n" +
                "                        select bjpart, max(pn) maxPn from tt1 group by bjpart  ),\n" +
                "\n" +
                "                        tt3 as (\n" +
                "                        select  tt2.sj nSj, tt5.maxpn, tt1.* from tt1 \n" +
                "                        left join tt1 tt2 on tt2.pn = tt1.pn - 1 and tt1.bjpart = tt2.bjpart\n" +
                "                        left join tt5 on tt5.bjpart = tt1.bjpart),\n" +
                "\n" +
                "                        tt6 as(\n" +
                "                        select tt3.sj , tt3.nsj , round(to_number(tt3.sj - tt3.nsj)* 24 * 60 ) diffM, tt3.pn, tt3.maxpn, tt3.bjlx,  bjPart, tt3.bjxx  from tt3 \n" +
                "                        order by bjpart, pn),\n" +
                "                        tt9 as (\n" +
                "                        select * from tt6  \n" +
                "                        where diffM > 8 or maxpn = pn)\n" +
                "\n" +
                "                            select*\n" +
                "                              from tt9\n" +
                "                             order by sj desc";
        // endregion


        String warnHisSql = "select * from (select * from A_FOCUS_WARN where JH='%s' and SOURCE='钻井液' order by WARN_TIME desc) where rownum=1";
        warnHisSql = String.format(warnHisSql, jh);
        List<Map<String, Object>> warnHisList = iaFocusWarnService.querySql(warnHisSql, null);

        String lastZjyTime = warnHisList.size() > 0 ?
                String.format(" sj > to_date('%s', 'yyyy-MM-dd hh24:mi:ss') ", warnHisList.get(0).get("WARN_TIME").toString().substring(0, 19))
                : String.format(" sj > to_date((select to_char(max(sj), 'yyyy-MM-dd') || '00:00:01' from %s), 'yyyy-MM-dd hh24:mi:ss') ", t);

        sql = String.format(sql, t, lastZjyTime);

        List<Map<String, Object>> data = iZjyService.querySql(sql, null);
        data.forEach(k -> {
            AFocusWarn record = new AFocusWarn();
            record.setSource("钻井液");
            record.setJh(jh);
            record.setCatogary(GetZjyCatogaryStr(k.get("BJLX").toString()));
            try {
                record.setWarnTime(org.jeecg.common.util.DateUtils.parseDate(k.get("SJ").toString(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            record.setBjnr(k.get("BJXX").toString());
            record.setServercost(System.currentTimeMillis() - startTime);
            //record.setDsjs(Double.toString(m._realDepthEnd));
            record.setKey(k.get("SJ") + "_" + k.get("BJLX"));
            warnList.add(record);
        });
        iaFocusWarnService.saveBatch(warnList);
    }

    private String GetZjyCatogaryStr(String bjlx) {
        switch (bjlx) {
            case "0":
                return "门限报警";
            case "1":
                return "溢流报警";
            case "2":
                return "井漏报警";
            case "3":
                return "异常报警";
            default:
                return "未分类";
        }
    }

    private void getGc2(String jh) {
        String warnHisSql = "select * from A_FOCUS_WARN where JH='%s' and SOURCE='工程预警' order by WARN_TIME desc";
        warnHisSql = String.format(warnHisSql, jh);
        List<Map<String, Object>> warnHisList = iaFocusWarnService.querySql(warnHisSql, null);
        long startTime = System.currentTimeMillis();
        List<AFocusWarn> warnList = new ArrayList<>();
        if (warnHisList.size() > 0) {
            String warnTime = warnHisList.get(0).get("WARN_TIME").toString().substring(0, 19);
            Date warnTimeValue = DateUtil.parse(warnTime);
            Date now = new Date();

            long minute = DateUtil.between(warnTimeValue, now, DateUnit.MINUTE);
            if (minute >= 1) {
                iEngineerApi.testAndSaveWarnResult(jh, new Date(), 30, true);
            }
        }
    }

}
