/*
*  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.youchain.basicdata.domain.BillType;
import com.youchain.businessdata.domain.Asn;
import com.youchain.businessdata.domain.AsnDetail;
import com.youchain.businessdata.repository.AsnDetailRepository;
import com.youchain.exception.handler.ApiResult;
import com.youchain.utils.*;
import lombok.Data;
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 org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

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

/**
* @website https://eladmin.vip
* @description 服务实现
* @author hjl
* @date 2024-02-29
**/
@Service
@RequiredArgsConstructor
public class AsnServiceImpl implements AsnService {

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

    @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(rollbackFor = Exception.class)
    public AsnDto create(Asn resources) {
        Asn asn = addAsn(resources.getBillType(), resources.getRelatedBill1(),resources.getStructure(), "WMS",null);
        return asnMapper.toDto(asn);
    }

    @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) {
            asnRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AsnDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AsnDto asn : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("仓库ID", asn.getDept());
            map.put("单据类型ID", asn.getBillType());
            map.put("订单来源", asn.getOrderOrigin());
            map.put("货主", asn.getStructure());
            map.put("操作时间", asn.getErTime());
            map.put("系统单号", asn.getRelatedBill1());
            map.put("客户订单号", asn.getRelatedBill2());
            map.put("来源名称", asn.getSourceName());
            map.put("订单状态", asn.getStatus());
            map.put("地址", asn.getAddress());
            map.put("创建人", asn.getCreateBy());
            map.put("修改人", asn.getUpdateBy());
            map.put("创建时间", asn.getCreateTime());
            map.put("修改时间", asn.getUpdateTime());
            map.put("订单时间", asn.getOrderDate());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Asn addAsn(BillType billType, String relatedBill1, String structure,String orderOrigin, Timestamp erTime) {
        Asn asn;
        asn = asnRepository.findByRelatedBill1(relatedBill1);
        if (asn==null){
            asn = new Asn();
            asn.setStatus(BizStatus.OPEN);
        }
        asn.setBillType(billType);
        asn.setDept(UserUtils.getDept());
        asn.setRelatedBill1(relatedBill1);
        asn.setStructure(structure);
        asn.setOrderOrigin(orderOrigin);
        asn.setErTime(erTime);
        asnRepository.save(asn);
        return asn;
    }

    @Override
    public List<Asn> getAsnList() {
        return asnRepository.findAll();
    }

    @Override
    public ApiResult startAsn(String id) {
        Asn asn=asnRepository.getById(Long.valueOf(id));
        if (asn.getStatus().equals(BizStatus.OPEN)) {
            asn.setStatus(BizStatus.RECEIVING);
            asnRepository.save(asn);
        }else {
            //状态错误
           return ApiResult.success(500,"状态错误!",id);
        }
        return ApiResult.success(200,"操作成功!",id);
    }
}