package com.dgtly.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.dgtly.system.domain.*;
import com.dgtly.system.mapper.CustomersExtMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dgtly.system.mapper.MetaHanaDeliverSignMapper;
import com.dgtly.system.service.IMetaHanaDeliverSignService;
import com.dgtly.common.core.text.Convert;

/**
 * 电子单签收状态数量Service业务层处理
 *
 * @author dgtly
 * @date 2025-01-03
 */
@Slf4j
@Service
public class MetaHanaDeliverSignServiceImpl implements IMetaHanaDeliverSignService
{

    @Autowired
    private MetaHanaDeliverSignMapper metaHanaDeliverSignMapper;

    @Autowired
    CustomersExtMapper customersExtMapper;

    /**
     * 查询电子单签收状态数量
     *
     * @param deliverNumber 电子单签收状态数量ID
     * @return 电子单签收状态数量
     */
    @Override
    public MetaHanaDeliverSign selectMetaHanaDeliverSignById(String deliverNumber)
    {
        return metaHanaDeliverSignMapper.selectMetaHanaDeliverSignById(deliverNumber);
    }

    /**
     * 查询电子单签收状态数量列表
     *
     * @param metaHanaDeliverSign 电子单签收状态数量
     * @return 电子单签收状态数量
     */
    @Override
    public List<MetaHanaDeliverSign> selectMetaHanaDeliverSignList(MetaHanaDeliverSign metaHanaDeliverSign)
    {
        return metaHanaDeliverSignMapper.selectMetaHanaDeliverSignList(metaHanaDeliverSign);
    }



    /**
     * 修改电子单签收状态数量
     *
     * @param metaHanaDeliverSign 电子单签收状态数量
     * @return 结果
     */
    @Override
    public int updateMetaHanaDeliverSign(MetaHanaDeliverSign metaHanaDeliverSign)
    {
        return metaHanaDeliverSignMapper.updateMetaHanaDeliverSign(metaHanaDeliverSign);
    }

    /**
     * 删除电子单签收状态数量对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteMetaHanaDeliverSignByIds(String ids)
    {
        return metaHanaDeliverSignMapper.deleteMetaHanaDeliverSignByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除电子单签收状态数量信息
     *
     * @param deliverNumber 电子单签收状态数量ID
     * @return 结果
     */
    @Override
    public int deleteMetaHanaDeliverSignById(String deliverNumber)
    {
        return metaHanaDeliverSignMapper.deleteMetaHanaDeliverSignById(deliverNumber);
    }

    /**
     * @description: 预处理电子单签收数据，交货单，订单，运单签收状态和最近一次签收时间
     * @param: []
     * @return: boolean
     * @author: njs
     * @date: 2025/6/5 9:53
     */
    @Override
    public void pretreatmentHanaDeliverSign() {
        List<MetaHanaDeliverSign> orderList = metaHanaDeliverSignMapper.selectDeliverSignListByOrderNumberAndOrderItem();

        //先处理订单，（处理电子单签收里的订单）
        if(orderList !=null && orderList.size()>0){
            List<OrderSignVO> orderSignVOList = new ArrayList<>();
            // 先建立订单号与对象的映射关系
            Map<String, List<MetaHanaDeliverSign>> orderSignList = orderList.stream()
                    .collect(Collectors.groupingBy(MetaHanaDeliverSign::getOrderNumber));

            // 遍历处理每个订单
            orderSignList.forEach((orderNum, list) -> {
                            if(!orderSignVOList.contains(orderNum)){
                                OrderSignVO vo = new OrderSignVO();
                                vo.setOrderNumber(orderNum);
                                List<String> signList = new ArrayList<>();
                                if(list !=null && list.size()>0){
                                    list.forEach(sign->{
                                        BigDecimal differenceQty = new BigDecimal(0);
                                        //差值
                                        if (org.apache.commons.lang.StringUtils.isNotBlank(sign.getDifferenceQty())) {
                                            differenceQty = new BigDecimal(sign.getDifferenceQty());
                                            differenceQty = differenceQty.setScale(0, BigDecimal.ROUND_HALF_UP);
                                        }
                                        //判断是否待签收和异常签收标记
                                        if(differenceQty.compareTo(new BigDecimal("0")) == 0 ) {
                                            if(sign.getZdateDate() !=null && !("").equals(sign.getZdateDate()) && !sign.getZdateDate().equals("00000000")){
                                                //正常签收
                                                signList.add("1");
                                            }else{
                                                //未签收
                                                signList.add("3");
                                            }
                                        }else{
                                            if(("全部签收").equals(sign.getAbnormalStatus())){
                                                //正常签收
                                                signList.add("1");
                                            }else{
                                                //异常签收 待签收
                                                signList.add("0");
                                            }
                                        }
                                    });

                                    if(signList !=null && signList.size()>0){
                                        if(signList.contains("0")){
                                            //异常签收 待签收
                                            vo.setSignType(0);
                                            String signTime = findMaxValidDateTime(list);
                                            vo.setZdateDate(signTime);
                                        }else if(signList.contains("1") && !signList.contains("0")){
                                            //正常签收
                                            vo.setSignType(1);
                                            String signTime = findMaxValidDateTime(list);
                                            vo.setZdateDate(signTime);
                                        }else{
                                            //未签收
                                            vo.setSignType(3);
                                        }
                                    }

                                    orderSignVOList.add(vo);

                                }
                            }
            });
            if(orderSignVOList !=null && orderSignVOList.size()>0){
                //清除表数据再批量新增
                metaHanaDeliverSignMapper.truncateOrderSign();
                metaHanaDeliverSignMapper.batchOrderSign(orderSignVOList);

            }
        }

        //再处理运单，（处理tms运单表中的运单）
        List<DeliverSignVO> tmsShipMentList =  metaHanaDeliverSignMapper.selectDeliverSignByTmsShipmentNumber();
        if(tmsShipMentList !=null && tmsShipMentList.size()>0){
            List<TmsShipmentSignVO> tmsList = new ArrayList<>();
            // 先建立运单号与对象的映射关系
            Map<String, List<DeliverSignVO>> shipmentMap = tmsShipMentList.stream()
                    .collect(Collectors.groupingBy(DeliverSignVO::getTmsShipmentNum));

            // 遍历处理每个运单号
                        shipmentMap.forEach((shipmentNum, list) -> {
                            List<String> tmsSignList = new ArrayList<>();
                                //已处理过就跳过
                                if (!tmsList.contains(shipmentNum)) {
                                    TmsShipmentSignVO signVO = new TmsShipmentSignVO();
                                    signVO.setTmsShipmentNumber(shipmentNum);
                                    if (list != null && list.size() > 0) {
                                        list.forEach(sign -> {
                                            //计算该运单下电子签收单状态和最近签收时间
                                            BigDecimal differenceQty = new BigDecimal(0);
                                            if (org.apache.commons.lang.StringUtils.isNotBlank(sign.getDifferenceQty())) {
                                                differenceQty = new BigDecimal(sign.getDifferenceQty());
                                                differenceQty = differenceQty.setScale(0, BigDecimal.ROUND_HALF_UP);
                                            }
                                            //判断是否待签收和异常签收标记
                                            if (differenceQty.compareTo(new BigDecimal("0")) == 0) {
                                                //正常签收
                                                //没有签收时间的则为未签收
                                                if (sign.getZDate() != null && !("").equals(sign.getZDate()) && !sign.getZDate().equals("00000000")) {
                                                    tmsSignList.add("1");
                                                } else {
                                                    tmsSignList.add("3");
                                                }
                                            } else {
                                                //abnormalStatus 1未签收；2未开始补货；3部分签收；4全部签收
                                                if (("4").equals(sign.getAbnormalStatus())) {
                                                    //正常签收
                                                    tmsSignList.add("1");
                                                } else {
                                                    //异常签收 待签收
                                                    tmsSignList.add("0");
                                                }

                                            }

                                        });

                                        if (tmsSignList.contains("0")) {
                                            signVO.setSignType(0);
                                            String signTime = findMaxTMSDateTime(list);
                                            signVO.setZdateDate(signTime);
                                        } else if (!tmsSignList.contains("0") && tmsSignList.contains("1")) {
                                            signVO.setSignType(1);
                                            String signTime = findMaxTMSDateTime(list);
                                            signVO.setZdateDate(signTime);
                                        } else {
                                            signVO.setSignType(3);
                                        }

                                    }else{
                                        signVO.setSignType(3);
                                    }

                                    tmsList.add(signVO);
                                }
                        });
                        if(tmsList !=null && tmsList.size()>0){
                            //清楚表数据再批量新增
                            metaHanaDeliverSignMapper.truncateTmsShipmentSign();
                            metaHanaDeliverSignMapper.batchTmsShipmentSign(tmsList);

                        }


        }

    }

    @Override
    public void certificationSync() {
       List<String> list = metaHanaDeliverSignMapper.selectCertificationSync();
       for (String deliverNumber:list){
           //判断ext表是否存在数据
           CustomersExt customersExt = customersExtMapper.selectCustomersExtById(deliverNumber);
           //查询主经销商的注册信息
           CustomersExt cust =  customersExtMapper.selectCustomersExt(deliverNumber);
           if (customersExt !=null){
               //如果存在数据直接认证通过
               CustomersExt customer = new CustomersExt();
               customer.setIsAuthentication("1");
               customer.setOrgId(cust.getOrgId());
               customer.setCreator(cust.getCreator());
               customer.setChainsCode(deliverNumber);
               customer.setOrgAttestationTime(new Date());
               customer.setCreateTime(new Date());
               customersExtMapper.updateCustomersExt(customer);
           }else {
               cust.setChainsCode(deliverNumber);
               cust.setOrgAttestationTime(new Date());
               cust.setCreateTime(new Date());
               customersExtMapper.insertCustomersExt(cust);
           }
       }
    }


    public  String findMaxValidDateTime(List<MetaHanaDeliverSign> list) {
        return list.stream()
                .filter(obj -> !obj.getSignTime().startsWith("0000"))
                .map(MetaHanaDeliverSign::getSignTime)  // 提取需要比较的字段
                .max(Comparator.naturalOrder())
                .orElse(null);
    }

    public  String findMaxTMSDateTime(List<DeliverSignVO> list) {
        return list.stream()
                .filter(obj -> !obj.getZdateDate().startsWith("0000"))
                .map(DeliverSignVO::getZdateDate)  // 提取需要比较的字段
                .max(Comparator.naturalOrder())
                .orElse(null);
    }




}
