package com.persagy.dmp.rwd.simple.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.basic.dto.RequestData;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.basic.model.QueryOperator;
import com.persagy.dmp.basic.utils.JsonNodeUtils;
import com.persagy.dmp.basic.utils.QueryCriteriaHelper;
import com.persagy.dmp.common.constant.CommonConstant;
import com.persagy.dmp.common.constant.ResponseCode;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.exception.BusinessException;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.common.utils.JsonHelper;
import com.persagy.dmp.common.utils.ParamCheckUtil;
import com.persagy.dmp.common.utils.ResultHelper;
import com.persagy.dmp.digital.entity.ObjectDigital;
import com.persagy.dmp.digital.entity.ObjectRelation;
import com.persagy.dmp.rwd.basic.constant.DigitalRelCode;
import com.persagy.dmp.rwd.digital.utils.ObjectDigitalCriteriaHelper;
import com.persagy.dmp.rwd.simple.service.ISystemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 系统业务接口
 * @author lvxy
 * @date 2021/10/9
 */
@Slf4j
@RestController
@RequestMapping("/api/custom/system")
public class SystemController {

    @Autowired
    private ISystemService systemService;
    /**
     * 查询不确定楼层/不确定建筑 的系统
     */
    @PostMapping("/queryNotSureSystem")
    public Page<Map<String,Object>> queryNotSureSystem(@RequestBody RequestData requestData) {
        //基础参数校验
        ParamCheckUtil.checkParam(CommonConstant.QUERY_GROUPCODE);
        if (StrUtil.isAllEmpty(AppContext.getContext().getProjectId(),requestData.getObjType())){
            throw new BusinessException(ResponseCode.A0402.getCode(),ResponseCode.A0402.getDesc());
        }
        Page<Map<String,Object>> result = systemService.queryNotSureSystem(requestData);
        return result;
    }

    /**
     * 根据条件查询系统 针对查询条件中有distinct 和 projectiond 的情况
     * {   "distinct": true,
     *     "pageNumber": 1,
     *     "pageSize": 1000,
     *     "projection": [
     *         "classCode",
     *         "CategoryName"
     *     ]
     * }
     * @param requestData
     * @return
     * @throws IOException
     */
    @PostMapping("/queryObjListByConditions")
    public CommonResult<List<ObjectNode>> queryObjListByConditions(@RequestBody RequestData requestData) throws IOException {
        // 暂时先拼接query接口参数进行查询,后续视情况再单独写逻辑
        ObjectMapper objectMapper = JsonHelper.objectMapper;
        QueryCriteria queryCriteria = new QueryCriteria();
        queryCriteria.setOrders(requestData.getOrders());
        queryCriteria.setPage(requestData.getPage());
        queryCriteria.setSize(requestData.getSize());
        ObjectNode objectNode = objectMapper.createObjectNode();
        // 专业,系统类,设备类
        if (StrUtil.isNotBlank(requestData.getClassCode())) {
            ObjectNode classCodeObj = objectMapper.createObjectNode();
            classCodeObj.put(QueryOperator.LIKE_RIGHT.getIndex(), requestData.getClassCode());
            objectNode.set(ObjectDigital.CLASS_CODE_HUM, classCodeObj);
        }
        // 楼层id
        if (StrUtil.isNotBlank(requestData.getFloorId())) {
            // criteria条件
            ObjectNode criteriaObj = objectMapper.createObjectNode();
            criteriaObj.put(ObjectRelation.REL_CODE_HUM, DigitalRelCode.SY_2_FL.getIndex());
            criteriaObj.put(ObjectRelation.OBJ_TO_HUM, requestData.getFloorId());
            objectNode.set(ObjectRelation.RELATION_FROM_HUM, criteriaObj);
        }
        // 系统id
        if (StrUtil.isNotBlank(requestData.getBuildingId())) {
            // criteria条件
            ObjectNode criteriaObj = objectMapper.createObjectNode();
            criteriaObj.put(ObjectRelation.REL_CODE_HUM, DigitalRelCode.SY_2_BD.getIndex());
            criteriaObj.put(ObjectRelation.OBJ_TO_HUM, requestData.getBuildingId());
            objectNode.set(ObjectRelation.RELATION_FROM_HUM, criteriaObj);
        }
        objectNode.put(ObjectDigital.OBJ_TYPE_HUM, requestData.getObjType());
        objectNode.put(ObjectDigital.PROP_VALID,Boolean.TRUE);
        queryCriteria.setCriteria(objectNode);


        //基础参数校验
        ParamCheckUtil.checkParam(CommonConstant.QUERY_GROUPCODE);
        // 增加判断传值项目id逻辑,2021年9月10日19:15:17
        JsonNode projectNode = queryCriteria.getCriteria().get(RequestData.PROJECT_IDS_HUM);
        if (queryCriteria.getCriteria().has(RequestData.PROJECT_IDS_HUM)){
            queryCriteria.getCriteria().remove(RequestData.PROJECT_IDS_HUM);
        }
        QueryWrapper<ObjectDigital> wrapper = new QueryWrapper<>();
        // 添加所属项目条件
        // ConditionUtil.ensureProjectCriteriaDirectly(wrapper);
        String projectId = AppContext.getContext().getProjectId();
        if (null!=projectNode && projectNode.isArray()){
            wrapper.in(StrUtil.toUnderlineCase(AppContext.PROJECT_ID), JsonHelper.toMultiEntity(projectNode,String.class));
        }else {
            wrapper.eq(StrUtil.isNotBlank(projectId), StrUtil.toUnderlineCase(AppContext.PROJECT_ID), projectId);
        }
        // 处理扩展条件
        ObjectDigitalCriteriaHelper.presetDigitalCriteria(queryCriteria);
        // 转换查询条件
        QueryCriteriaHelper.toWrapper(wrapper, queryCriteria, ObjectDigital.class);

        if(CollUtil.isNotEmpty(requestData.getProjection())){
            StringBuilder distictParam = new StringBuilder( "DISTINCT ");
            requestData.getProjection().stream().forEach(coulum ->{
                if(coulum.equals(ObjectDigital.CLASS_CODE_HUM)){
                    distictParam.append(ObjectDigital.CLASS_CODE).append(",");
                }
                if(coulum.equals(ObjectDigital.LOCAL_NAME_HUM)){
                    distictParam.append(ObjectDigital.LOCAL_NAME).append(",");
                }
                if(coulum.equals(ObjectDigital.LOCAL_ID_HUM)){
                    distictParam.append(ObjectDigital.LOCAL_ID).append(",");
                }
                if(coulum.equals(ObjectDigital.NAME)){
                    distictParam.append(ObjectDigital.NAME).append(",");
                }
            });
            String coulums = StrUtil.sub(distictParam.toString(),0, -1);
            wrapper.select(coulums);
        }

        Page page = QueryCriteriaHelper.toPage(queryCriteria);
        if(queryCriteria.isOnlyCount()) {
            Integer total = systemService.queryCount(wrapper);
            page.setTotal(total);
        } else {
            page = systemService.queryByCondition(QueryCriteriaHelper.toPage(queryCriteria), wrapper);
        }
        // 处理扩展属性
        List<ObjectNode> records = JsonNodeUtils.toListNode(page.getRecords(), ObjectDigital.EXTRA_COLUMN, queryCriteria.getWithColumns());
        return ResultHelper.multi(records, page.getTotal());
    }

}
