package org.jeecg.modules.dataVue.task;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.dataVue.entity.AFocusjh;
import org.jeecg.modules.dataVue.entity.Ajh;
import org.jeecg.modules.dataVue.service.*;
import org.jeecg.modules.newWarning.service.RealTimeZjService;
import org.jeecg.modules.warning.entity.Ltd;
import org.jeecg.modules.warning.entity.WellNewTable;
import org.jeecg.modules.warning.service.ILtdService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class jhHistoryJob implements Job {

    @Autowired
    ILjrbService iLjrbService;
    @Autowired
    ILtdSourceService iLtdSourceService;
    @Autowired
    IZjyService iZjyService;
    @Autowired
    IAjhService ajhService;
    @Autowired
    IAFocusjhService focusjhService;
    @Autowired
    RealTimeZjService realTimeZjService;
    @Autowired
    IMasterService iLogicService;

    @Autowired
    ILtdService ltdService;

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

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        if (!port.equals("8090")) {
            return;
        }
        log.info(String.format(" 备份井号的定时任务  时间:" + org.jeecg.common.util.DateUtils.getTimestamp()));

        iLjrbService.clearEjdwList();

        List<String> newTableList = ltdService.selectNewTable();


//        String newSQL = "select jh, any_value(dwmc) ejdw, any_value(dwmc) sjdw, any_value(dtmc) dt , any_value(sgyq) sgyq," +
//                "  any_value(dh) dh,  any_value(kzrq) kzrq , any_value(jjrq) jjrq , any_value(sgdd) sgdd ," +
//                " any_value(jfdw) jfdw , any_value(jb) jb , any_value(jx) jx from " +
//                "v_yw_zjrb3 where 0=0 ";
        String newSQL = "SELECT * " +
                " FROM v_yw_zjrb3 " +
                " WHERE (jh, rq) IN ( " +
                "    SELECT jh, MAX(rq) " +
                "    FROM v_yw_zjrb3 " +
                "    GROUP BY jh " +
                ")  ";

        if (newTableList.size() > 0){
            newSQL += " and jh in ( ";
            for (String jh : newTableList){
                newSQL += "'" + jh + "',";
            }

            newSQL += " '0' ) ";
        }
        List<Map<String, Object>> list = iLjrbService.querySql(newSQL, null);

        List<Ajh> beanList = new ArrayList<>();
        // 查询 录井仪、钻井液 标志
        // TODO: 如果慢的话增加记录表 进行记录
        List<String> wells = new ArrayList<>();
        for (Map<String, Object> row : list) {

            if (row.get("JH") == null) {
                continue;
            }

            if (row.get("DSJS")!=null){
                row.put("DSSJ",row.get("DSJS").toString());
            }
            if (row.get("DWMC")!=null){
                row.put("EJDW",row.get("DWMC").toString());
                row.put("SJDW",row.get("DWMC").toString());
            }
            if (row.get("DTMC")!=null){
                row.put("DT",row.get("DTMC").toString());
            }


            String wellName = row.get("JH").toString().trim();

            row.put("JH", wellName);
            wells.add(wellName);

            String zjyParam = "zjycs_" + wellName.replace('-', '_');
            try {
                String test = String.format("select max(sj) day from %s   ", zjyParam);
                List<Map<String, Object>> testObj = iZjyService.querySql(test, null);
                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);

        }
        updateJhNew(newTableList,beanList);
    }



    @Transactional
    public void updateJhNew(List<String> newTableList , List<Ajh> beanList) {

        List<Ajh> ajhList = ajhService.selectNotNullList();

        List<String> ajhs = ajhList.stream().map(e -> e.getJH()).collect(Collectors.toList());

        List<String> beans = beanList.stream().map(e -> e.getJH()).collect(Collectors.toList());

        List<Ajh> saveList = new ArrayList<>();

        for (String jh : newTableList){
            Ajh ajh;
            if (beans.contains(jh)){
                ajh = beanList.stream().filter(item -> item.getJH().equals(jh)).findFirst().get();
                ajh.setNOTFOUND("0");
            }else {
                ajh = new Ajh();
                ajh.setJH(jh);
                ajh.setEJDW("黄河钻井");
                ajh.setNOTFOUND("1");
            }

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

                Ltd ltd = realTimeZjService.selectDate(dateMap);

                if (ltd != null && StringUtils.isNotEmpty(ltd.getTime())) {
                    ajh.setLtd(1);
                    ajh.setLtdDay(ltd.getTime().substring(0, 10));
                }


            }catch (Exception e){
                ajh.setLtd(0);
            }

            if (StringUtils.isNotEmpty(jh) && ajhs.contains(jh)){
                try {
                    ajh.setID(ajhList.stream().filter(item -> item.getJH().equals(jh)).findFirst().get().getID());
                    ajhService.updateById(ajh);
                }catch (Exception e){
                    System.out.println(jh);
                    System.out.println(e);
                }
            }else {
                ajhService.saveOrUpdate(ajh);
//                saveList.add(ajh);
            }

        }

        System.out.println("savelist"+ saveList.size());
//        ajhService.saveBatch(saveList);
    }



    @Transactional
    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);
        }
    }
}
