package com.ruoyi.web.controller.ems;

import com.huashe.common.domain.AjaxResult;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ems.domain.Area;
import com.ruoyi.ems.domain.EmsDevice;
import com.ruoyi.ems.model.QueryDevice;
import com.ruoyi.ems.service.IAreaService;
import com.ruoyi.ems.service.IEmsDeviceService;
import com.ruoyi.ems.service.IEmsFacsService;
import com.ruoyi.ems.util.AreaUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 能源设备Controller
 *
 * @author ruoyi
 * @date 2024-07-10
 */
@RestController
@RequestMapping("/ems/device")
@Api(value = "DeviceController", description = "能源设备管理")
public class DeviceController extends BaseController {
    @Autowired
    private IEmsDeviceService deviceService;

    @Autowired
    private IEmsFacsService facsService;

    @Autowired
    private IAreaService areaService;

    /**
     * 查询能源设备列表
     */
    @PreAuthorize("@ss.hasPermi('ems:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryDevice queryDevice) {
        startPage();
        List<EmsDevice> list = deviceService.selectDetailList(queryDevice);
        return getDataTable(list);
    }

    /**
     * 查询能源设备列表
     */
    @GetMapping("/getByCondition")
    public AjaxResult getByCondition(QueryDevice queryDevice) {
        List<EmsDevice> list = deviceService.selectList(queryDevice);
        return success(list);
    }

    /**
     * 查询能源设备列表
     */
    @GetMapping("/getByFlowRel")
    public AjaxResult getByFlowRel(QueryDevice queryDevice) {
        List<EmsDevice> list = deviceService.selectByFlowRel(queryDevice);
        return success(list);
    }

    /**
     * 查询能源设备列表
     */
    @GetMapping("/getDetail")
    public AjaxResult getDetail(@RequestParam(value = "deviceCode") String deviceCode) {
        EmsDevice device = deviceService.selectDetailByCode(deviceCode);
        return success(device);
    }

    /**
     * 递归查询 区域 下的设备(分页)
     */
    @PreAuthorize("@ss.hasPermi('basecfg:device:list')")
    @GetMapping("/listRecursionByArea")
    public TableDataInfo listRecursionByArea(QueryDevice queryDevice) {
        TableDataInfo tabInfo = null;

        try {
            if (StringUtils.isNotEmpty(queryDevice.getLocationRef())) {
                List<Area> areaTree = areaService.selectAreaTree(queryDevice.getLocationRef(), true);
                List<String> areaCodes = new ArrayList<>();
                areaCodes.add(queryDevice.getLocationRef());
                // 递归取出区域子节点code做查询条件（需要将子节点区域关联设备一并取出）
                AreaUtils.getCodeRecursion(areaTree, areaCodes);
                queryDevice.setAreaCodes(areaCodes);
            }

            startPage();
            List<EmsDevice> list = deviceService.selectByAreaTree(queryDevice);
            tabInfo = getDataTable(list);
        }
        catch (BusinessException e) {
            tabInfo = new TableDataInfo();
            tabInfo.setCode(e.getCode());
            tabInfo.setMsg(e.getMessage());
        }

        return tabInfo;
    }

    /**
     * 根据设施获取设备树结构
     *
     * @param areaCode 区域code
     * @return 树结构
     */
    @PreAuthorize("@ss.hasPermi('basecfg:device:list')")
    @GetMapping("/getTreeByFacs")
    public AjaxResult getTreeByFacs(@RequestParam(value = "areaCode", required = false) String areaCode,
        @RequestParam(value = "deviceCategory", required = false) String deviceCategory) {
        QueryDevice queryDevice = new QueryDevice();
        queryDevice.setAreaCode(areaCode);
        queryDevice.setDeviceCategory(deviceCategory);
        return success(facsService.getFacsDevTree(queryDevice));
    }

    /**
     * 导出能源设备列表
     */
    @PreAuthorize("@ss.hasPermi('ems:device:export')")
    @Log(title = "能源设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QueryDevice queryDevice) {
        List<EmsDevice> list = deviceService.selectDetailList(queryDevice);
        ExcelUtil<EmsDevice> util = new ExcelUtil<EmsDevice>(EmsDevice.class);
        util.exportExcel(response, list, "能源设备数据");
    }

    /**
     * 获取能源设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('ems:device:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(deviceService.selectEmsDeviceById(id));
    }

    /**
     * 新增能源设备
     */
    @PreAuthorize("@ss.hasPermi('ems:device:add')")
    @Log(title = "能源设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmsDevice emsDevice) {
        return toAjax(deviceService.insertEmsDevice(emsDevice));
    }

    /**
     * 修改能源设备
     */
    @PreAuthorize("@ss.hasPermi('ems:device:edit')")
    @Log(title = "能源设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EmsDevice emsDevice) {
        return toAjax(deviceService.updateEmsDevice(emsDevice));
    }

    /**
     * 删除能源设备
     */
    @PreAuthorize("@ss.hasPermi('ems:device:remove')")
    @Log(title = "能源设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(deviceService.deleteEmsDeviceByIds(ids));
    }

    /**
     * 设备-类型在线率
     *
     * @param areaCode
     * @return
     */
    @GetMapping(value = "/type/online")
    public AjaxResult getDeviceOnlineSummary(@RequestParam("areaCode") String areaCode) {
        return success(deviceService.calcDeviceOnlineSummary(areaCode));
    }
}