/*
*  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.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.repository.PointRepository;
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 PointRepository pointRepository;
    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 relatedBill2, String structure,String orderOrigin, Timestamp erTime) {
        Asn asn;
        asn = asnRepository.findByRelatedBill2(relatedBill2);
        if (asn==null){
            asn = new Asn();
            asn.setStatus(BizStatus.OPEN);
        }
        asn.setBillType(billType);
        // 默认单号
        asn.setRelatedBill1(relatedBill2);
        asn.setDept(UserUtils.getDept());
        asn.setRelatedBill2(relatedBill2);
        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(Asn asn) {
        List<String> datas=new ArrayList<>();
        if (asn.getStatus().equals(BizStatus.OPEN)) {
            //占用库位
            List<AsnDetail> asnDetailList=asnDetailRepository.findByAsnId(asn.getId(), BizStatus.OPEN );
            if (asnDetailList.size()>0){
                for (int i = 0; i < asnDetailList.size(); i++) {
                    AsnDetail asnDetail=asnDetailList.get(i);
                    Item item = asnDetail.getItem();
                    Double zzsQty=item.getExtendD1();// 装载数
                    Double orderQty=asnDetail.getOrderQty()-asnDetail.getReceivedQty();// 订单数
                    double result = orderQty / zzsQty;
                    int floorNum = (int) Math.floor(result);// 整托数
                    // 成品入库 分配库位
                    List<Point> points=new ArrayList<>();
                    String billType=asnDetail.getAsn().getBillType().getCode();
                    String areaCode="";
                    if (billType.equals(BizStatus.SM_RK)){
                        areaCode=BizStatus.BCP;
                    } else if (billType.equals(BizStatus.RM_RK)) {
                        areaCode=BizStatus.LX;
                    }else {
                        areaCode=BizStatus.CP;
                    }
                    List<Point> pointList=pointRepository.findByAreaCodeCp(areaCode,BaseStatus.FREE);
                    for (int j = 0; j < pointList.size(); j++) {
                        if (points.size()>=floorNum){
                            // 整托数 分配完成
                            break;
                        }
                        Point point =pointList.get(j);
                        if (point.getHeat()==null||point.getHeat()==1){
                            //浅位 直接分配
                            points.add(point);
                            continue;
                        }else {
                            // 深位，查询浅位是否空闲
                            List<Point> pointListQ=pointRepository.findByBeatCode(point.getBeatCode(),point.getHeat());
                            if (pointListQ.size()>0){
                                // 浅位有库存
                                continue;
                            }
                            points.add(point);
                        }
                    }
                    //添加任务
                    StringBuffer sb=new StringBuffer();
                    sb.append("明细行:"+asnDetail.getLineNo()+",分配库位【");
                    for (int j = 0; j < points.size(); j++) {
                        Point point=points.get(j);
                        sb.append(point.getCode()+",");
                        point.setStatus(BaseStatus.USED);
                        pointRepository.save(point);
                    }
                    sb.append("】剩余整托数"+(floorNum-points.size())+",未占用库位的余托数量"+orderQty % zzsQty+";");
                    datas.add(sb.toString());
                    asnDetail.setStatus(BizStatus.ACTIVE);
                    asnDetailRepository.save(asnDetail);
                }
            }
            //修改状态
            asn.setStatus(BizStatus.ACTIVE);
            asnRepository.save(asn);
        }else {
            //状态错误
            return ApiResult.success(500,"状态错误!",asn.getId());
        }
        return ApiResult.success(200,datas.toString(),asn.getId());
    }
    @Override
    public ApiResult cancelAsn(String id) {
        List<String> datas=new ArrayList<>();
        Asn asn=asnRepository.getById(Long.valueOf(id));
        if (asn.getStatus().equals(BizStatus.ACTIVE)) {
            //占用库位
            List<AsnDetail> asnDetailList=asnDetailRepository.findByAsnId(asn.getId(), BizStatus.ACTIVE);
            if (asnDetailList.size()>0){
                for (int i = 0; i < asnDetailList.size(); i++) {
                    AsnDetail asnDetail=asnDetailList.get(i);
                    Item item = asnDetail.getItem();
                    Double zzsQty=item.getExtendD1();// 装载数
                    Double orderQty=asnDetail.getOrderQty()-asnDetail.getReceivedQty();// 订单数
                    double result = orderQty / zzsQty;
                    int floorNum = (int) Math.floor(result);// 整托数
                    // 成品入库 分配库位
                    List<Point> points=new ArrayList<>();
                    List<Point> pointList=pointRepository.findByAreaCodeCp(item.getGoodType(),BaseStatus.USED);
                    for (int j = 0; j < pointList.size(); j++) {
                        if (points.size()>=floorNum){
                            // 整托数 分配完成
                            break;
                        }
                        Point point =pointList.get(j);
                        if (point.getHeat()==null||point.getHeat()==1){
                            //浅位 直接取消
                            points.add(point);
                            continue;
                        }else {
                            // 深位，查询浅位是否空闲
                            List<Point> pointListQ=pointRepository.findByBeatCode(point.getBeatCode(),point.getHeat());
                            if (pointListQ.size()>0){
                                // 浅位有库存
                                continue;
                            }
                            points.add(point);
                        }
                    }
                    //添加任务
                    StringBuffer sb=new StringBuffer();
                    sb.append("单号:"+asnDetail.getAsn().getRelatedBill1()+"明细行:"+asnDetail.getLineNo()+",取消占用库位【");
                    for (int j = 0; j < points.size(); j++) {
                        Point point=points.get(j);
                        sb.append(point.getCode()+",");
                        point.setStatus(BaseStatus.FREE);
                        pointRepository.save(point);
                    }
                    sb.append("】");
                    datas.add(sb.toString());
                    asnDetail.setStatus(BizStatus.OPEN);
                    asnDetailRepository.save(asnDetail);
                }
            }
            //修改状态
            asn.setStatus(BizStatus.OPEN);
            asnRepository.save(asn);
        }else {
            //状态错误
            return ApiResult.success(500,"状态错误!",id);
        }
        return ApiResult.success(200,datas.toString(),id);
    }
}