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

import me.zhengjie.modules.system.domain.UserBank;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.UserBankRepository;
import me.zhengjie.modules.system.service.UserBankService;
import me.zhengjie.modules.system.service.dto.UserBankDto;
import me.zhengjie.modules.system.service.dto.UserBankQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.UserBankMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
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;

import me.zhengjie.utils.PageResult;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author author
* @date 2023-10-31
**/
@Service
@RequiredArgsConstructor
public class UserBankServiceImpl implements UserBankService {

    private final UserBankRepository userBankRepository;
    private final UserBankMapper userBankMapper;


    @Override
    public PageResult<UserBankDto> queryAll(UserBankQueryCriteria criteria, Pageable pageable){
        Page<UserBank> page = userBankRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(userBankMapper::toDto));
    }

    @Override
    public List<UserBankDto> queryAll(UserBankQueryCriteria criteria){
        return userBankMapper.toDto(userBankRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public UserBankDto findById(Long bankId) {
        UserBank userBank = userBankRepository.findById(bankId).orElseGet(UserBank::new);
        ValidationUtil.isNull(userBank.getBankId(),"UserBank","bankId",bankId);
        return userBankMapper.toDto(userBank);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(UserBank resources) {
        if (resources.getBankUse() == null){
            resources.setBankUse("否");
        }
        handleBankUse(resources);
        userBankRepository.save(resources);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(UserBank resources) {
        handleBankUse(resources);
        UserBank userBank = userBankRepository.findById(resources.getBankId()).orElseGet(UserBank::new);
        ValidationUtil.isNull( userBank.getBankId(),"UserBank","id",resources.getBankId());
        userBank.copy(resources);
        userBankRepository.save(userBank);
    }

    /**
     * 常用银行卡处理
     * */
    private void handleBankUse(UserBank resources) {
        if (Objects.equals("是", resources.getBankUse())) {
             userBankRepository.findByBankUseAndUser("是", resources.getUser()).ifPresent(userBank ->{
                 userBank.setBankUse("否");
                 userBankRepository.save(userBank);
             });
        }
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long bankId : ids) {
            userBankRepository.deleteById(bankId);
        }
    }

    @Override
    public void download(List<UserBankDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (UserBankDto userBank : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("所属用户", userBank.getUser().getNickName());
            map.put("银行卡号", userBank.getBankNo());
            map.put("银行卡所属支行", userBank.getBankName());
            map.put("是否常用账号", userBank.getBankUse());
            map.put("备注", userBank.getRemark());
            map.put("创建者", userBank.getCreateBy());
            map.put("更新者", userBank.getUpdateBy());
            map.put("创建日期", userBank.getCreateTime());
            map.put("更新时间", userBank.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}