package com.imdroid.beidou.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.imdroid.secapi.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;

@Controller
public class IndexController extends BasicController{
    @Autowired
    GnssDeviceMapper gnssDeviceMapper;
    @Autowired
    GnssStatusMapper statusMapper;

    @RequestMapping("/")
    public String index0(Model m, HttpSession session) {
        initModel(m, session);
        return "/index";
    }

    @RequestMapping("/index")
    public String index(Model m, HttpSession session) {
        initModel(m, session);
        return "/index";
    }

    @RequestMapping("/page/device_overview")
    public String deviceOverview(Model m, HttpSession session) {
        initModel(m, session);
        int deviceDeployedNum;
        int deviceOfflineNum=0;
        int warning1Num=0;//一般告警
        int warning2Num=0;//严重告警
        int noGGA = 0;
        int noFix = 0;

        //未推送设备数（同时满足：非SAAS服务商、使用状态正常、fwd_group_id和fwd_group_id2都为"不推送"的设备）
        Long deviceNoFwdNum;
        QueryWrapper<GnssDevice> noFwdQueryWrapper = new QueryWrapper<>();
        if (tenantId != Tenant.SAAS_PROVIDER_ID) {
            // 非SAAS服务商查询当前租户
            noFwdQueryWrapper.eq("tenantid", tenantId);
        } else {
            // SAAS服务商查询所有非SAAS的租户
            noFwdQueryWrapper.ne("tenantid", Tenant.SAAS_PROVIDER_ID);
        }
        // 使用状态正常
        noFwdQueryWrapper.eq("opmode", GnssDevice.OP_MODE_USE);
        // 设备类型为测站（非基站）
        noFwdQueryWrapper.eq("devicetype", GnssDevice.TYPE_ROVER);
        // fwd_group_id为"不推送"
        noFwdQueryWrapper.eq("fwd_group_id", GnssGroupFwd.FWD_TYPE_NONE);
        // fwd_group_id2为"不推送"或为null
        noFwdQueryWrapper.and(wrapper -> wrapper.eq("fwd_group_id2", GnssGroupFwd.FWD_TYPE_NONE).or().isNull("fwd_group_id2"));
        deviceNoFwdNum = gnssDeviceMapper.selectCount(noFwdQueryWrapper);

        List<GnssStatusJoin> deviceList;
        if(tenantId == Tenant.SAAS_PROVIDER_ID){
            deviceList = statusMapper.queryDeployed();
        }
        else{
            deviceList = statusMapper.queryDeployedByTenant(tenantId);
        }
        deviceDeployedNum = deviceList.size();

        //for(GnssStatusJoin status:deviceList){遍历删除异常
        Iterator<GnssStatusJoin> iterator = deviceList.iterator();
        while(iterator.hasNext()){
            GnssStatusJoin status=iterator.next();
            if(status.getState() == GnssStatus.STATE_OFFLINE) {
                deviceOfflineNum++;
            }
            else if((status.getWarningcode()&WarningCfg.TYPE_CONT_INVALID_RESULT) != 0) {
                noFix++;
            }

            if(status.getWarning() == WarningCfg.LEVEL_1) warning1Num++;
            else if(status.getWarning() == WarningCfg.LEVEL_2) warning2Num++;

            // 剔除无经纬度的对象，不在地图上显示
            if(status.getLatitude()==null || status.getLongitude()==null){
                noGGA++;
                iterator.remove();
            }
            else{
                // 地图上显示工点名称
                if(status.getName()!=null){
                    status.setDeviceid(status.getDeviceid() +" "+status.getName());
                }
                // 地图上显示告警原因
                if(status.getWarning()!=WarningCfg.LEVEL_0){
                    List<String> warningInfo= WarningCfg.parseCode(status.getWarningcode());
                    status.setDeviceid(status.getDeviceid() +" "+warningInfo);
                }
            }
        }

        //temp
/*        if(deviceOfflineNum>10) deviceOfflineNum=deviceOfflineNum/10;
        if(warning1Num>10) warning1Num=warning1Num/10;
        if(warning2Num>10) warning1Num=warning2Num/10;
*/
        m.addAttribute("deviceDeployedNum", deviceDeployedNum);
        m.addAttribute("deviceOnlineNum", deviceDeployedNum-deviceOfflineNum);
        m.addAttribute("deviceOfflineNum",  deviceOfflineNum);
        m.addAttribute("warning1Num", warning1Num);
        m.addAttribute("warning2Num", warning2Num);
        m.addAttribute("warningTotalNum", warning1Num+warning2Num);
        m.addAttribute("noGGA", noGGA);
        m.addAttribute("noFix", noFix);
        m.addAttribute("deviceNoFwdNum", deviceNoFwdNum);
        m.addAttribute("deviceList", deviceList);

        return "/page/device_overview";
    }

    @RequestMapping("/page/gnss_q_status")
    public String gnssStatusQuery(Model m, HttpSession session,@RequestParam String query) {
        initModel(m, session);
        if(query != null){
            session.setAttribute("query",query);
        }
        return "/page/table/gnss_status_list";
    }

    /**** 推送数据  *****/
    @RequestMapping("/gnss/q_status/list")
    @ResponseBody
    public JSONObject list(HttpSession session, Integer page, Integer limit) {
        Page pageable = new Page<>(page == null ? 1 : page, limit == null ? 10 : limit);
        MPJQueryWrapper<GnssStatus> queryWrapper = new MPJQueryWrapper<>();
        Integer tenantId = getTenantId(session);
        if(tenantId == Tenant.SAAS_PROVIDER_ID) {
            queryWrapper.selectAll(GnssStatus.class)
                    .select("d.name as name", "d.devicetype as devicetype", "d.project_id as project_id")
                    .leftJoin("gnssdevices d on t.deviceid = d.deviceid")
                    .ne("d.tenantid", Tenant.SAAS_PROVIDER_ID)
                    .eq("opmode", GnssDevice.OP_MODE_USE)
                    .orderByDesc("updatetime");
        }
        else{
            queryWrapper.selectAll(GnssStatus.class)
                    .select("d.name as name", "d.devicetype as devicetype", "d.project_id as project_id")
                    .leftJoin("gnssdevices d on t.deviceid = d.deviceid")
                    .eq("d.tenantid", tenantId)
                    .eq("opmode", GnssDevice.OP_MODE_USE)
                    .orderByDesc("updatetime");
        }

        String query = (String) session.getAttribute("query");
        if(query != null){
            if(query.equals("offline")){
                queryWrapper.eq("state",GnssStatus.STATE_OFFLINE);
            }
            else if(query.equals("nofixed")){
                queryWrapper.eq("warningcode&"+WarningCfg.TYPE_CONT_INVALID_RESULT,WarningCfg.TYPE_CONT_INVALID_RESULT);
            }
            else if(query.equals("warning1")){
                queryWrapper.eq("warning",WarningCfg.LEVEL_1);
            }
            else if(query.equals("warning2")){
                queryWrapper.eq("warning",WarningCfg.LEVEL_2);
            }
            else if(query.equals("nogga")){
                queryWrapper.isNull("latitude");
            }
            else if(query.equals("no_fwd")){
                // 查询同时满足：使用状态正常、设备类型为测站、fwd_group_id和fwd_group_id2都为"不推送"的设备
                queryWrapper.eq("d.opmode", GnssDevice.OP_MODE_USE)
                        .eq("d.devicetype", GnssDevice.TYPE_ROVER)
                        .eq("d.fwd_group_id", GnssGroupFwd.FWD_TYPE_NONE)
                        .and(wrapper -> wrapper.eq("d.fwd_group_id2", GnssGroupFwd.FWD_TYPE_NONE).or().isNull("d.fwd_group_id2"));
            }
            session.setAttribute("query",query);
        }

        IPage<GnssStatusJoin> cs = statusMapper.selectJoinPage(pageable, GnssStatusJoin.class, queryWrapper);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", cs.getTotal());
        jsonObject.put("data", cs.getRecords());
        return jsonObject;
    }


}
