package com.zhongshu.card.server.core.dao.org.impl;

import com.github.microservice.components.data.mongo.mongo.helper.DBHelper;
import com.zhongshu.card.client.model.org.OrganizationUserSearch;
import com.zhongshu.card.server.core.dao.BaseImpl;
import com.zhongshu.card.server.core.dao.org.DepartmentDao;
import com.zhongshu.card.server.core.dao.org.RoleDao;
import com.zhongshu.card.server.core.dao.org.extend.OrganizationUserDaoExtend;
import com.zhongshu.card.server.core.domain.org.Department;
import com.zhongshu.card.server.core.domain.org.OrganizationUser;
import com.zhongshu.card.server.core.domain.org.Role;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author TRX
 * @CreateDate: 2023/4/12
 * @Version: 1.0
 */
public class OrganizationUserDaoImpl extends BaseImpl implements OrganizationUserDaoExtend {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DBHelper dbHelper;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Override
    public Page<OrganizationUser> page(Pageable pageable, OrganizationUserSearch param) {
        Criteria criteria = buildFilterCriteria(param);

        Sort sort = buildSort(param);
        Query query = Query.query(criteria);
        query.with(sort);
        return dbHelper.pages(query, pageable, OrganizationUser.class);
    }

    @Override
    public long countUser(OrganizationUserSearch param) {
        Criteria criteria = buildFilterCriteria(param);
        Query query = Query.query(criteria);
        return mongoTemplate.count(query, OrganizationUser.class);
    }

    private Criteria buildFilterCriteria(OrganizationUserSearch param) {
        Criteria criteria = buildCriteriaNotOid(param);

        // 用户ID
        if (StringUtils.isNotEmpty(param.getUserId())) {
            criteria.and("userId").is(param.getUserId());
        }

        // 机构ID
        if (StringUtils.isNotEmpty(param.getOid())) {
            criteria.and("oid").is(param.getOid());
        }

        // 在这个机构的状态，是否可用
        if (param.getState() != null) {
            criteria.and("state").is(param.getState());
        }

        // 用户在机构的类型
        if (param.getUserType() != null) {
            criteria.and("userType").is(param.getUserType());
        }

        // 机构类型
        if (param.getAuthType() != null) {
            criteria.and("authType").is(param.getAuthType());
        }

        // 不属于某种类型机构
        if (param.getNotAuthType() != null) {
            criteria.and("authType").ne(param.getNotAuthType());
        }

        // 在机构里是否是管理员
        if (param.getIsAdmin() != null) {
            criteria.and("isAdmin").is(param.getIsAdmin());
        }

        // 职位
        if (StringUtils.isNotEmpty(param.getPositionId())) {
            criteria.and("position.id").is(param.getPositionId());
        }

        // 性别
        if (param.getSex() != null) {
            criteria.and("sex").is(param.getSex());
        }

        // 角色
        List<String> roleIds = param.getRoleIds();
        if (ObjectUtils.isNotEmpty(roleIds)) {
            List<Role> roles = roleDao.findByIdIn(roleIds);
            criteria.and("roles").in(roles);
        }

        // 部门
        List<String> departmentIds = param.getDepartmentIds();
        if (ObjectUtils.isNotEmpty(departmentIds)) {
            List<Department> roles = departmentDao.findByIdIn(departmentIds);
            criteria.and("departments").in(roles);
        }

        // 搜索项目的用户
        if (param.getIsSearchProject() != null && param.getIsSearchProject()) {
            criteria.and("projectOid").is(param.getProjectOid());
        }

        // 搜索是否是结构的用户
        if (param.getIsOrg() != null) {
            criteria.and("isOrg").is(param.getIsOrg());
        }

        // 模糊搜索
        List<Criteria> criterias = new ArrayList<>();
        // 用户名称
        if (StringUtils.isNotEmpty(param.getName())) {
            Pattern pattern = Pattern.compile("^.*" + param.getName() + ".*$");
            criterias.add(Criteria.where("name").is(pattern));
        }
        // 登录名
        if (StringUtils.isNotEmpty(param.getLoginName())) {
            Pattern pattern = Pattern.compile("^.*" + param.getLoginName() + ".*$");
            criterias.add(Criteria.where("loginName").is(pattern));
        }
        // 电话号码
        if (StringUtils.isNotEmpty(param.getPhone())) {
            Pattern pattern = Pattern.compile("^.*" + param.getPhone() + ".*$");
            criterias.add(Criteria.where("phone").is(pattern));
        }
        if (!CollectionUtils.isEmpty(criterias)) {
            criteria.andOperator(criterias.toArray(new Criteria[]{}));
        }
        // 关键字搜索
        if (StringUtils.isNotEmpty(param.getKeyWord())) {
            Pattern pattern = Pattern.compile("^.*" + param.getKeyWord() + ".*$");
            criteria.orOperator(Criteria.where("name").regex(pattern), Criteria.where("phone").regex(pattern), Criteria.where("code").regex(pattern));
        }
        return criteria;
    }

}
