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.imdroid.beidou.auth.SessionUtils;
import com.imdroid.beidou.entity.Tenant;
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.*;

import javax.servlet.http.HttpSession;

@Controller
public class GnssFwdController extends BasicController{
    @Autowired
    GnssGroupFwdMapper gnssGroupFwdMapper;
    @Autowired
    FwdRecordMapper fwdRecordMapper;

    /********* 推送页面 *********/
    @RequestMapping("/page/fwd_agents")
    public String fwdAgents(Model m, HttpSession session) {
        initModel(m, session);
        return "/page/fwd_agents";
    }

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

    /********* 基本参数组 *********/
    @RequestMapping("/fwd/agents")
    @ResponseBody
    public JSONObject listAgents(int page, int limit) {
        Page<GnssGroupFwd> pageable = new Page<>(page, limit);
        IPage<GnssGroupFwd> cs = gnssGroupFwdMapper.selectPage(pageable, null);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", cs.getTotal());
        jsonObject.put("data", cs.getRecords());
        return jsonObject;
    }

    @RequestMapping("/fwd/records")
    @ResponseBody
    public JSONObject listRecords(HttpSession session, int page, int limit) {
        Page<FwdRecord> pageable = new Page<>(page, limit);
        QueryWrapper<FwdRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("starttime");
        Integer tenantId = (Integer) session.getAttribute(SessionUtils.SESSION_TENANT_ID);
        if (tenantId != null && tenantId != Tenant.SAAS_PROVIDER_ID) {
            queryWrapper.eq("tenantid", tenantId);
        }
        IPage<FwdRecord> cs = fwdRecordMapper.selectPage(pageable, queryWrapper);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", cs.getTotal());
        jsonObject.put("data", cs.getRecords());
        return jsonObject;
    }
}
