package com.ruoyi.ems.controller;

import com.huashe.common.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
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.Area;
import com.ruoyi.ems.domain.EmsFacs;
import com.ruoyi.ems.enums.FacsCategoryType;
import com.ruoyi.ems.model.TreeEntity;
import com.ruoyi.ems.service.IAreaService;
import com.ruoyi.ems.service.IEmsFacsService;
import com.ruoyi.ems.util.AreaUtils;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
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.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 能源设施/系统Controller
 *
 * @author ruoyi
 * @date 2024-07-10
 */
@RestController
@RequestMapping("/basecfg/emsfacs")
@Api(value = "EmsFacsController", description = "能源设施管理")
public class EmsFacsController extends BaseController {
    @Autowired
    private IEmsFacsService facsService;

    @Autowired
    private IAreaService areaService;

    /**
     * 查询能源设施/系统列表
     */
    @RequiresPermissions("basecfg:emsfacs:list")
    @GetMapping("/list")
    public TableDataInfo list(EmsFacs emsFacs) {
        startPage();
        List<EmsFacs> list = facsService.selectEmsFacsList(emsFacs);
        return getDataTable(list);
    }

    /**
     * 导出能源设施/系统列表
     */
    @RequiresPermissions("basecfg:emsfacs:export")
    @Log(title = "能源设施/系统", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmsFacs emsFacs) {
        List<EmsFacs> list = facsService.selectEmsFacsList(emsFacs);
        ExcelUtil<EmsFacs> util = new ExcelUtil<EmsFacs>(EmsFacs.class);
        util.exportExcel(response, list, "能源设施/系统数据");
    }

    /**
     * 获取能源设施/系统详细信息
     */
    @RequiresPermissions("basecfg:emsfacs:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(facsService.selectEmsFacsById(id));
    }

    /**
     * 新增能源设施/系统
     */
    @RequiresPermissions("basecfg:emsfacs:add")
    @Log(title = "能源设施/系统", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmsFacs emsFacs) {
        return toAjax(facsService.insertEmsFacs(emsFacs));
    }

    /**
     * 修改能源设施/系统
     */
    @RequiresPermissions("basecfg:emsfacs:edit")
    @Log(title = "能源设施/系统", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EmsFacs emsFacs) {
        return toAjax(facsService.updateEmsFacs(emsFacs));
    }

    /**
     * 删除能源设施/系统
     */
    @RequiresPermissions("basecfg:emsfacs:remove")
    @Log(title = "能源设施/系统", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(facsService.deleteEmsFacsByIds(ids));
    }

    /**
     * 获取所有能源设施/系统列表
     *
     * @return 能源设施/系统列表
     */
    @GetMapping("/listall")
    public AjaxResult listAll(@RequestParam(name = "refArea", required = false) String refArea,
        @RequestParam(name = "facsCategory", required = false) String facsCategory,
        @RequestParam(name = "subCategory", required = false) String subCategory) {
        EmsFacs emsFacs = new EmsFacs();
        emsFacs.setRefArea(refArea);
        emsFacs.setFacsCategory(facsCategory);
        emsFacs.setFacsSubCategory(subCategory);

        return success(facsService.selectEmsFacsList(emsFacs));
    }

    /**
     * 查询区域树 (根据设施类型过滤)
     *
     * @param parentCode   父区域编码
     * @param facsCategory 设施类别
     */
    @GetMapping("/getFacsCategoryTree")
    public AjaxResult getFacsCategoryTree(
        @RequestParam(name = "parentCode", required = false, defaultValue = "0") String parentCode,
        @RequestParam(name = "facsCategory", required = false) String facsCategory) {

        // 查询区域树
        List<Area> areaTree = areaService.selectAreaTree(parentCode, false);

        // 查询设施列表
        EmsFacs facsParam = new EmsFacs();
        facsParam.setFacsCategory(facsCategory);
        List<EmsFacs> facsList = facsService.selectEmsFacsList(facsParam);
        Map<String, List<EmsFacs>> groupByArea = facsList.stream()
            .collect(Collectors.groupingBy(EmsFacs::getRefArea, Collectors.toList()));

        List<TreeEntity> retList = AreaUtils.convertAreaTree(areaTree);

        for (TreeEntity treeEntity : retList) {
            List<EmsFacs> facsTemp = groupByArea.get(treeEntity.getId());

            if (CollectionUtils.isNotEmpty(facsTemp)) {
                Map<String, List<EmsFacs>> groupByCaregory = facsTemp.stream()
                    .collect(Collectors.groupingBy(EmsFacs::getFacsCategory, Collectors.toList()));

                List<TreeEntity> facsCategoryList = new ArrayList<>();
                facsCategoryList.addAll(buildSubTree(FacsCategoryType.E, groupByCaregory));
                facsCategoryList.addAll(buildSubTree(FacsCategoryType.W, groupByCaregory));
                facsCategoryList.addAll(buildSubTree(FacsCategoryType.C, groupByCaregory));
                facsCategoryList.addAll(buildSubTree(FacsCategoryType.Z, groupByCaregory));
                treeEntity.setChildren(facsCategoryList);
            }
        }

        return success(retList);
    }

    private List<TreeEntity> buildSubTree(FacsCategoryType type, Map<String, List<EmsFacs>> groupByCaregory) {
        List<TreeEntity> retList = new ArrayList<>();
        List<EmsFacs> facsList = groupByCaregory.get(type.name());

        if (CollectionUtils.isNotEmpty(facsList)) {
            TreeEntity cnEntity = new TreeEntity();
            cnEntity.setId(type.name());
            cnEntity.setLabel(type.getTypeName());
            cnEntity.setChildren(convertEntity(facsList));
            retList.add(cnEntity);
        }

        return retList;
    }

    public static List<TreeEntity> convertEntity(List<EmsFacs> facsList) {
        List<TreeEntity> retList = new ArrayList<>();

        facsList.forEach(facs -> {
            TreeEntity treeEntity = new TreeEntity();
            treeEntity.setId(facs.getFacsCode());
            treeEntity.setLabel(facs.getFacsName());
            retList.add(treeEntity);
        });

        return retList;
    }
}
