package org.jeecg.modules.dataVue.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.ReflectHelper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.cas.service.IWellboreAuthQuery;
import jtznyj.common.api.vo.AFocusWarn;
import org.jeecg.modules.dataVue.entity.AFocusjh;
import org.jeecg.modules.dataVue.entity.Ajh;
import org.jeecg.modules.dataVue.mapper.CustomMapper;
import org.jeecg.modules.dataVue.service.IAFocusWarnService;
import org.jeecg.modules.dataVue.service.IAFocusjhService;
import org.jeecg.modules.dataVue.service.IAjhService;
import org.jeecg.modules.dataVue.service.ILjrbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/focusJh")
@Slf4j
public class FocusJhController {

    @Autowired
    private IAFocusjhService iaFocusjhService;
    @Resource
    private CustomMapper customMapper;

    @Autowired
    private IAFocusWarnService iaFocusWarnService;
    @Autowired
    ILjrbService iLjrbService;
    @Autowired
    IWellboreAuthQuery iWellboreAuthQuery;

    @Resource
    private IAjhService ajhService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<?> queryPageList(@RequestParam(name = "dw", defaultValue = "") String dw,
                                   @RequestParam(name = "jh", defaultValue = "") String jh,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<HashMap<String, Object>> result = new Result<HashMap<String, Object>>();
        String sql = "";
        String casUser = iWellboreAuthQuery.getSessionCasName();
        if (StringUtils.isEmpty(dw)) {
            sql = "select * from a_jh where jh in ( " +
                    "select jh from a_focus_jh where" + String.format(" cas_user = '%s' ", casUser) + " ) ";
            sql += String.format(" and cas_user = '%s' ", casUser);
        } else {
            sql = " select * from a_jh where jh is not null ";
            sql += String.format(" and ejdw = '%s' ", dw);
        }
        if (!StringUtils.isEmpty(jh)) {
            sql += String.format(" and jh like '%%%s%%' ", jh);
        }

        if (StringUtils.isEmpty(dw)){
            sql = String.format(" select t.*, row_number() over (partition by id order by create_time desc) rn from (%s) t", sql);
            sql = String.format(" select * from (%s) where rn = 1 order by id ", sql);
        }else{
        sql += " order by NVL(LASTDATE,TO_DATE('1999-01-01','yyyy.MM.dd')) desc ";
        sql = String.format(" select t.*, row_number() over (partition by id order by id  ) rn from (%s) t", sql);
        sql = String.format(" select * from (%s) where rn = 1 order by NVL(LASTDATE,TO_DATE('1999-01-01','yyyy.MM.dd')) desc ", sql);
        }

        int start = pageNo * pageSize - pageSize;
        int end = pageNo * pageSize;
        String pageSql = "select * from (select rownum a,t.* from (" + sql + ") t where rownum<=" + end + ") where a>" + start;
        String countSql = " select count(*) from (" + sql + " )";
        System.out.println("sql" + pageSql);


        int count = iaFocusjhService.querySqlCount(countSql, null);
        List<Map<String, Object>> table = iaFocusjhService.querySql(pageSql, null);
        List<AFocusjh> list = ReflectHelper.transList2Entrys(table, AFocusjh.class);
        result.setSuccess(true);
        HashMap<String, Object> temp = new HashMap<>();

        temp.put("current", 0);
        temp.put("pages", Math.ceil(count / Double.parseDouble(pageSize.toString())));
        temp.put("records", list);
        temp.put("total", 0);
        temp.put("size", 0);
        result.setResult(temp);
        return result;
    }

    @RequestMapping(value = "/getJh", method = RequestMethod.GET)
    public Result<?> getJh(@RequestParam(name = "dw", defaultValue = "") String dw,
                           @RequestParam(name = "jh", defaultValue = "") String jh,
                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req){
        Result<HashMap<String, Object>> result = new Result<HashMap<String, Object>>();
        String casUser = iWellboreAuthQuery.getSessionCasName();
        List<Ajh> list =new ArrayList<>();
        if (StringUtils.isEmpty(dw)) {
            QueryWrapper<Ajh> ajhQueryWrapper = new QueryWrapper<>();
            QueryWrapper<AFocusjh> aFocusjhQueryWrapper = new QueryWrapper<>();
            aFocusjhQueryWrapper.lambda().eq(AFocusjh::getCasUser, casUser);
            List<AFocusjh> aFocusjhList = iaFocusjhService.list(aFocusjhQueryWrapper);
            if (aFocusjhList.size() > 0) {
                List<String> collect = aFocusjhList.stream().map(AFocusjh::getId).collect(Collectors.toList());
                ajhQueryWrapper.lambda().in(Ajh::getID, collect);
                if (!StringUtils.isEmpty(jh)) {
                    ajhQueryWrapper.lambda().like(Ajh::getJH,jh);
                }
                ajhQueryWrapper.lambda().orderByDesc(Ajh::getLtdDay);
                list = ajhService.list(ajhQueryWrapper);
                log.info("list:{}", list);
                list.forEach(item -> {
                    String id = item.getID();
                    List<AFocusjh> collects = aFocusjhList.stream().filter(items -> items.getId().equals(id)).collect(Collectors.toList());
                    AFocusjh aFocusjh = collects.get(0);
                    item.setIsWarn(aFocusjh.getIsWarn());
                });
            }
        } else {
            QueryWrapper<Ajh> ajhQueryWrapper = new QueryWrapper<>();
            ajhQueryWrapper.lambda().in(Ajh::getEJDW, dw);
            if (!StringUtils.isEmpty(jh)) {
                ajhQueryWrapper.lambda().like(Ajh::getJH,jh);
            }
            ajhQueryWrapper.lambda().orderByDesc(Ajh::getLtdDay);
            list = ajhService.list(ajhQueryWrapper);
        }
        result.setSuccess(true);
        HashMap<String, Object> temp = new HashMap<>();
        temp.put("records", list);
        result.setResult(temp);
        return result;
    }

    @RequestMapping(value = "/listWarning", method = RequestMethod.GET)
    public Result<IPage<AFocusWarn>> queryPageListWarning(AFocusWarn aFocusWarn, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<AFocusWarn>> result = new Result<IPage<AFocusWarn>>();
        QueryWrapper<AFocusWarn> queryWrapper = QueryGenerator.initQueryWrapper(aFocusWarn, req.getParameterMap());
        Page<AFocusWarn> page = new Page<AFocusWarn>(pageNo, pageSize);

        if (oConvertUtils.isNotEmpty(aFocusWarn.getJh())) {
            String[] jhList = aFocusWarn.getJh().split(",");
            queryWrapper.in("JH", jhList);
            aFocusWarn.setJh(null);
        }
        queryWrapper.orderByDesc("WARN_TIME");
        IPage<AFocusWarn> pageList = iaFocusWarnService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 工程预警获取数据
     *
     * @param jh
     * @param time
     * @return
     */
    @RequestMapping(value = "/getGcyjList", method = RequestMethod.GET)
    public Result<List<Map<String, Object>>> getGcyjList(String jh, String time, String lastOne) {
        Result<List<Map<String, Object>>> result = new Result<>();
        if (StringUtils.isEmpty(jh)) {
            result.error500("井号不能为空");
        }
        if (StringUtils.isEmpty(time)) {
            result.error500("时间不能为空");
        }
        String startTime = time + " 00:00:00";
        String endTime = time + " 23:59:59";
        String warnHisSql = "";
        if (lastOne.equals("Y")) {
            warnHisSql = "select * from (select * from A_FOCUS_WARN where JH='%s' and SOURCE='工程预警' order by WARN_TIME desc) where rownum=1";
        } else {
            warnHisSql = "select * from A_FOCUS_WARN where SOURCE='工程预警' and JH='" + jh + "' ";
        }

        warnHisSql += " and WARN_TIME>to_date('" + startTime + "', 'yyyy-MM-dd hh24:mi:ss')";
        warnHisSql += " and WARN_TIME<to_date('" + endTime + "', 'yyyy-MM-dd hh24:mi:ss') order by WARN_TIME";
        List<Map<String, Object>> warnHisList = iaFocusWarnService.querySql(warnHisSql, null);
        result.setSuccess(true);
        result.setResult(warnHisList);
        return result;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<AFocusjh> add(@RequestBody AFocusjh aFocusjh, HttpServletRequest request) {
        Result<AFocusjh> result = new Result<AFocusjh>();
        try {
            String casAccount = iWellboreAuthQuery.getSessionCasName();
            aFocusjh.setCasUser(casAccount);
            aFocusjh.setCreateTime(new Date());
            iaFocusjhService.save(aFocusjh);
            result.success("关注成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<AFocusjh> delete(@RequestParam(name = "jh", required = true) String jh, HttpServletRequest request) {
        Result<AFocusjh> result = new Result<AFocusjh>();
        String casAccount = iWellboreAuthQuery.getSessionCasName();
        QueryWrapper<AFocusjh> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("JH", jh)
                .eq("CAS_USER", casAccount);
        List<AFocusjh> list = iaFocusjhService.list(queryWrapper);
        if (list == null || list.size() == 0) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = iaFocusjhService.remove(queryWrapper);
            if (ok) {
                result.success("取消成功!");
            }
        }
        return result;
    }


    @RequestMapping(value = "/warningUpdate", method = RequestMethod.POST)
    public Result<AFocusWarn> update(@RequestBody AFocusWarn aFocusWarn) {

//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        System.out.println(loginUser.getRealname());
        aFocusWarn.setUpdated(new Date());
//        aFocusWarn.setRecorder(loginUser.getRealname());

        Result<AFocusWarn> result = new Result<AFocusWarn>();
        System.out.println(aFocusWarn);
        try {
            iaFocusWarnService.updateById(aFocusWarn);
            result.success("成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }


    @RequestMapping(value = "/newListWarning", method = RequestMethod.GET)
    public Result<Object> newListWarning(
            AFocusWarn aFocusWarn
            , @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo
            , @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
            , @RequestParam(name = "group", defaultValue = "1") Integer group,
            String warn_s, String warn_e,
            HttpServletRequest req) {
        Result<IPage<AFocusWarn>> result = new Result<IPage<AFocusWarn>>();
        int start = pageNo * pageSize - pageSize;
        int end = pageNo * pageSize;
        String sql = "";
        String where = " where 0=0 ";
        if (oConvertUtils.isNotEmpty(aFocusWarn.getSource()) && !"全部".equals(aFocusWarn.getSource())) {
            where += " and SOURCE = '" + aFocusWarn.getSource() + "' ";
        }
        if (oConvertUtils.isNotEmpty(aFocusWarn.getCatogary())) {
            where += " and CATOGARY = '" + aFocusWarn.getCatogary() + "' ";
        }
        if (oConvertUtils.isNotEmpty(warn_s)) {
            where += " and WARN_TIME > to_date('" + warn_s + " 00:00:00" + "', 'yyyy-mm-dd hh24:mi:ss') ";
        }
        if (oConvertUtils.isNotEmpty(warn_e)) {
            where += " and WARN_TIME < to_date('" + warn_e + " 23:59:59" + "', 'yyyy-mm-dd hh24:mi:ss') ";
        }

        if (oConvertUtils.isNotEmpty(aFocusWarn.getJh())) {
            String[] jhList = aFocusWarn.getJh().split(",");
            String in = " AND JH IN ( ";
            int a = 0;
            for (String jh : jhList) {
                a++;
                in += " '" + jh + "' ";
                if (a != jhList.length) {
                    in += ",";
                }
            }
            where += in + ")";
        }
        if (group == 1) {
            sql = "SELECT JH,CATOGARY,SOURCE,COUNT (*) AS COUNT,MAX (WARN_TIME) AS WARN_TIME FROM A_FOCUS_WARN O " + where + " GROUP BY JH,CATOGARY,SOURCE  ORDER BY WARN_TIME desc,JH";
        } else {
            sql = "SELECT O.* FROM A_FOCUS_WARN O " + where + " order by WARN_TIME DESC";
        }
        String pageSql = "select * from (select rownum a,t.* from (" + sql + " ) t where rownum<=" + end + ") where a>" + start;
        String countSql = " select count(*) from (" + sql + ")";

        pageSql = "SELECT M.*,(select N.jh from B_WELLOWNENGINEER N where N.jh=M.jh) MX FROM (" + pageSql + ") M";
        System.out.println("pageSql:" + pageSql);
        List<Map<String, Object>> list = iaFocusWarnService.querySql(pageSql, null);


        for (Map<String, Object> map : list) {

            /**
             * 没写过oracle的group by 先用代码实现 后期再改
             */
            if (group == 1) {
                String sqlOne = "SELECT * FROM (SELECT \"NAVICAT_TABLE\".*, ROWNUM \"NAVICAT_ROWNUM\" FROM ( SELECT \"JTZNYJ\".\"A_FOCUS_WARN\".*, ROWID \"NAVICAT_ROWID\" FROM \"JTZNYJ\".\"A_FOCUS_WARN\" WHERE \"JH\" = '" + map.get("JH").toString() + "' AND \"CATOGARY\" = '" + map.get("CATOGARY").toString() + "' ORDER BY WARN_TIME DESC ) \"NAVICAT_TABLE\" WHERE ROWNUM <= 1) WHERE \"NAVICAT_ROWNUM\" > 0";
                System.out.println("sqlOne=" + sqlOne);
                List<Map<String, Object>> fcusList = iaFocusWarnService.querySql(sqlOne, null);
                Map<String, Object> aFocusWarn2 = fcusList.get(0);
                map.put("BJNR", aFocusWarn2.get("BJNR").toString());
                map.put("SOURCE", aFocusWarn2.get("SOURCE").toString());
                map.put("JUDGE", aFocusWarn2.get("JUDGE"));
                map.put("REMARK", aFocusWarn2.get("REMARK"));
                map.put("RECORDER", aFocusWarn2.get("RECORDER"));
                map.put("UPDATED", aFocusWarn2.get("UPDATED"));
            }

            String DSJS = "";
            String SJJS = "";
            String kzSql = "select DSJS,SJJS from ( select * from v_yw_zjrb where jh='" + map.get("JH").toString() + "' ORDER BY LRSJ desc ) where ROWNUM =1 ";
            List<Map<String, Object>> kzList = iLjrbService.querySql(kzSql, null);
            if (kzList.size() > 0) {
                DSJS = kzList.get(0).get("DSJS").toString();
                SJJS = kzList.get(0).get("SJJS").toString();
            }
            if ("钻井液".equals(map.getOrDefault("SOURCE", ""))) {
                map.put("MX", "");
            } else {
                if (map.getOrDefault("MX", null) == null) {
                    map.putIfAbsent("MX", "默认");
                } else {
                    map.put("MX", "定制");
                }
            }

            map.put("DSJS", DSJS);
            map.put("SJJS", SJJS);

        }
        System.out.println("countSql:" + countSql);
        int count = iaFocusWarnService.querySqlCount(countSql, null);
        Map<String, Object> res = new HashMap<>();
        res.put("records", list);
        res.put("pages", Math.ceil(count / Double.parseDouble(pageSize.toString())));
        res.put("total", count);
//        Map<String,Object> res = iaFocusWarnService.newListWarning(aFocusWarn,pageNo,pageSize,group,warnTime_s,warnTime_e);
        return Result.ok(res);
    }
}
