/*
 *  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.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.repository.PickDetailRepository;
import com.youchain.businessdata.service.*;
import com.youchain.exception.BadRequestException;
import com.youchain.modules.system.domain.Dict;
import com.youchain.modules.system.repository.DictRepository;
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 java.util.stream.Collectors;
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 DictRepository dictRepository;
    private final PickRepository pickRepository;
    private final PickDetailRepository pickDetailRepository;
    private final PickMapper pickMapper;
    private final PickDetailService pickDetailService;
    private final LogService logService;


    @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) {
        return pickRepository.findByPickStatus(statuses, isCall);
    }


    @Override
    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 && pickedQty == 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);
    }

    @Override
    public JSONObject returnPickJson(Task task) {
        Pick pick=task.getPickDetail().getPick();
        int complete = getCompleteStatus(pick);
        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
        //需求工位
        jsonObject.put("OpName", task.getPickDetail().getPick().getStation());
        //工单号
        jsonObject.put("OrderCode", task.getPickDetail().getPick().getGdCode());
        //物料编码
        String itemCode = task.getPickDetail().getPropC3() == null ? task.getPickDetail().getItem().getCode() : task.getPickDetail().getPropC3();
        jsonObject.put("MaterialCode", itemCode);
        //数量
        jsonObject.put("number", task.getMoveQty()== null ? 0 : task.getMoveQty().intValue());
        //taskId
        jsonObject.put("taskId", task.getPickDetail().getPick().getTaskCode());
        //complete 完成标识；0未完成；1完成
        jsonObject.put("complete", complete);
        return jsonObject;
    }

    private int getCompleteStatus(Pick pick) {
        return BizStatus.PICK_ALL.equals(pick.getStatus()) ? 1 : 0;
    }

    @Override
    public void returnPickByTask(Task task) {
        sendPick(UrlApi.stock(), task);
    }

    @Override
    public void sendPick(String url, Task task) {
        String message = null;
        String resultJson = null;
        Dict dict = dictRepository.findDictByName("OPEN");
        PickDetail pickDetail=task.getPickDetail();
        if (dict == null) {
            pickDetail.setSourceId(1L);
            pickDetail.setSourceName("成功");
            pickDetailRepository.save(pickDetail);
            //保存日志
            logService.saveLogInfo(returnPickJson(task), pickDetail.getPick().getCode(), UrlApi.stock(), resultJson, "工单回传", 200, "info");
            return;
        }

        resultJson = HttpPostUtil.sendPostReq(url, returnPickJson(task).toString());
        if (StringUtils.isEmpty(resultJson)) {
            message = "MES返回信息:接口调用失败";
            handleFailure(pickDetail, returnPickJson(task), resultJson, message);
            return;
        }
        JSONObject resultObject = JSON.parseObject(resultJson);
        if (resultObject == null) {
            message = "MES返回信息:接口数据返回为空";
            handleFailure(pickDetail, returnPickJson(task), resultJson, message);
            return;
        }
        String code = resultObject.getString("code");
        message = resultObject.getString("message");
        if (!"200".equals(code)) {
            handleFailure(pickDetail, returnPickJson(task), resultJson, message);
            return;
        }
        pickDetail.setSourceId(1L);
        pickDetail.setSourceName(resultJson);
        pickDetailRepository.save(pickDetail);
        //保存日志
        logService.saveLogInfo(returnPickJson(task), pickDetail.getPick().getCode(), UrlApi.stock(), resultJson, "工单回传", 200, "info");

    }


    private void handleFailure(PickDetail pickDetail, JSONObject requestJson, String resultJson, String message) {
        pickDetail.setSourceId(0L);
        pickDetail.setSourceName(message);
        pickDetailRepository.save(pickDetail);
        logService.saveLogInfo(requestJson,
                pickDetail.getPick().getGdCode() + "-" + pickDetail.getItem().getCode(),
                UrlApi.stock(),
                resultJson,
                "工单回传",
                200,
                "info");
    }


}
