/*
 *  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.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.StockService;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.service.*;
import com.youchain.exception.BadRequestException;
import com.youchain.service.LogService;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.PickRepository;
import com.youchain.businessdata.service.dto.PickDto;
import com.youchain.businessdata.service.dto.PickQueryCriteria;
import com.youchain.businessdata.service.mapstruct.PickMapper;
import lombok.extern.slf4j.Slf4j;
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.io.IOException;
import javax.servlet.http.HttpServletResponse;


/**
 * @author huojin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-06-11
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class PickServiceImpl implements PickService {

    private final PickRepository pickRepository;
    private final PickMapper pickMapper;
    private final PickDetailService pickDetailService;
    private final PointService pointService;
    private final AgvTaskService agvTaskService;


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

    @Override
    public List<PickDto> queryAll(PickQueryCriteria criteria) {
        return pickMapper.toDto(pickRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public Pick findById(Long id) {
        return pickRepository.findById(id).orElseGet(Pick::new);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickDto create(Pick resources) {
        return pickMapper.toDto(pickRepository.save(resources));
    }

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

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

    @Override
    public void download(List<PickDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PickDto pick : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建人", pick.getCreateBy());
            map.put("修改人", pick.getUpdateBy());
            map.put("创建时间", pick.getCreateTime());
            map.put("修改时间", pick.getUpdateTime());
            map.put("出库单头", pick.getCode());
            map.put("序号", pick.getLineNo());
            map.put("状态", pick.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    @Override
    public Pick findByPickCode(String lineSlotCode) {
        return pickRepository.findByPickCode(lineSlotCode);
    }

    @Override
    public List<Pick> findByPickStatus(List<String> statuses, boolean isCall,String orderType) {
        return pickRepository.findByPickStatus(statuses, isCall, orderType);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshPickStatus(Pick pick) {
        // 查询出库单的所有明细
        List<PickDetail> allocatePickDetailList = pickDetailService.findByAllPickDetail(pick.getId());

        double orderQty = 0;
        double allocatedQty = 0;
        double pickedQty = 0;

        // 一次遍历计算所需数量总和
        for (PickDetail detail : allocatePickDetailList) {
            orderQty += detail.getOrderQty();
            allocatedQty += detail.getAllocatedQty();
            pickedQty += detail.getPickedQty();
        }


        // 当前状态
        String status = pick.getStatus();

        // 更新状态
        if (orderQty - allocatedQty > 0 && allocatedQty != 0) {
            status = BizStatus.ASSIGN;
        } else if (orderQty == allocatedQty && pickedQty == 0) {
            status = BizStatus.ALLOCATE;
        } else if (orderQty - pickedQty > 0 && pickedQty != 0) {
            status = BizStatus.PICKUP;
        } else if (orderQty == pickedQty) {
            status = BizStatus.PICK_ALL;
        }

        // 更新pick状态
        pick.setStatus(status);
        pickRepository.save(pick);
    }

}
