package com.ruoyi.ems.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.ems.domain.AreaBuilding;
import com.ruoyi.ems.domain.AreaBuildingZoning;
import com.ruoyi.ems.domain.EmsDevice;
import com.ruoyi.ems.domain.common.AreaTier;
import com.ruoyi.ems.domain.vo.QueryDevice;
import com.ruoyi.ems.service.IAreaBuildingService;
import com.ruoyi.ems.service.IAreaBuildingZoningService;
import com.ruoyi.ems.service.IEmsDeviceService;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.List;
import java.util.stream.Collectors;

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

    @Autowired
    private IAreaBuildingService buildingService;

    @Autowired
    private IAreaBuildingZoningService zoningService;

    /**
     * 查询能源设备列表
     */
    @RequiresPermissions("ems:device:list")
    @GetMapping("/list")
    public TableDataInfo list(EmsDevice emsDevice) {
        startPage();
        List<EmsDevice> list = deviceService.selectEmsDeviceList(emsDevice);
        return getDataTable(list);
    }

    /**
     * 递归查询 区域/建筑/区块 下的设备(分页)
     */
    @RequiresPermissions("basecfg:device:list")
    @GetMapping("/listRecursionByArea")
    public TableDataInfo listRecursionByArea(QueryDevice queryDevice) {
        // 层级为区域 (建筑->区块)
        if (StringUtils.equals(queryDevice.getAreaType(), AreaTier.Area.name()) && StringUtils.isNotBlank(
            queryDevice.getRefArea())) {
            List<AreaBuilding> buildings = buildingService.selectBuildingByAreaCode(queryDevice.getRefArea());
            List<String> buildingCodes = buildings.stream().map(AreaBuilding::getBldgCode).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(buildings)) {
                // 回填建筑codes
                queryDevice.setBuildingCodes(buildingCodes);

                List<AreaBuildingZoning> zonings = zoningService.selectZoningByBuildings(buildingCodes);
                List<String> zoningCodes = zonings.stream().map(AreaBuildingZoning::getZoningCode)
                    .collect(Collectors.toList());
                // 回填区块codes
                queryDevice.setZoningCodes(CollectionUtils.isNotEmpty(zoningCodes) ? zoningCodes : null);
            }
        }
        // 层级为建筑 (区块)
        else if (StringUtils.equals(queryDevice.getAreaType(), AreaTier.Building.name()) && StringUtils.isNotBlank(
            queryDevice.getRefArea())) {
            List<AreaBuildingZoning> list = zoningService.selectZoningByBuilding(queryDevice.getRefArea());
            List<String> zoningCodes = list.stream().map(AreaBuildingZoning::getZoningCode)
                .collect(Collectors.toList());
            // 回填区块codes
            queryDevice.setZoningCodes(CollectionUtils.isNotEmpty(zoningCodes) ? zoningCodes : null);
        }

        startPage();
        List<EmsDevice> list = deviceService.selectByAreaTree(queryDevice);
        return getDataTable(list);
    }

    /**
     * 根据设施获取设备树结构
     * @param areaCode 区域code
     * @return 树结构
     */
    @RequiresPermissions("basecfg:device:list")
    @GetMapping("/getTreeByFacs")
    public AjaxResult getTreeByFacs(@RequestParam(value = "areaCode", required = false) String areaCode) {
        return success(deviceService.getTreeByFacs(areaCode));
    }

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

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

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

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

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