package com.kym.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.kym.common.R;
import com.kym.common.annotation.SysLog;
import com.kym.entity.admin.Station;
import com.kym.entity.admin.vo.ConnectorVo;
import com.kym.service.admin.StationService;
import com.kym.service.cache.KymCache;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;

/**
 * <p>
 * 充电站信息 前端控制器
 * </p>
 *
 * @author skyline
 * @since 2023-08-12
 */
@RestController
@RequestMapping("/station")
public class StationController {

    private final StationService stationService;


    public StationController(StationService stationService) {
        this.stationService = stationService;
    }

    @SysLog("充电站数据统计")
    @GetMapping("/stationStatusDetail")
    R<?> stationStatusDetail(@RequestParam("stationId") String stationId,
                             @RequestParam("startTime") @DateTimeFormat(pattern = "yyyy-MM-dd") String startTime,
                             @RequestParam("endTime") @DateTimeFormat(pattern = "yyyy-MM-dd") String endTime) {
        // 请求en+接口
        var response = stationService.stationStats(stationId, startTime, endTime);
        return R.success(response);
    }

    @SysLog("站点列表")
    @GetMapping("listStation")
    R<?> listStation(@RequestParam(required = false) String stationName) {
        // 判断数据权限
        var adminStationIds = KymCache.INSTANCE.getAdminUserStationIds(StpUtil.getLoginIdAsLong());
        var res = stationService.lambdaQuery()
                .eq(Station::getStationStatus, Station.STATION_STATUS_正常使用)
                .in(isNotNull(adminStationIds), Station::getStationId, adminStationIds)
                .like(isNotNull(stationName), Station::getStationName, stationName)
                .orderByAsc(Station::getStationId).list();
        return R.success(res);
    }

    @SysLog("修改站点信息")
    @PostMapping("modify")
    R<?> modifyStation(@RequestBody Station station) {
        stationService.modifyStation(station);
        return R.success();
    }

    /**
     * 拉取EN+充电站信息数据并更新本地服务器数据
     *
     * @return
     */
    @GetMapping("/pullEnStations/{stationId}")
    R<?> pullEnStationInfos(@PathVariable String stationId) {
        stationService.pullEnStationInfos(stationId);
        return R.success();
    }

    // 新增站点
    @SysLog("初始化新站点信息")
    @PostMapping("/addStation")
    R<?> addStation(@RequestBody List<ConnectorVo> stationInfo) {
        stationService.addStation(stationInfo);
        return R.success();
    }

    @PostMapping("/importData")
    R<?> importData(@RequestBody JSONObject data){
        stationService.importData(data);
        return R.success(data);
    }

}
