/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.dm.user.service.impl;

import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.dm.user.domain.DmUser;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dm.user.repository.DmUserRepository;
import me.zhengjie.modules.dm.user.service.DmUserService;
import me.zhengjie.modules.dm.user.service.dto.DmUserDto;
import me.zhengjie.modules.dm.user.service.dto.DmUserQueryCriteria;
import me.zhengjie.modules.dm.user.service.mapstruct.DmUserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author shiguangji
* @date 2021-03-09
**/
@Service
@RequiredArgsConstructor
public class DmUserServiceImpl implements DmUserService {

    private final DmUserRepository dmUserRepository;
    private final DmUserMapper dmUserMapper;
   /* private final UserService userService;
    private final UserRepository userRepository;*/

    @Override
    public Map<String,Object> queryAll(DmUserQueryCriteria criteria, Pageable pageable){
        Page<DmUser> page = dmUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dmUserMapper::toDto));
    }

    @Override
    public List<DmUserDto> queryAll(DmUserQueryCriteria criteria){
        return dmUserMapper.toDto(dmUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmUserDto findById(String id) {
        DmUser dmUser = dmUserRepository.findById(id).orElseGet(DmUser::new);
        ValidationUtil.isNull(dmUser.getId(),"DmUser","id",id);
        return dmUserMapper.toDto(dmUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmUserDto create(DmUser resources) {
//        resources.setId(IdUtil.simpleUUID());
        //判断邮箱是否重复
        DmUser user = dmUserRepository.findByEmail(resources.getEmail());
        if (user != null) {
            throw new EntityExistException(DmUser.class, "email", resources.getEmail());
        }
        return dmUserMapper.toDto(dmUserRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmUser resources) {
        DmUser dmUser = dmUserRepository.findById(resources.getId()).orElseGet(DmUser::new);
        ValidationUtil.isNull( dmUser.getId(),"DmUser","id",resources.getId());
        //判断邮箱是否重复
        DmUser user = dmUserRepository.findByEmail(resources.getEmail());
        if (user != null && !dmUser.getId().equals(user.getId())) {
            throw new EntityExistException(DmUser.class, "email", resources.getEmail());
        }
        dmUser.copy(resources);
        dmUserRepository.save(dmUser);

    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            dmUserRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DmUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmUserDto dmUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("姓名", dmUser.getName());
            map.put("性别", dmUser.getSex());
            map.put("联系方式", dmUser.getContacts());
            map.put("邮箱", dmUser.getEmail());
            map.put("部门", dmUser.getDept() != null ? dmUser.getDept().getName() : "");
            map.put("是否是审批人", dmUser.getIsApprover());
            map.put("创建者", dmUser.getCreateBy());
            map.put("更新者", dmUser.getUpdateBy());
            /*map.put("创建日期", dmUser.getCreateTime());
            map.put("更新时间", dmUser.getUpdateTime());*/
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<DmUser> findNotBindUser(Long userId) {
        String param = "";
        if(userId != null){
            param = userId+"";
        }
        return dmUserRepository.findNotBindUser(param);
    }
}