package org.springblade.system.expand.wrapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.springblade.core.mp.support.BaseEntityWrapper;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.cache.DictCache;
import org.springblade.system.cache.SysCache;
import org.springblade.system.entity.Dept;
import org.springblade.system.entity.Tenant;
import org.springblade.system.expand.entity.OrgPosition;
import org.springblade.system.expand.service.IOrgPositionService;
import org.springblade.system.expand.vo.UserVO;
import org.springblade.system.user.entity.User;
import org.springframework.util.Assert;


import java.util.List;
import java.util.Objects;

/**
 * Created By lidexi in 2021/3/24
 **/
public class UserWrapper extends BaseEntityWrapper<User, UserVO> {

	private IOrgPositionService orgPositionService;

	public UserWrapper(IOrgPositionService orgPositionService) {
		this.orgPositionService = orgPositionService;
	}

	public static UserWrapper build(IOrgPositionService orgPositionService) {
		return new UserWrapper(orgPositionService);
	}

	@Override
	public UserVO entityVO(User user) {
		UserVO userVO = Objects.requireNonNull(BeanUtil.copy(user,UserVO.class));
		Tenant tenant = SysCache.getTenant(user.getTenantId());
		List<String> roleName = SysCache.getRoleNames(user.getRoleId());
		List<String> deptName = SysCache.getDeptNames(user.getDeptId());
		String[] deptIds = user.getDeptId().split(",");
		StringBuilder stringBuilder = new StringBuilder();
		StringBuilder stringBuilder1 = new StringBuilder();
		for(String deptId : deptIds){
			Dept dept = SysCache.getDept(Long.valueOf(deptId));
			stringBuilder.append(dept.getDeptCategory()+",");

			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptId));
			if(orgPosition != null){
				stringBuilder1.append(orgPosition.getOrgPosition()+",");
			}
		}
		String deptType = stringBuilder.toString().substring(0,stringBuilder.toString().length()-1);
		Assert.isTrue(stringBuilder1.length() > 0, "请先绑定机构路径");
		String orgPosition = stringBuilder1.toString().substring(0,stringBuilder1.toString().length()-1);
		userVO.setOrgPosition(orgPosition);
		userVO.setDeptType(deptType);
		List<String> postName = SysCache.getPostNames(user.getPostId());
		if(tenant != null){
			userVO.setTenantName(tenant.getTenantName());
		}

		userVO.setRoleName(Func.join(roleName));
		userVO.setDeptName(Func.join(deptName));
		userVO.setPostName(Func.join(postName));
		userVO.setSexName(DictCache.getValue("sex", Func.toInt(user.getSex())));
		return userVO;
	}

}
