/*
 *  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 com.youchain.businessdata.service.impl;

import com.google.common.collect.Maps;
import com.youchain.businessdata.domain.Asn;
import com.youchain.businessdata.domain.AsnDetail;
import com.youchain.businessdata.repository.AsnDetailRepository;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.AsnRepository;
import com.youchain.businessdata.service.AsnService;
import com.youchain.businessdata.service.dto.AsnDto;
import com.youchain.businessdata.service.dto.AsnQueryCriteria;
import com.youchain.businessdata.service.mapstruct.AsnMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JiangKun
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-01-09
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class AsnServiceImpl implements AsnService {

    private final AsnRepository asnRepository;
    private final AsnMapper asnMapper;
    private final AsnDetailRepository asnDetailRepository;
    private final CodeUtils codeUtils;


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

    @Override
    public List<AsnDto> queryAll(AsnQueryCriteria criteria) {
        return asnMapper.toDto(asnRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public AsnDto findById(Long id) {
        Asn asn = asnRepository.findById(id).orElseGet(Asn::new);
        ValidationUtil.isNull(asn.getId(), "Asn", "id", id);
        return asnMapper.toDto(asn);
    }

    @Override
    @Transactional
    public Asn getEntity(Long id) {
        Asn asn = asnRepository.findById(id).orElseGet(Asn::new);
        return asn;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AsnDto create(Asn resources) {
        resources.setCode(codeUtils.getCode_yyMMdd(resources.getBillType().getCode(), 3));
        return asnMapper.toDto(asnRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Asn resources) {
        Asn asn = asnRepository.findById(resources.getId()).orElseGet(Asn::new);
        ValidationUtil.isNull(asn.getId(), "Asn", "id", resources.getId());
        asn.copy(resources);
        asnRepository.save(asn);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            //删除附表
//            AsnDto byId = this.findById(id);
            List<AsnDetail> asnDetails = asnDetailRepository.queryByAsnId(id);
            if (!asnDetails.isEmpty()) {
                for (AsnDetail a : asnDetails) {
                    asnDetailRepository.deleteById(a.getId());
                }
            }
            asnRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AsnDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AsnDto asn : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("单号", asn.getCode());
            map.put("库区", asn.getArea().getCode());
            map.put("状态", asn.getStatus());
            map.put("客户订单号", asn.getCusCode());
            map.put("相关单号1", asn.getRelatedBill1());
            map.put("相关单号2", asn.getRelatedBill2());
            map.put("相关单号3", asn.getRelatedBill3());
            map.put("订单日期", asn.getOrderDate());
            map.put("预计到货日期", asn.getEstimateDate());
            map.put("收货日期", asn.getReceivedDate());
            map.put("发货方", asn.getFromName());
            map.put("发货地址", asn.getFromAddress());
            map.put("发货联系人", asn.getFromMan());
            map.put("发货电话", asn.getFromTel());
            map.put("订单数量", asn.getOrderQuantity());
            map.put("收货数量", asn.getReceivedQuantity());
            map.put("上架数量", asn.getPutawayQuantity());
            map.put("车牌号", asn.getVehicle());
            map.put("单据类型", asn.getBillType().getCode());
            map.put("仓库ID", asn.getDept().getName());
            map.put("备注", asn.getDescription());
            map.put("创建人", asn.getCreateBy());
            map.put("修改人", asn.getUpdateBy());
            map.put("创建时间", asn.getCreateTime());
            map.put("修改时间", asn.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<Asn> queryByCusCodes(List<String> asnCodes) {
        if (CollectionUtils.isEmpty(asnCodes)) {
            return Collections.emptyList();
        }
        //去重
        asnCodes = asnCodes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        return asnRepository.queryByCusCodes(asnCodes);
    }

    @Override
    public Map<String, Asn> queryByCusCodesToMap(List<String> cusCodes) {
        List<Asn> asnList = queryByCusCodes(cusCodes);
        //封装成map
        Map<String, Asn> asnMap = Maps.newHashMap();
        for (Asn asn : asnList) {
            asnMap.put(asn.getCusCode(), asn);
        }
        return asnMap;
    }


}