package org.springblade.flow.permission.service;

import java.util.ArrayList;
import java.util.List;

import org.springblade.flow.base.Pagination;
import org.springblade.flow.permission.entity.OrganizeEntity;
import org.springblade.flow.permission.entity.PositionEntity;
import org.springblade.flow.permission.entity.Role4FlowEntity;
import org.springblade.flow.permission.entity.UserEntity;
import org.springblade.flow.permission.mapper.User4FlowMapper;
import org.springblade.flow.permission.model.user.UserAllModel;
import org.springblade.flow.util.JsonUtil;
import org.springblade.flow.util.StringUtil;
import org.springblade.flow.util.UploaderUtil;
import org.springblade.flow.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollUtil;

/**
 *  服务类
 *
 * @author william
 * @date   2022-07-14 10:57:53
 */
@Service
public class User4FlowService extends ServiceImpl<User4FlowMapper, UserEntity> {

	@Autowired
	private UserProvider userProvider;
	@Autowired
	private OrganizeService organizeService;
	@Autowired
	private PositionService positionService;
	@Autowired
	private Role4FlowService roleService;

	public List<UserEntity> getList(Pagination pagination, String organizeId) {
		String userId = userProvider.getUserId();
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().ne(UserEntity::getId, userId);
		// 组织机构
		if (!StringUtil.isEmpty(organizeId)) {
			String[] organizeIds = organizeId.split(",");
			if (organizeIds != null && organizeIds.length > 0) {
				queryWrapper.lambda().in(UserEntity::getOrganizeId, CollUtil.newArrayList(organizeIds));
			}
		}
		// 关键字（账户、姓名、手机）
		if (!StringUtil.isEmpty(pagination.getKeyword())) {
			queryWrapper.lambda()
					.and(t -> t.like(UserEntity::getAccount, pagination.getKeyword()).or()
							.like(UserEntity::getRealName, pagination.getKeyword()).or()
							.like(UserEntity::getMobilePhone, pagination.getKeyword()));
		}
		// 排序
		queryWrapper.lambda().orderByAsc(UserEntity::getId).orderByDesc(UserEntity::getCreateTime);
		Page<UserEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
		IPage<UserEntity> iPage = this.page(page, queryWrapper);
		return pagination.setData(iPage.getRecords(), iPage.getTotal());
	}

	public List<String> getAllUserIds() {
		return baseMapper.getAllUserIds();
	}

	public boolean isExistUser(String account) {
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(UserEntity::getAccount, account).eq(UserEntity::getEnabledMark, 1)
				.eq(UserEntity::getIsDeleted, 0);
		return getOne(queryWrapper) != null;
	}

	public UserEntity getInfo(String id) {
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(UserEntity::getId, id);
		return getOne(queryWrapper);
	}

	public UserEntity getUserEntity(String account) {
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(UserEntity::getAccount, account);
		return baseMapper.selectOne(queryWrapper);
	}

	public List<UserEntity> getList() {
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().orderByAsc(UserEntity::getId).eq(UserEntity::getEnabledMark, 1)
				.eq(UserEntity::getIsDeleted, 0);
		return list(queryWrapper);
	}

	public List<UserEntity> getEnableMarkList(int enableMark) {
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(UserEntity::getEnabledMark, Integer.valueOf(enableMark));
		queryWrapper.lambda().orderByAsc(UserEntity::getId);
		return list(queryWrapper);
	}

	public List<UserAllModel> getAll() {
		List<UserEntity> list = this.getEnableMarkList(1);
		// 获取全部部门信息
		List<OrganizeEntity> departmentList = organizeService.getList();
		// 获取全部岗位信息
		List<PositionEntity> positionList = positionService.getList();
		// 获取全部角色信息
		List<Role4FlowEntity> roleList = roleService.getList();
		List<UserAllModel> models = JsonUtil.getJsonToList(list, UserAllModel.class);
		for (UserAllModel model : models) {
			// 部门名称
			OrganizeEntity deptEntity = departmentList.stream().filter(t -> t.getId().equals(model.getOrganizeId()))
					.findFirst().orElse(new OrganizeEntity());
			if (StringUtil.isNotEmpty(deptEntity.getFullName())) {
				model.setDepartment(deptEntity.getFullName());
				model.setDepartmentId(deptEntity.getId());
			}
			// 组织名称
			OrganizeEntity organizeEntity = departmentList.stream()
					.filter(t -> t.getId().equals(String.valueOf(deptEntity.getParentId()))).findFirst()
					.orElse(new OrganizeEntity());
			if (organizeEntity != null) {
				model.setOrganizeId(organizeEntity.getId());
				model.setOrganize(organizeEntity.getFullName());
			}
			// 岗位名称(多个)
			if (model.getPositionId() != null) {
				List<String> positionName = new ArrayList<>();
				for (String id : model.getPositionId().split(",")) {
					String name = positionList.stream().filter(t -> t.getId().equals(id)).findFirst()
							.orElse(new PositionEntity()).getFullName();
					if (!StringUtil.isEmpty(name)) {
						positionName.add(name);
					}
				}
				model.setPositionName(String.join(",", positionName));
			}
			// 角色名称(多个)
			if (model.getRoleId() != null) {
				List<String> roleName = new ArrayList<>();
				for (String id : model.getRoleId().split(",")) {
					String name = roleList.stream().filter(t -> t.getId().equals(id)).findFirst()
							.orElse(new Role4FlowEntity()).getFullName();
					if (!StringUtil.isEmpty(name)) {
						roleName.add(name);
					}
				}
				model.setRoleName(String.join(",", roleName));
			}
			// 主管名称
			String managerName = list.stream().filter(t -> t.getId().equals(model.getManagerId())).findFirst()
					.orElse(new UserEntity()).getRealName();
			if (StringUtil.isNotEmpty(managerName)) {
				model.setManagerName(managerName);
			}
			model.setHeadIcon(UploaderUtil.uploaderImg(model.getHeadIcon()));
		}
		return models;
	}

	public List<UserAllModel> getDbUserAll() {
		List<UserEntity> list = this.getList();
		// 获取全部部门信息
		List<OrganizeEntity> departmentList = organizeService.getList();
		// 获取全部岗位信息
		List<PositionEntity> positionList = positionService.getList();
		// 获取全部角色信息
		List<Role4FlowEntity> roleList = roleService.getList();
		List<UserAllModel> models = JsonUtil.getJsonToList(list, UserAllModel.class);
		for (UserAllModel model : models) {
			// 部门名称
			OrganizeEntity organize = departmentList.stream().filter(t -> t.getId().equals(model.getOrganizeId()))
					.findFirst().orElse(new OrganizeEntity());
			if (StringUtil.isNotEmpty(organize.getFullName())) {
				model.setDepartment(organize.getFullName());
			}
			// 组织名称
			String organizeName = departmentList.stream()
					.filter(t -> t.getId().equals(String.valueOf(organize.getParentId()))).findFirst()
					.orElse(new OrganizeEntity()).getFullName();
			if (StringUtil.isNotEmpty(organizeName)) {
				model.setOrganize(organizeName);
			}
			// 岗位名称(多个)
			if (model.getPositionId() != null) {
				List<String> positionName = new ArrayList<>();
				for (String id : model.getPositionId().split(",")) {
					String name = positionList.stream().filter(t -> t.getId().equals(id)).findFirst()
							.orElse(new PositionEntity()).getFullName();
					positionName.add(name);
				}
				model.setPositionName(String.join(",", positionName));
			}
			// 角色名称(多个)
			if (model.getRoleId() != null) {
				List<String> roleName = new ArrayList<>();
				for (String id : model.getRoleId().split(",")) {
					String name = roleList.stream().filter(t -> t.getId().equals(id)).findFirst()
							.orElse(new Role4FlowEntity()).getFullName();
					roleName.add(name);
				}
				model.setRoleName(String.join(",", roleName));
			}
			// 主管名称
			String managerName = list.stream().filter(t -> t.getId().equals(model.getManagerId())).findFirst()
					.orElse(new UserEntity()).getRealName();
			if (StringUtil.isNotEmpty(managerName)) {
				model.setManagerName(managerName);
			}
			model.setHeadIcon(UploaderUtil.uploaderImg(model.getHeadIcon()));
		}
		return models;
	}
}