/*
*  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.Purchase;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.PurchaseRepository;
import me.zhengjie.modules.system.service.PurchaseService;
import me.zhengjie.modules.system.service.dto.PurchaseDto;
import me.zhengjie.modules.system.service.dto.PurchaseQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.PurchaseMapper;
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.sql.Timestamp;
import java.time.LocalDateTime;
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;
import me.zhengjie.utils.PageResult;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author author
* 
**/
@Service
@RequiredArgsConstructor
public class PurchaseServiceImpl implements PurchaseService {

    private final PurchaseRepository purchaseRepository;
    private final PurchaseMapper purchaseMapper;

    @Override
    public PageResult<PurchaseDto> queryAll(PurchaseQueryCriteria criteria, Pageable pageable){
        Page<Purchase> page = purchaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(purchaseMapper::toDto));
    }

    @Override
    public List<PurchaseDto> queryAll(PurchaseQueryCriteria criteria){
        return purchaseMapper.toDto(purchaseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public PurchaseDto findById(Long purchaseId) {
        Purchase purchase = purchaseRepository.findById(purchaseId).orElseGet(Purchase::new);
        ValidationUtil.isNull(purchase.getPurchaseId(),"Purchase","purchaseId",purchaseId);
        return purchaseMapper.toDto(purchase);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Purchase resources) {
        resources.setApplyTime(Timestamp.valueOf(LocalDateTime.now()));
        purchaseRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Purchase resources) {
        Purchase purchase = purchaseRepository.findById(resources.getPurchaseId()).orElseGet(Purchase::new);
        ValidationUtil.isNull( purchase.getPurchaseId(),"Purchase","id",resources.getPurchaseId());
        purchase.copy(resources);
        purchaseRepository.save(purchase);
    }

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

    @Override
    public void download(List<PurchaseDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PurchaseDto purchase : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("申请人", purchase.getUser().getNickName());
            map.put("申请事由", purchase.getReason());
            map.put("申请金额", purchase.getFee());
            map.put("货物/服务名称", purchase.getProductName());
            map.put("申请类型", purchase.getPurchaseType());
            map.put("品牌/规格/参数", purchase.getProductInfo());
            map.put("数量", purchase.getProductCount());
            map.put("预算单价", purchase.getProductPrice());
            map.put("预算总价", purchase.getTotalFee());
            map.put("资金来源", purchase.getFeeSource());
            map.put("项目名称", purchase.getProjectName());
            map.put("项目编号", purchase.getProjectNo());
            map.put("预计采购时间", purchase.getPurchaseTime());
            map.put("申请时间", purchase.getApplyTime());
            map.put("备注", purchase.getRemark());
            map.put("创建者", purchase.getCreateBy());
            map.put("更新者", purchase.getUpdateBy());
            map.put("创建日期", purchase.getCreateTime());
            map.put("更新时间", purchase.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}