package io.renren.modules.generator.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.generator.entity.EdgenodesEntity;
import io.renren.modules.generator.service.ApplicationsService;
import io.renren.modules.generator.service.EdgenodesService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2021-08-06 15:33:20
 */
@RestController
@RequestMapping("generator/edgenodes")
public class EdgenodesController {
    @Autowired
    private EdgenodesService edgenodesService;
    @Autowired
    private ApplicationsService applicationsService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:edgenodes:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = edgenodesService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{edgenodesId}")
    @RequiresPermissions("generator:edgenodes:info")
    public R info(@PathVariable("edgenodesId") Integer edgenodesId) {
        EdgenodesEntity edgenodes = edgenodesService.getById(edgenodesId);

        return R.ok().put("edgenodes", edgenodes);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:edgenodes:save")
    public R save(@RequestBody EdgenodesEntity edgenodes) {
        Date date = new Date();
        edgenodes.setCreatedTime(date);
        edgenodesService.save(edgenodes);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:edgenodes:update")
    public R update(@RequestBody EdgenodesEntity edgenodes) {
        Date date = new Date();
        edgenodes.setCreatedTime(date);
        edgenodesService.updateById(edgenodes);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:edgenodes:delete")
    public R delete(@RequestBody Integer[] edgenodesIds) {
        for (int edgenodeId:edgenodesIds){
            if (applicationsService.selectByDeployDeviceId(edgenodeId)>0){
                return R.error("该设备正在运行智能应用");
            }
        }
        edgenodesService.removeByIds(Arrays.asList(edgenodesIds));

        return R.ok();
    }

}
