package com.prolog.cs.biz.outbound.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.prolog.cs.biz.outbound.dao.InvoicePdfMapper;
import com.prolog.cs.biz.outbound.dao.OmsDoBillHMapper;
import com.prolog.cs.biz.outbound.model.OmsDoBillHDO;
import com.prolog.cs.biz.outbound.model.dto.InvoicePdfDTO;
import com.prolog.cs.biz.outbound.model.entity.InvoicePdfDO;
import com.prolog.cs.biz.outbound.model.vo.InvoicePdfVO;
import com.prolog.cs.biz.outbound.model.vo.ReceiveInvoiceVO;
import com.prolog.cs.biz.outbound.resource.InventoryResource;
import com.prolog.cs.biz.outbound.service.InvoicePdfService;
import com.prolog.framework.authority.core.dto.UserDTO;
import com.prolog.framework.authority.user.UserTemplate;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.ParameterException;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.framework.utils.MapUtils;
import com.prolog.framework.utils.UUIDUtils;
import com.prolog.upcloud.base.inventory.vo.AskIntegrationVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zzz
 * @desc 打印服务实现
 * @date 2021/4/30
 */
@Service
public class InvoicePdfServiceImpl implements InvoicePdfService {

    @Resource
    private InventoryResource inventoryResource;

    @Resource
    private InvoicePdfMapper invoicePdfMapper;

    @Autowired
    private OmsDoBillHMapper omsDoBillHMapper;

    @Autowired
    UserTemplate userTemplate;

    @Override
    @Transactional
    public boolean getInvoicePdfUrl(List<String> orderNos) {
        try {
            UserDTO userDTO = userTemplate.getUserDTO();
            if(CollectionUtil.isEmpty(orderNos)){
                throw new BizException("订单号集合不能为空");
            }
            String orderNoStr = StringUtils.join(orderNos, "|");

            InvoicePdfVO pdfVO =new InvoicePdfVO();
            pdfVO.setOrderNos(orderNoStr);
            AskIntegrationVo vo = new AskIntegrationVo();
            vo.setIntegrationCode("invoicePdfs");
            vo.setParam(pdfVO);
            RestMessage<?> msg = inventoryResource.askIntegration(vo);
            //返回成功
            if(msg.getCode().equals("1")){
                JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(msg.getData()));
                List<InvoicePdfDTO> pdfDTOS = jsonArray.toJavaList(InvoicePdfDTO.class);
                //保存数据到表中
                List<InvoicePdfDO> invoicePdfDOS =new ArrayList<>();
                for (InvoicePdfDTO pdfDTO : pdfDTOS) {
                    InvoicePdfDO invoicePdfDO =new InvoicePdfDO();
                    invoicePdfDO.setOrderNo(pdfDTO.getOrderNo());
                    invoicePdfDO.setPdfUrl(pdfDTO.getPdf());
                    invoicePdfDO.setEnterpriseId("891063172566487040");
                    invoicePdfDO.setConsignorId("748963439141064888");
                    invoicePdfDO.setWarehouseId("891420072483098624");
                    invoicePdfDO.setCreateBy(userDTO.getUsername());
                    invoicePdfDO.setCreateDate(new Date());
                    invoicePdfDOS.add(invoicePdfDO);
                }
                invoicePdfMapper.saveBatch(invoicePdfDOS);
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            System.out.println("catch:" + e);
            return false;
        }
    }

    @Override
    public void receiveInvoice(ReceiveInvoiceVO vo) {
        if(vo == null){
            throw new ParameterException("入参不能为空!");
        }
        if(com.prolog.framework.utils.StringUtils.isBlank(vo.getBillNo())){
            throw new ParameterException("订单编号不能为空!");
        }
        if(vo.getUrls() == null || vo.getUrls().size() <= 0){
            throw new ParameterException("发票地址不能为空!");
        }

        long count = omsDoBillHMapper.findCountByMap(MapUtils.put("billno", vo.getBillNo()).getMap(), OmsDoBillHDO.class);
        if(count <= 0){
            throw new ParameterException("订单编号未查询到对应的出库单!");
        }

        Criteria cr = Criteria.forClass(InvoicePdfDO.class);
        Restriction r1 = Restrictions.eq(InvoicePdfDO::getOrderNo, vo.getBillNo());
        Restriction r2 = Restrictions.in(InvoicePdfDO::getPdfUrl, vo.getUrls().toArray());
        cr.setRestriction(Restrictions.and(r1,r2));
        List<InvoicePdfDO> extInvoices = invoicePdfMapper.findByCriteria(cr);

        List<InvoicePdfDO> saves = new ArrayList<>();
        for (String url : vo.getUrls()) {

            long count1 = extInvoices.stream().filter(item -> item.getPdfUrl().equals(url)).count();
            if(count1 > 0){
                continue;
            }

            InvoicePdfDO pdfDO = new InvoicePdfDO();
            pdfDO.setId(UUIDUtils.generateWithoutSeperator());
            pdfDO.setOrderNo(vo.getBillNo());
            pdfDO.setPdfUrl(url);
            pdfDO.setEnterpriseId(vo.getEnterpriseId());
            pdfDO.setWarehouseId(vo.getWarehouseId());
            pdfDO.setConsignorId(vo.getConsignorId());
            pdfDO.setCreateBy("ERP");
            pdfDO.setCreateDate(new Date());

            saves.add(pdfDO);
        }
        if(saves.size() > 0){
            invoicePdfMapper.saveBatch(saves);
        }
    }
}
