package com.persagy.dmp.rwd.define.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.model.QueryCriteria;
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.helper.SpringHelper;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.common.utils.ResultHelper;
import com.persagy.dmp.define.entity.ObjectInfoDefine;
import com.persagy.dmp.define.entity.ObjectTypeDefine;
import com.persagy.dmp.digital.entity.ObjectDigital;
import com.persagy.dmp.mybatis.utils.ConditionUtil;
import com.persagy.dmp.rwd.define.service.IObjectInfoService;
import com.persagy.dmp.rwd.define.service.IObjectTypeService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
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 javax.validation.Valid;
import java.util.List;

/**
 * 对象类型 Controller
 * @author Charlie Yu
 * @date 2021-06-25
 */
@RestController
@RequestMapping("/rwd/def/funcid")
@RequiredArgsConstructor
public class ObjectInfoController {

    private final IObjectInfoService service;
    private final IObjectTypeService typeService;

    @PostMapping("")
    public CommonResult<List<ObjectInfoDefine>> query(@RequestBody QueryCriteria criteria) {
        if(criteria == null) {
            throw new BusinessException(ResponseCode.A0400.getCode(), ResponseCode.A0400.getDesc());
        }
        // 2021年8月18日20:06:24 兼容旧的查询
        ObjectNode objCriteria = criteria.getCriteria();
        if (null!=objCriteria && objCriteria.size()>0){
            objCriteria.remove(CommonConstant.TYPE);
        }
        String projectId = AppContext.getContext().getProjectId();
        List<ObjectTypeDefine> typeDefineList = queryClassCodes(criteria);
        // 处理查询条件
        QueryWrapper<ObjectInfoDefine> wrapper = new QueryWrapper<>();
        // 没有排序条件时，按默认条件排序
        if(CollUtil.isEmpty(criteria.getOrders())) {
            wrapper.orderByAsc("show_order");
        }
        // 如果入参带classCode：不进行分页并连带查出上级类型信息点
        if(CollUtil.isNotEmpty(typeDefineList) && StrUtil.isNotBlank(projectId)) {
            criteria.getCriteria().remove(ObjectDigital.CLASS_CODE_HUM);
            QueryCriteriaHelper.toWrapper(wrapper, criteria, ObjectInfoDefine.class);
            List<String> classCodes = CollUtil.getFieldValues(typeDefineList, "code", String.class);
            List<ObjectInfoDefine> vos = service.queryByClassCodes(projectId, classCodes, wrapper);
            return ResultHelper.multi(vos);
        }
        // 普通查询
        ConditionUtil.ensureProjectCriteria(wrapper);
        QueryCriteriaHelper.toWrapper(wrapper, criteria, ObjectInfoDefine.class);
        Page<ObjectInfoDefine> page = QueryCriteriaHelper.toPage(criteria);
        // 只计数
        if(criteria.isOnlyCount()) {
            page = page.setTotal(service.queryCount(wrapper));
        } else {
            page = service.queryByCondition(QueryCriteriaHelper.toPage(criteria), wrapper);
        }
        return ResultHelper.multi(page.getRecords(), page.getTotal());
    }

    @PostMapping("/create")
    public CommonResult<ObjectInfoDefine> create(@Valid @RequestBody ObjectInfoDefine vo){
        List<ObjectInfoDefine> voList = CollUtil.newArrayList(vo);
        //创建默认条件
        createDefaultValue(voList);
        //新增信息点
        service.insert(voList);
        return ResultHelper.single(vo);
    }

    @PostMapping("/createBatch")
    public CommonResult<List<ObjectInfoDefine>> createBatch(@Valid @RequestBody List<ObjectInfoDefine> voList){
        //创建默认条件
        createDefaultValue(voList);
        //批量新增信息点
        voList = service.insert(voList);
        return ResultHelper.multi(voList);
    }

    @PostMapping("/update")
    public CommonResult<ObjectInfoDefine> update(@Valid @RequestBody ObjectInfoDefine vo){
        List<ObjectInfoDefine> voList = CollUtil.newArrayList(vo);
        //创建默认条件
        createDefaultValue(voList);
        //修改信息点
        service.update(voList);
        return ResultHelper.single(vo);
    }

    @PostMapping("/updateBatch")
    public CommonResult<List<ObjectInfoDefine>> updateBatch(@Valid @RequestBody List<ObjectInfoDefine> voList){
        //创建默认条件
        createDefaultValue(voList);
        //修改信息点
        voList = service.update(voList);
        return ResultHelper.multi(voList);
    }

    @PostMapping("/delete")
    public CommonResult delete(@RequestBody String id){
        if(StringUtils.isEmpty(id)){
            throw new BusinessException(ResponseCode.A0400.getCode(), "id不能为空");
        }
        service.delete(CollUtil.newArrayList(id));
        return ResultHelper.success();
    }

    @PostMapping("/deleteBatch")
    public CommonResult deleteBatch(@RequestBody List<String> ids){
        if(ids == null || ids.size()<=0){
            throw new BusinessException(ResponseCode.A0400.getCode(), "id不能为空");
        }
        service.delete(ids);
        return ResultHelper.success();
    }

    /***
     * Description: 处理对象类型,如果父级id存在则加上父级id
     * @param criteria : 查询参数
     * @return : void
     * @author : lijie
     * @date :2021/9/9 18:25
     * Update By lijie 2021/9/9 18:25
     */
    private List<ObjectTypeDefine> queryClassCodes(QueryCriteria criteria) {
        ObjectNode objectNode = criteria.getCriteria();
        if (!objectNode.has(ObjectDigital.CLASS_CODE_HUM)){
            return null;
        }
        JsonNode jsonNode = objectNode.get(ObjectDigital.CLASS_CODE_HUM);
        QueryCriteria typeCriteria = new QueryCriteria();
        typeCriteria.setCriteria(SpringHelper.getBean(ObjectMapper.class).createObjectNode());
        typeCriteria.getCriteria().set("code",jsonNode);
        typeCriteria.getCriteria().put("valid",true);
        QueryWrapper<ObjectTypeDefine> wrapper = new QueryWrapper<>();
        // 添加所属项目条件
        ConditionUtil.ensureProjectCriteria(wrapper);
        // 转换查询条件
        QueryCriteriaHelper.toWrapper(wrapper, typeCriteria, ObjectTypeDefine.class);
        List<ObjectTypeDefine> objectTypeDefines = typeService.queryByCondition(wrapper);
        if (CollUtil.isEmpty(objectTypeDefines)){
            return null;
        }
        return objectTypeDefines;
    }

    /**
     * 创建默认条件
     * @param voList
     */
    private void createDefaultValue(List<ObjectInfoDefine> voList){
        String groupCode = AppContext.getContext().getGroupCode();
        if(StringUtils.isEmpty(groupCode)){
            //默认集团
            groupCode = CommonConstant.DEFAULT_ID;
        }
        String projectId = AppContext.getContext().getProjectId();
        if(StringUtils.isEmpty(projectId)){
            //默认项目
            projectId = CommonConstant.DEFAULT_ID;
        }
        for (ObjectInfoDefine vo : voList) {
            vo.setGroupCode(groupCode);
            vo.setProjectId(projectId);
        }
    }
}
