package com.cf.imes.module.system.dal.mysql.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.cf.imes.framework.common.enums.CommonStatusEnum;
import com.cf.imes.framework.common.exception.util.ServiceExceptionUtil;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.framework.mybatis.core.mapper.BaseMapperX;
import com.cf.imes.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cf.imes.framework.organ.core.aop.OrganIgnore;
import com.cf.imes.framework.security.core.LoginUser;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.executor.enums.OrderDeletedEnum;
import com.cf.imes.module.system.controller.admin.user.vo.user.UserPageReqVO;
import com.cf.imes.module.system.dal.dataobject.user.AdminUserDO;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

import static com.cf.imes.module.system.enums.ErrorCodeConstants.USERNAME_MULTIPLE_ERROR;

@Mapper
public interface AdminUserMapper extends BaseMapperX<AdminUserDO> {

    default AdminUserDO selectByUsername(String username, Long organId) {
        organId = Objects.isNull(organId) ? SecurityFrameworkUtils.getLoginUser().getOrganId(): organId;
       return selectOne(new LambdaQueryWrapperX<AdminUserDO>()
               .eq(AdminUserDO::getUsername, username)
               .eqIfPresent(AdminUserDO::getOrganId, organId)
       );
    }

    /**
     * 用户名查询唯一用户，存在多个用户抛出业务异常
     *
     * @param userName
     * @return
     */
    @OrganIgnore
    default AdminUserDO selectByUsernameUnique(String userName) {
        AdminUserDO adminUserDO = null;
        List<AdminUserDO> adminUserDOS = selectList(new LambdaQueryWrapperX<AdminUserDO>()
                .eq(AdminUserDO::getUsername, userName));
        if (CollUtil.isNotEmpty(adminUserDOS)) {
            if (adminUserDOS.size() > 1) {
                throw ServiceExceptionUtil.exception(USERNAME_MULTIPLE_ERROR, userName);
            }
            adminUserDO = adminUserDOS.get(0);
        }
        return adminUserDO;
    }

    default AdminUserDO selectByEmail(String email) {
        return selectOne(AdminUserDO::getEmail, email);
    }

    default AdminUserDO selectByMobile(String mobile) {
        return selectOne(AdminUserDO::getMobile, mobile);
    }

    default PageResult<AdminUserDO> selectPage(UserPageReqVO reqVO, Collection<Long> deptIds) {
        LambdaQueryWrapperX<AdminUserDO> lambdaQueryWrapperX = new LambdaQueryWrapperX<>();
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        assert loginUser != null;
        if (SecurityFrameworkUtils.isCfOrg()) {
            if (!Objects.isNull(reqVO.getOrganId())) {
                // 管理端晨丰组织看全部组织下的
                lambdaQueryWrapperX.eqIfPresent(AdminUserDO::getOrganId, reqVO.getOrganId());
            } else if(!SecurityFrameworkUtils.isManageEndPoint()){
                // 生产端晨丰组织只看晨丰组织下的
                lambdaQueryWrapperX.eqIfPresent(AdminUserDO::getOrganId, loginUser.getOrganId());
            }
        } else {
            lambdaQueryWrapperX.eqIfPresent(AdminUserDO::getOrganId, loginUser.getOrganId());
        }
        return selectPage(reqVO, lambdaQueryWrapperX
                .likeIfPresent(AdminUserDO::getUsername, reqVO.getUsername())
                .likeIfPresent(AdminUserDO::getMobile, reqVO.getMobile())
                .eqIfPresent(AdminUserDO::getStatus, reqVO.getStatus())
                .betweenIfPresent(AdminUserDO::getCreateTime, reqVO.getCreateTime())
                .inIfPresent(AdminUserDO::getDeptId, deptIds)
                .and(CharSequenceUtil.isNotBlank(reqVO.getNickname()), wrapper -> {
                    if (CharSequenceUtil.isNotBlank(reqVO.getPyAll())) {
                        wrapper.or(Boolean.TRUE).like(AdminUserDO::getPinyinFull, reqVO.getPyAll()) ;
                    }
                    if (CharSequenceUtil.isNotBlank(reqVO.getPyFirstChar())) {
                        wrapper.or(Boolean.TRUE).like(AdminUserDO::getPinyinInitial, reqVO.getPyFirstChar()) ;
                    }
                    if(CharSequenceUtil.isNotBlank(reqVO.getNickname())) {
                        wrapper.or(Boolean.TRUE).like(AdminUserDO::getNickname, reqVO.getNickname()) ;
                    }
                })
                .orderByDesc(AdminUserDO::getId));
    }

    default List<AdminUserDO> selectListByNickname(String nickname) {
        return selectList(new LambdaQueryWrapperX<AdminUserDO>().like(AdminUserDO::getNickname, nickname));
    }

    default List<AdminUserDO> selectListByStatus(Integer status, Long organId, Long deptId) {
        return selectList(new LambdaQueryWrapperX<AdminUserDO>()
                .eqIfPresent(AdminUserDO::getOrganId, organId)
                .eqIfPresent(AdminUserDO::getDeptId, deptId)
                .eq(AdminUserDO::getStatus, status));
       // return selectList(AdminUserDO::getStatus, status);
    }

    default List<AdminUserDO> selectListByDeptIds(Collection<Long> deptIds) {
        return selectList(AdminUserDO::getDeptId, deptIds);
    }

//    default List<AdminUserDO> selectListByTerms(Integer status, String namePyAll,String namePyFirstChar,String name,Long organId) {
//        return selectList(new LambdaQueryWrapperX<AdminUserDO>()
//                .eqIfPresent(AdminUserDO::getStatus, status)
//                .likeIfPresent(AdminUserDO::getNickname, name)
//                .or(StrUtil.isNotBlank(name))
//                .likeIfPresent(AdminUserDO::getPinyinFull, namePyAll)
//                .or(StrUtil.isNotBlank(namePyAll))
//                .likeIfPresent(AdminUserDO::getPinyinInitial, namePyFirstChar)
//                .orderByDesc(AdminUserDO::getId));
//    }
    @OrganIgnore
    List<AdminUserDO> selectListByTerms(@Param("status") Integer status,@Param("namePyAll") String namePyAll,
                                                @Param("namePyFirstChar")String namePyFirstChar,@Param("name") String name,
                                                @Param("organId")Long organId);

    default List<AdminUserDO> selectListByIds(List<Long> userIds, Long userOrganId) {
        return selectList(new LambdaQueryWrapperX<AdminUserDO>()
                .eq(AdminUserDO::getOrganId, userOrganId)
                .in(AdminUserDO::getId, userIds));
    }

    default Integer selectUserCount() {
        return Math.toIntExact(selectCount(new LambdaQueryWrapperX<AdminUserDO>()
                .eq(AdminUserDO::getDeleted, OrderDeletedEnum.NOT_DELETED.getStatus())));
    }

    default Integer selectUserCountAdd() {
        return Math.toIntExact(selectCount(new LambdaQueryWrapperX<AdminUserDO>()
                .eq(AdminUserDO::getDeleted, OrderDeletedEnum.NOT_DELETED.getStatus())
                .between(AdminUserDO::getCreateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT),
                        LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59)))));
    }

    default Integer selectUserCountDel() {
        return Math.toIntExact(selectCount(new LambdaQueryWrapperX<AdminUserDO>()
                .eq(AdminUserDO::getDeleted, OrderDeletedEnum.DELETED.getStatus())
                .between(AdminUserDO::getUpdateTime, LocalDateTime.of(LocalDate.now(), LocalTime.MIDNIGHT),
                        LocalDateTime.of(LocalDate.now(), LocalTime.of(23, 59, 59)))));
    }

    default Integer selectUserCountSilent(LocalDateTime dateTime) {
        return Math.toIntExact(selectCount(new LambdaQueryWrapperX<AdminUserDO>()
                .eq(AdminUserDO::getDeleted, OrderDeletedEnum.NOT_DELETED.getStatus())
                .lt(AdminUserDO::getLoginDate, dateTime)));
    }

    default Integer selectUserActCountTime(LocalDateTime startTime, LocalDateTime endTIme) {
        return Math.toIntExact(selectCount(new LambdaQueryWrapperX<AdminUserDO>()
                .eq(AdminUserDO::getDeleted, OrderDeletedEnum.NOT_DELETED.getStatus())
                .eq(AdminUserDO::getStatus, CommonStatusEnum.ENABLE.getStatus())
                .between(AdminUserDO::getLoginDate, startTime, endTIme)));
    }

    /**
     * 数据库锁id下的数据，注意使用
     *
     * @param id
     * @return
     */
    @Select("SELECT username, password FROM system_users WHERE id = #{id} FOR UPDATE")
    AdminUserDO selectByIdForUpdate(@Param("id") Long id);

    /**
     * 根据id物理删除user
     *
     * @param id
     * @return 改动数量
     */
    @Delete("DELETE FROM system_users WHERE id = #{id}")
    int physicalDeleteById(@Param("id") Long id);

    /**
     * 查询机构下的所有用户
     *
     * @param organId
     * @return
     */
    @Select("SELECT ID FROM system_users WHERE organ_id = #{organId}")
    List<Long> selectAllOrganUsers(@Param("organId") Long organId);

    /**
     * 查询部门下的所有用户
     *
     * @param deptId
     * @return
     */
    @Select("SELECT ID FROM system_users WHERE dept_id = #{deptId}")
    List<Long> selectAllDeptUsers(@Param("deptId") Long deptId);

    List<AdminUserDO> selectUserDataSource(@Param("filed") String filed,@Param("organId")  Long organId,@Param("nameList")  List<String> nameList);

}
