package com.kcim.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kcim.common.exception.CostException;
import com.kcim.common.util.BeanUtil;
import com.kcim.common.util.PageUtils;
import com.kcim.common.util.UserContext;
import com.kcim.dao.mapper.RoleMapper;
import com.kcim.dao.model.Role;
import com.kcim.dao.model.dto.RoleEditDTO;
import com.kcim.dao.model.dto.RoleSaveDTO;
import com.kcim.vo.RoleVO;
import com.kcim.vo.SessionUserVO;
import com.kcim.service.RoleService;
import com.kcim.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    private final UserService userService;


    public RoleServiceImpl(UserService userService) {
        this.userService = userService;
    }

    /**
     * 保存角色
     *
     * @param roleSaveDTO {@link RoleSaveDTO}
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveRole(RoleSaveDTO roleSaveDTO) {
        Role role = BeanUtil.convertObj(roleSaveDTO, Role.class);
        SessionUserVO user = UserContext.getCurrentUser();
        role.setCreateUserId(user.getId())
                .setHospId(user.getHospId())
                .setCreateTime(System.currentTimeMillis());
        this.save(role);
    }

    /**
     * 查询角色列表并分页
     *
     * @param page     页码
     * @param pageSize 每页展示数据条数
     * @param keyword  模糊匹配关键字
     * @return {@link PageUtils} 分页对象
     */
    @Override
    public PageUtils selectList(Integer page, Integer pageSize, String keyword, String startDate, String endDate) {
        long startTime=0L;
        long endTime=0L;
        if (StrUtil.isNotBlank(startDate) && StrUtil.isNotBlank(endDate)){
            DateTime startDateTime = DateUtil.parseDate(startDate);
            startTime = DateUtil.beginOfDay(startDateTime).getTime();
            endTime = DateUtil.endOfDay(DateUtil.parseDate(endDate)).getTime();
        }

        Page<Role> rolePage = new Page<>(page, pageSize);
        Page<Role> pages = this.page(rolePage,
                new LambdaQueryWrapper<Role>().eq(Role::getHospId, UserContext.getHospId())
                        .and(StrUtil.isNotBlank(keyword), i -> i.eq(Role::getRoleName, keyword)
                                .or()
                                .eq(Role::getRemark, keyword))
                        .between((StrUtil.isNotBlank(startDate) && StrUtil.isNotBlank(endDate)), Role::getCreateTime, startTime, endTime)
        );
        List<Role> records = pages.getRecords();
        List<RoleVO> list = records.stream().map(i -> {
            RoleVO roleVO = BeanUtil.convertObj(i, RoleVO.class);
            roleVO.setModifyUserName(userService.getUsernameByIdAndHospId(i.getCreateUserId(), UserContext.getHospId()));
            roleVO.setModifyTime(DateUtil.formatDateTime(DateUtil.date(i.getCreateTime())));
//            List<CommonVO> users = userRoleService.getUsersByRoleId(i.getRoleId(), user.getHospId());
//            roleVO.setUsers(users);
            return roleVO;
        }).collect(Collectors.toList());

        return new PageUtils(list, (int) pages.getTotal(), pageSize, page);
    }


    /**
     * 编辑某个角色
     *
     * @param roleEditDTO {@link RoleEditDTO}
     * @param userId      当前登录人id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateRole(RoleEditDTO roleEditDTO, Long userId) {
        Role byId = this.getById(roleEditDTO.getRoleId());
        if (Objects.isNull(byId)) {
            throw new CostException(500, "选择的角色已被移除");
        }
        BeanUtil.convertObj(roleEditDTO, byId);
        byId.setCreateTime(System.currentTimeMillis());
        byId.setCreateUserId(userId);

        log.info("byId:{}", byId);
        this.updateById(byId);
    }

    /**
     * 批量删除角色信息
     *
     * @param asList 角色的Id集合
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteByIds(List<Long> asList) {
        this.removeByIds(asList);
    }
}