package org.springblade.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.AllArgsConstructor;
import org.springblade.community.agency.entity.Agency;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.system.orgposition.service.impl.OrgPositionServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


public class QueryWrapperUtil<T> {

	public LambdaQueryWrapper<T> getBasicQueryWrapper(SFunction<T, String> function, T t, BladeUser bladeUser,IOrgPositionService orgPositionService){
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<T> wrapper = Condition.getQueryWrapper(t).lambda();
		for (int i = 0; i < deptIds.length; i++) {
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
			if (i == 0) {
				wrapper.like(function,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(function,orgPosition.getOrgPosition());
			}
		}
		return wrapper;
	}

	public LambdaQueryWrapper<T> getBasicQueryWrapperByMap(SFunction<T, String> function, Map map, T t, BladeUser bladeUser, IOrgPositionService orgPositionService){
		String deptId = bladeUser.getDeptId();
		if(StringUtil.isBlank(deptId)){
			return Condition.getQueryWrapper(map,t.getClass()).lambda();
		}
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<T> wrapper = Condition.getQueryWrapper(map,t.getClass()).lambda();
		for (int i = 0; i < deptIds.length; i++) {
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
			if (orgPosition == null){
				continue;
			}
			if (i == 0) {
				wrapper.like(function,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(function,orgPosition.getOrgPosition());
			}
		}
		return wrapper;
	}
}
