/*
*  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.company.service.impl;

import me.zhengjie.modules.dm.company.domain.DmCompany;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.dm.company.repository.DmCompanyRepository;
import me.zhengjie.modules.dm.company.service.DmCompanyService;
import me.zhengjie.modules.dm.company.service.dto.DmCompanyDto;
import me.zhengjie.modules.dm.company.service.dto.DmCompanyQueryCriteria;
import me.zhengjie.modules.dm.company.service.mapstruct.DmCompanyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

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

    private final DmCompanyRepository dmCompanyRepository;
    private final DmCompanyMapper dmCompanyMapper;
    @Autowired
    private final UserRepository userRepository;

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

    @Override
    public List<DmCompanyDto> queryAll(DmCompanyQueryCriteria criteria){
        return dmCompanyMapper.toDto(dmCompanyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public DmCompanyDto findById(Long companyId) {
        DmCompany dmCompany = dmCompanyRepository.findById(companyId).orElseGet(DmCompany::new);
        ValidationUtil.isNull(dmCompany.getCompanyId(),"DmCompany","companyId",companyId);
        return dmCompanyMapper.toDto(dmCompany);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmCompanyDto create(DmCompany resources) {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        resources.setCompanyId(snowflake.nextId()); 
        return dmCompanyMapper.toDto(dmCompanyRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DmCompany resources) {
        DmCompany dmCompany = dmCompanyRepository.findById(resources.getCompanyId()).orElseGet(DmCompany::new);
        ValidationUtil.isNull( dmCompany.getCompanyId(),"DmCompany","id",resources.getCompanyId());
        dmCompany.copy(resources);
        dmCompanyRepository.save(dmCompany);
    }

    @Override
    public Map<String,Object> deleteAll(Long[] ids) {
        Map<String,Object> map= new HashMap<>();
        List name=userRepository.selectCompanyName(ids);
        for (Long companyId : ids) {
            Integer count = userRepository.selecIsNotCompany(companyId);
            if(count<=0){
                dmCompanyRepository.deleteById(companyId);
            }else {
                map.put("lose",name+"已绑定用户,不能删除");
                map.put("type", "company");
            }
        }
        return map;
    }

    @Override
    public void download(List<DmCompanyDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DmCompanyDto dmCompany : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("单位名称(全称)", dmCompany.getFullName());
            map.put("单位简称", dmCompany.getShortName());
            map.put("单位地址", dmCompany.getAddress());
            map.put("联系方式", dmCompany.getContacts());
            map.put("单位logo", dmCompany.getLogo());
            map.put("单位介绍", dmCompany.getDescription());
            map.put("单位官网", dmCompany.getWebsite());
            map.put("备注", dmCompany.getRemark());
            map.put("注册时间", dmCompany.getRegisterDate());
            map.put("创建者", dmCompany.getCreateBy());
            map.put("更新者", dmCompany.getUpdatedBy());
            map.put("创建日期", dmCompany.getCreateTime());
            map.put("更新时间", dmCompany.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}