package com.imdroid.beidou.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.imdroid.beidou.common.HttpResult;
import com.imdroid.beidou.service.CommonExcelService;
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.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.List;

/**
 * gnss设备解算数据 控制器
 */
@Controller
public class GnssCalcDataController extends BasicController implements CommonExcelService<GnssCalcData, GnssCalcData> {
    @Autowired
    GnssCalcDataMapper dataMapper;
    @Autowired
    TenantMapper tenantMapper;
    @Autowired
    GnssDeviceMapper deviceMapper;
    @Autowired
    OpLogManager opLogManager;
    boolean isJoinQuery = false;
    final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @RequestMapping("/page/gnss_data_calc")
    public String gnssData(Model m, HttpSession session) {
        initModel(m, session);
        List<Tenant> tenants = tenantMapper.selectList(null);
        m.addAttribute("tenant_list", tenants);

        if(tenantId != Tenant.SAAS_PROVIDER_ID) {
            QueryWrapper<GnssDevice> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tenantid", tenantId);
            queryWrapper.select("project_id");
            queryWrapper.groupBy("project_id");
            List<GnssDevice> gnssDeviceList = deviceMapper.selectList(queryWrapper);
            m.addAttribute("project_list", gnssDeviceList);
        }
        return "/page/gnss_data_calc";
    }

    @PostMapping("/page/gnssUpdateEnabled")
    @ResponseBody
    public String gnssUpdateEnabled(HttpSession session, @RequestParam Long id) throws Exception {
        int num = 0;
        GnssCalcData calcData = dataMapper.selectById(id);
        if(calcData != null){
            calcData.setEnabled(!calcData.getEnabled());  // 使用Boolean类型
            calcData.setUpdatetime(LocalDateTime.now());
            num = dataMapper.updateById(calcData);
        }

        opLogManager.addLog(getLoginUser(session),getTenantId(session),
                OpLogManager.OP_TYPE_DEL,
                OpLogManager.OP_OBJ_DEVICE,
                calcData.getDeviceid() + " "+calcData.getCreatetime()+" gnss data changed");
        if (num == 0) {
            return HttpResult.failed();
        } else{
            return HttpResult.ok();
        }
    }


    /**** 推送数据  *****/
    @RequestMapping("/gnss/data/list_calc")
    @ResponseBody
    public JSONObject listData(HttpSession session, Integer page, Integer limit, String searchParams) {
        // 检查查询条件
        JSONObject search = null;
        if (searchParams != null) {
            search = (JSONObject) JSONObject.parse(searchParams);
            String deviceId = search.getString("s_t.deviceid");
            Integer freqency = search.getInteger("freqency");
            String begin = search.getString("dgt_t.createtime");
            String end = search.getString("dlt_t.createtime");

            if(deviceId != null && !deviceId.isEmpty() && freqency!=0){
                Page pageable = new Page<>(page == null ? 1 : page, limit == null ? 10 : limit);

                // 缺省按1小时采样，如果时间跨度较大，则按最多300条记录的采样率采样
                int sample = 6;

                if(freqency == 2){
                    LocalDateTime endTime = LocalDateTime.now();
                    LocalDateTime beginTime = endTime.minusDays(30);
                    if(begin!=null && !begin.isEmpty()){
                        beginTime = LocalDateTime.parse(begin,df);
                    }
                    if(end!=null && !end.isEmpty()){
                        endTime = LocalDateTime.parse(end,df);
                    }
                    Duration duration = Duration.between(beginTime, endTime);
                    int hours = (int)duration.toHours();
                    if(hours > 300) sample = hours*6/300;
                }
                Page<GnssCalcData> calcDataList = dataMapper.queryByDeviceId(pageable, deviceId,begin,end,sample);

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

        return this.pageList(session, page, limit, searchParams);
    }

    /**
     * 获取实体类的class
     *
     * @return 实体类的class
     */
    @Override
    public Class<GnssCalcData> getEntityClass() {
        return GnssCalcData.class;
    }

    /**
     * 获取实体类对应的mybatis mapper
     *
     * @return 实体类对应的mybatis mapper
     */
    @Override
    public BaseMapper<GnssCalcData> getMapper() {
        return dataMapper;
    }

    /**
     * 导出excel
     *
     * @param session      HttpSession
     * @param request HttpServletRequest
     * @param response     HttpServletResponse
     * @throws Exception
     */
    @RequestMapping("/gnss/data/calc/export")
    @ResponseBody
    public void exportData(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
        this.export(session, request, response);
    }

    @Override
    public void checkSearchParams(JSONObject search){
        if(search != null) {
            String deviceId = search.getString("sl_t.deviceid");
            if(StringUtils.hasText(deviceId)){
                search.remove("sl_d.parentid");
                search.remove("sl_d.project_id");
                isJoinQuery=false;
            }
            else {
                String parentId = search.getString("sl_d.parentid");
                String projectId = search.getString("sl_d.project_id");
                isJoinQuery = StringUtils.hasText(parentId) || StringUtils.hasText(projectId);
            }
        }
        else isJoinQuery=false;
    }
    @Override
    public void checkSearchParams(Enumeration<String> enu){
        isJoinQuery=false;
        if(enu != null) {
            while (enu.hasMoreElements()) {
                String item = enu.nextElement();
                if(item.contains("d.parentid") || item.contains("d.project_id")){
                    isJoinQuery = true;
                    break;
                }
            }
        }
    }

    @Override
    public MPJQueryWrapper<GnssCalcData> prepareQueryWrapper() {
        if(isJoinQuery) {
            return new MPJQueryWrapper<GnssCalcData>()
                    .selectAll(GnssCalcData.class)
                    .leftJoin("gnssdevices d on t.deviceid = d.deviceid")
                    .orderByDesc("t.createtime");
        }
        else{
            return new MPJQueryWrapper<GnssCalcData>()
                    .selectAll(GnssCalcData.class)
                    .orderByDesc("createtime");
        }
    }

    /**
     * 是否联表查询
     *
     * @return 是否联表查询
     */
    @Override
    public boolean isJoinSelect() {
        return isJoinQuery;
    }

    @Override
    public String tenantIdField() {
        if(isJoinQuery) return "d.tenantid";
        else return "tenantid";
    }
}
