package com.ruoyi.ems.controller;

import com.alibaba.fastjson2.JSONObject;
import com.huashe.common.domain.AjaxResult;
import com.huashe.common.domain.JsonEntity;
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.ems.domain.EmsDevice;
import com.ruoyi.ems.domain.EmsObjAttr;
import com.ruoyi.ems.domain.EmsObjAttrDto;
import com.ruoyi.ems.domain.EmsObjAttrEnum;
import com.ruoyi.ems.domain.EmsSubsystem;
import com.ruoyi.ems.enums.DevObjType;
import com.ruoyi.ems.mapper.EmsDeviceMapper;
import com.ruoyi.ems.mapper.EmsSubsystemMapper;
import com.ruoyi.ems.service.IEmsObjAttrEnumService;
import com.ruoyi.ems.service.IEmsObjAttrService;
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 java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 能源对象属性Controller
 *
 * @author ruoyi
 * @date 2024-09-23
 */
@RestController
@RequestMapping("/object/attr")
@Api(value = "EmsObjAttrController", description = "能源对象属性管理")
public class EmsObjAttrController extends BaseController {
    @Autowired
    private IEmsObjAttrService attrService;

    @Autowired
    private IEmsObjAttrEnumService enumService;

    @Autowired
    private EmsDeviceMapper deviceService;

    @Autowired
    private EmsSubsystemMapper subsystemService;

    /**
     * 查询能源对象属性列表
     */
    @GetMapping("/list")
    public TableDataInfo list(EmsObjAttr objAttr) {
        startPage();
        List<EmsObjAttr> list = attrService.selectObjAttrList(objAttr);
        return getDataTable(list);
    }

    /**
     * 查询能源对象属性列表
     */
    @GetMapping("/enum/list")
    public AjaxResult list(@RequestParam(name = "modelCode") String modelCode,
        @RequestParam(name = "attrKey") String attrKey) {
        List<EmsObjAttrEnum> list = enumService.getObjAttrEnumList(modelCode, attrKey);
        return AjaxResult.success(list);
    }

    /**
     * 获取能源对象属性详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(attrService.selectObjAttrById(id));
    }

    /**
     * 查询能源对象属性值列表
     */
    @GetMapping("/getObjAttr")
    public AjaxResult list(@RequestParam(name = "objType") Integer objType,
        @RequestParam(name = "objCode") String objCode,
        @RequestParam(name = "modelCode", required = false) String modelCode) {
        AjaxResult result = null;

        try {
            JSONObject json = new JSONObject();
            json.put("objType", objType);
            json.put("objCode", objCode);

            if (null == modelCode) {
                modelCode = getModeCode(objType, objCode);
                json.put("modelCode", modelCode);
            }

            // 获取属性列表
            List<EmsObjAttrDto> attrDtos = attrService.selectObjAttrItem(modelCode, objType, objCode);

            if (CollectionUtils.isNotEmpty(attrDtos)) {
                Map<String, List<EmsObjAttrDto>> attrMap = attrDtos.stream()
                    .collect(Collectors.groupingBy(EmsObjAttrDto::getAttrGroup, Collectors.toList()));

                json.putAll(attrMap);
            }

            result = success(json);
        }
        catch (Exception e) {
            result = error(e.getMessage());
        }

        return result;
    }

    /**
     * 查询能源对象属性值列表
     */
    @GetMapping("/getObjAttrBatch")
    public AjaxResult listAll(@RequestParam(name = "objType") Integer objType,
        @RequestParam(name = "modelCode") String modelCode) {
        AjaxResult result = null;

        try {
            // 获取属性列表
            List<EmsObjAttrDto> attrDtos = attrService.selectObjAttrItem(modelCode, objType, null);
            JsonEntity.ObjBuilder json = JsonEntity.objBuilder();

            if (CollectionUtils.isNotEmpty(attrDtos)) {
                attrDtos = attrDtos.stream()
                    .filter(attr -> StringUtils.isNotEmpty(attr.getObjCode()))
                    .collect(Collectors.toList());
                Map<String, List<EmsObjAttrDto>> objAttrMap = attrDtos.stream()
                    .collect(Collectors.groupingBy(EmsObjAttrDto::getObjCode, Collectors.toList()));

                for (Map.Entry<String, List<EmsObjAttrDto>> entry : objAttrMap.entrySet()) {
                    String objCode = entry.getKey();
                    List<EmsObjAttrDto> subDtos = entry.getValue();

                    JsonEntity.ObjBuilder nodeJson = JsonEntity.objBuilder().putKv("objType", objType)
                        .putKv("objCode", objCode).putKv("modelCode", modelCode);

                    Map<String, List<EmsObjAttrDto>> gpAttrMap = subDtos.stream()
                        .collect(Collectors.groupingBy(EmsObjAttrDto::getAttrGroup, Collectors.toList()));

                    nodeJson.putMap(gpAttrMap);

                    json.putKv(objCode, nodeJson.build().getJsonObj());
                }
            }

            result = success(json.build().getJsonObj());
        }
        catch (Exception e) {
            result = error(e.getMessage());
        }

        return result;
    }

    /**
     * 新增能源对象属性
     */
    @Log(title = "能源对象属性", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmsObjAttr objAttr) {
        return toAjax(attrService.insertObjAttr(objAttr));
    }

    /**
     * 新增能源对象属性
     */
    @Log(title = "能源对象属性", businessType = BusinessType.INSERT)
    @PostMapping("/batch")
    public AjaxResult addBatch(@RequestBody List<EmsObjAttr> list) {
        return toAjax(attrService.insertBatch(list));
    }

    /**
     * 修改能源对象属性
     */
    @Log(title = "能源对象属性", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EmsObjAttr objAttr) {
        return toAjax(attrService.updateObjAttr(objAttr));
    }

    /**
     * 删除能源对象属性
     */
    @Log(title = "能源对象属性", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(attrService.deleteObjAttrByIds(ids));
    }

    private String getModeCode(Integer objType, String objCode) {
        String modeCode = null;

        if (objType == DevObjType.DEVC.getCode()) {
            EmsDevice device = deviceService.selectDeviceByCode(objCode);
            modeCode = null != device ? device.getDeviceModel() : null;
        }
        else if (objType == DevObjType.SYSTEM.getCode()) {
            EmsSubsystem subsystem = subsystemService.selectEmsSubsystemByCode(objCode);
            modeCode = null != subsystem ? subsystem.getModelCode() : null;
        }

        return modeCode;
    }
}
