package com.persagy.proxy.object.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.persagy.dmp.common.model.entity.BaseEntity;
import com.persagy.proxy.adm.request.AdmCreateRequest;
import com.persagy.proxy.adm.request.AdmCreateResponse;
import com.persagy.proxy.adm.request.AdmQueryCriteria;
import com.persagy.proxy.adm.request.AdmResponse;
import com.persagy.proxy.adm.utils.AdmContextUtil;
import com.persagy.proxy.adm.utils.ObjectNameUtil;
import com.persagy.proxy.common.entity.DmpResult;
import com.persagy.proxy.object.model.*;
import com.persagy.proxy.object.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * ADM 建筑 API
 * @author Charlie Yu
 * @date 2021-08-16
 */
@RestController
@RequestMapping("/object/building")
public class AdmBuildingController {

    @Autowired
    private IAdmBuildingService service;
    @Autowired
    private IAdmEquipmentService equipmentService;
    @Autowired
    private IAdmFloorService floorService;
    @Autowired
    private IAdmISpaceService iAdmISpaceService;
    @Autowired
    private IAdmSpaceService spaceService;

    /**
     * 创建
     * @param createRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/create")
    public AdmCreateResponse create(@RequestBody AdmCreateRequest<AdmBuilding> createRequest) throws Exception {
        List<AdmBuilding> vos = CollUtil.newArrayList(createRequest.getContent());
        vos.stream().forEach(admBuilding -> {
            if (StrUtil.isEmpty(admBuilding.getName())){
                admBuilding.setName(ObjectNameUtil.objectName("建筑-"));
            }
            if(CollUtil.isNotEmpty(admBuilding.getInfos())){
                if(admBuilding.getInfos().get("buildAge") != null){
                    admBuilding.getInfos().put("buildAge", DateUtil.format(DateUtil.parseDate(admBuilding.getInfos().get("buildAge").toString()),"yyyy"));
                }
            }
        });
        vos = service.doInsert(AdmContextUtil.toDmpContext(), AdmBuilding.class, vos);
        return AdmCreateResponse.success(vos);
    }

    /**
     * 根据ID删除
     * @param vos
     * @return
     * @throws Exception
     */
    @PostMapping("/delete")
    public AdmResponse delete(@RequestBody List<AdmBuilding> vos) throws Exception {
        if(CollUtil.isEmpty(vos)){
            return AdmResponse.failure("参数不能为空");
        }
        //验证楼层 空间 设备 等信息是否存在，不存在关系可以删除
        Map<String, AdmBuilding> admBuildingMap = CollUtil.fieldValueMap(vos, BaseEntity.PROP_ID);
        String msg = "建筑下包含其他对象实例，请解除关系后删除";
        AdmQueryCriteria admQueryCriteria = new AdmQueryCriteria();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(" buildingId in [");
        admBuildingMap.keySet().stream().forEach(buildingId -> {
            stringBuilder.append("'").append(buildingId).append("'").append(",");
        });

        String filters = StrUtil.sub(stringBuilder.toString(),0, -1);
        filters+= "] ";

        admQueryCriteria.setFilters(filters);
        admQueryCriteria.setName(AdmFloor.OBJ_TYPE);
        AdmResponse admResponseF = floorService.query(admQueryCriteria);
        if(DmpResult.SUCCESS.equals(admResponseF.getResult()) && CollUtil.isNotEmpty(admResponseF.getContent())){
            return AdmResponse.failure(msg);
        }
        admQueryCriteria.setName(AdmSpace.OBJ_TYPE);
        AdmResponse admResponseSpace = spaceService.query(admQueryCriteria);
        if(admResponseSpace.getResult().equals(DmpResult.SUCCESS) && CollUtil.isNotEmpty(admResponseSpace.getContent())){
            return AdmResponse.failure(msg);
        }
        admQueryCriteria.setName(AdmISpace.OBJ_TYPE);
        AdmResponse admResponseISpace = iAdmISpaceService.doQuery(AdmContextUtil.toDmpContext(), admQueryCriteria, AdmISpace.class);
        if(admResponseISpace.getResult().equals(DmpResult.SUCCESS) && CollUtil.isNotEmpty(admResponseISpace.getContent())){
            return AdmResponse.failure(msg);
        }

        admQueryCriteria.setName(AdmEquipment.OBJ_TYPE);
        AdmResponse admResponseEuip = equipmentService.query(admQueryCriteria);
        if(admResponseEuip.getResult().equals(DmpResult.SUCCESS) && CollUtil.isNotEmpty(admResponseEuip.getContent())){
            return AdmResponse.failure(msg);
        }
        service.doDelete(AdmContextUtil.toDmpContext(), vos);
        return AdmResponse.success();
    }

    /**
     * 根据ID删除 - 单条删除
     * @param vos
     * @return
     * @throws Exception
     */
    @PostMapping("/single/delete")
    public AdmResponse deleteSingle(@RequestBody List<AdmBuilding> vos) throws Exception {
        return delete(vos);
    }

    /**
     * 更新
     * @param createRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/update")
    public AdmResponse update(@RequestBody AdmCreateRequest<AdmBuilding> createRequest) throws Exception {
        List<AdmBuilding> vos = CollUtil.newArrayList(createRequest.getContent());
        vos.forEach(admBuilding -> {
            if(StrUtil.isEmpty(admBuilding.getName())){
                admBuilding.setName(ObjectNameUtil.objectName("建筑-"));
            }
        });
        vos = service.doUpdate(AdmContextUtil.toDmpContext(), AdmBuilding.class, vos);
        return AdmResponse.success(vos);
    }

    /**
     * 查询
     * @param projectId
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/query")
    public AdmResponse query(@RequestParam(value = "projectId",required = false) String projectId,
                             @RequestBody AdmQueryCriteria request) throws Exception {
        request.setName(AdmBuilding.OBJ_TYPE);
        return service.doQuery(AdmContextUtil.toDmpContext(), request, AdmBuilding.class);
    }

    /**
     * 统计
     * @param projectId
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/count")
    public AdmResponse count(@RequestParam(value = "projectId",required = false) String projectId,
                             @RequestBody AdmQueryCriteria request) throws Exception {
        request.setName(AdmBuilding.OBJ_TYPE);
        request.setOnlyCount(true);
        return service.doQuery(AdmContextUtil.toDmpContext(), request, AdmBuilding.class);
    }
}
