package cn.iocoder.yudao.module.order.service.order.impl;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.code.CodeUtils;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.file.core.client.FileClient;
import cn.iocoder.yudao.module.depository.dal.dataobject.warehouse.WarehouseLineDO;
import cn.iocoder.yudao.module.depository.service.warehouse.WarehouseService;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.infra.controller.admin.file.vo.file.FilePageReqVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO;
import cn.iocoder.yudao.module.infra.service.file.FileConfigService;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.order.service.order.OrderPrintTagService;
import cn.iocoder.yudao.module.order.service.order.OrderService;
import cn.iocoder.yudao.module.order.service.orderLabel.OrderLabelService;
import cn.iocoder.yudao.module.order.vo.orderLabel.OrderLabelBackVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderPrintTagServiceImpl implements OrderPrintTagService {

    public static Map<String, String> hashMap = new HashMap();

    static {
        hashMap.put("1", "LCL");//海运拼箱
        hashMap.put("2", "FCL");//海箱整运
        hashMap.put("3", "AIR");//空运专线
        hashMap.put("4", "SA");//海空联运
    }

    private static final String LOGISTICS = "E&CLogistics:   www.groupage.cn";

    @Resource
    private OrderService orderService;

    @Resource
    private FileConfigService fileConfigService;

    @Resource
    private OrderLabelService orderLabelService;

    @Resource
    private FileApi fileApi;

    @Autowired
    private WarehouseService warehouseService;

    @Resource
    private FileService fileService;

    @Value("${yudao.web.admin-ui.url}")
    private String basePath;

    @Override
    public List orderTagPrint(Long orderId) throws Exception {

        OrderDO orderDO = orderService.getById(orderId);

        boolean isSplitOrderChildren = orderDO.getParentOrderId() != null && orderDO.getParentOrderId() != 0L;

        String marks = orderDO.getMarks();//唛头
        String orderNo = orderDO.getOrderNo();//订单ID
        Date inTime = orderDO.getCreateTime();
        List lineIdList = new ArrayList();
        lineIdList.add(orderDO.getLineId());//路线ID
        List<WarehouseLineDO> warehouseLineDOS = warehouseService.selectBylineIdList(lineIdList);
        String startTitleEn = "";
        String destTitleEn = "";
        if (warehouseLineDOS != null && warehouseLineDOS.size() > 0) {
            startTitleEn = warehouseLineDOS.get(0).getStartQianzhui();//始发仓
            destTitleEn = warehouseLineDOS.get(0).getDestQianzhui();//目的仓
        }
        String partPath = "/tag/"+DateUtils.formatDate(new Date()) + "/";
        FileClient masterFileClient = fileConfigService.getMasterFileClient();
        String domain = masterFileClient.getDomain();
//        ExecutorService executorService = Executors.newSingleThreadExecutor();

        //判断起始，谁大用谁的
        Integer start = 1;
        Integer end = JSON.parseObject(orderDO.getCost()).getInteger("totalNum");
        if (orderDO.getSumNum() != null && orderDO.getSumNum() != 0 && orderDO.getSumNum() > end) {
            end = orderDO.getSumNum();//入仓箱数
        }

        List<OrderLabelBackVO> orderLabelList = orderLabelService.getLabelListByOrder(orderId);
        //排序
        orderLabelList.sort(Comparator.comparing(OrderLabelBackVO::getStart));

        //获取标签
        String labels = start + "~" + end;

        List<Map<String,String>> resultList = new ArrayList();
        if (orderLabelList.size() > 1 || isSplitOrderChildren) {
            //标签
            List<String> labelList = orderLabelList.stream().map(orderLabelBackVO -> orderLabelBackVO.getStart() + "~" + orderLabelBackVO.getEnd()).collect(Collectors.toList());
            labels = StrUtil.join(", ", labelList);

            //注入配置
            for (OrderLabelBackVO labelBackVO : orderLabelList) {
                Integer start1 = labelBackVO.getStart();
                Integer end1 = labelBackVO.getEnd();

                addToList(marks, orderNo, startTitleEn, destTitleEn, partPath, domain, resultList, orderDO, start1, end1, labels);
            }
        } else {
            addToList(marks, orderNo, startTitleEn, destTitleEn, partPath, domain, resultList, orderDO, start, end, labels);
        }

        //上传文件
//        executorService.execute(new Runnable() {
//            @Override
//            public void run() {
//                resultList.stream().forEach(item -> {
//                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//                    try {
//                        QRCode.generateQRCodeImage(item.get("tag"), 350, 350, outputStream);
//                        fileApi.createFile(item.get("uploadPath"),outputStream.toByteArray());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    } finally {
//                        try {
//                            outputStream.flush();
//                            outputStream.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
//            }
//        });
//        executorService.shutdown();
        return resultList;
    }


    private void addToList(String marks, String orderNo, String startTitleEn, String destTitleEn, String partPath, String domain, List<Map<String, String>> list, OrderDO info, Integer start, Integer end, String labels) {
        for (int i = start; i <= end; i++) {
            Map<String,String> map = new HashMap();
            String orderTag = CodeUtils.createOrderTagNumber(orderNo, i);
            map.put("orderNo", orderNo);
            map.put("marks", marks);
            map.put("startTitleEn", startTitleEn);
            map.put("destTitleEn", destTitleEn);
            map.put("inTime", DateUtils.formatDate(new Date()));
            map.put("num", String.valueOf(i));
            map.put("tag", orderTag);
            map.put("foot", LOGISTICS);
            map.put("transportType", hashMap.get(String.valueOf(info.getTransportId())));
            String url = StrUtil.format("{}/{}", domain, partPath + orderTag);
//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            QRCode.generateQRCodeImage(orderTag, 350, 350, outputStream);
//            String url = fileApi.createFile(partPath+"/"+ UUID.fastUUID().toString(),outputStream.toByteArray());
            map.put("url", url);
            map.put("uploadPath", partPath + orderTag);
            map.put("labels", labels);
//            outputStream.flush();
//            outputStream.close();
            list.add(map);
        }
    }

    @Override
    public Boolean checkPrintFinishStatus(Long orderId) {
        boolean flag = false;
        try {
            OrderDO orderDO = orderService.getById(orderId);

            boolean isSplitOrderChildren = orderDO.getParentOrderId() != null && orderDO.getParentOrderId() != 0L;

            //判断起始，谁大用谁的
            Integer start = 1;
            Integer end = JSON.parseObject(orderDO.getCost()).getInteger("totalNum");
            if (orderDO.getSumNum() != null && orderDO.getSumNum() == 0 && orderDO.getSumNum() > end) {
                end = orderDO.getSumNum();//入仓箱数
            }

            List<OrderLabelBackVO> orderLabelList = orderLabelService.getLabelListByOrder(orderId);
            //排序
            orderLabelList.sort(Comparator.comparing(OrderLabelBackVO::getStart));

            if (orderLabelList.size() > 1 || isSplitOrderChildren) {
                end = orderLabelList.get(orderLabelList.size() - 1).getEnd();
            }

            Date date = new Date();
            String orderTag = CodeUtils.createOrderTagNumber(orderDO.getOrderNo(), end);
            String path = "/tag/"+DateUtils.formatDate(date) + "/" + orderTag;
            String path1 = "/tag/"+DateUtils.formatDate(DateUtils.addDate(date,Calendar.DATE,-1)) + "/" + orderTag;
            FilePageReqVO pageVO = new FilePageReqVO();
            pageVO.setPath(path);
            pageVO.setPageNo(1);
            pageVO.setPageSize(10);
            PageResult<FileDO> pageResult = fileService.getFilePage(pageVO);
            pageVO.setPath(path1);
            PageResult<FileDO> pageResult1 = fileService.getFilePage(pageVO);
            if (pageResult.getTotal() > 1L || pageResult1.getTotal() > 1L) {
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Boolean.valueOf(flag);
    }
}
