package com.jwipc.supplier.logic.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jwipc.api.OaCallBackLogic;
import com.jwipc.api.constant.OaStatus;
import com.jwipc.api.constant.RestCode;
import com.jwipc.api.dto.ApiResult;
import com.jwipc.api.dto.SapResposeBody;
import com.jwipc.constant.OaProcessType;
import com.jwipc.exception.DaoException;
import com.jwipc.supplier.constant.AuthenticationState;
import com.jwipc.supplier.constant.PurchaseCategoryApprStatus;
import com.jwipc.supplier.constant.PurchaseCategoryType;
import com.jwipc.supplier.constant.SupplierSapClient;
import com.jwipc.supplier.convert.SupplierBankConvert;
import com.jwipc.supplier.dto.SupplierStateToSapDTO;
import com.jwipc.supplier.entity.Supplier;
import com.jwipc.supplier.entity.SupplierBank;
import com.jwipc.supplier.entity.SupplierBankInfo;
import com.jwipc.supplier.entity.SupplierPurchaseCategory;
import com.jwipc.supplier.logic.SupplierLogic;
import com.jwipc.supplier.service.*;
import com.jwipc.sys.client.PurchaseCategoryClient;
import com.jwipc.sys.client.dto.PurchaseCategoryClientDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p> </p>
 *
 * @author ZhangJie
 * @version 1.0
 * @since JDK 1.8
 */
@Service("SupplierAccessCallBack")
@RequiredArgsConstructor
public class SupplierAccessCallBack implements OaCallBackLogic {
    private final ISupplierService supplierService;
    private final ISupplierPurchaseCategoryService supplierPurchaseCategoryService;
    private final PurchaseCategoryClient purchaseCategoryClient;
    private final SupplierLogic supplierLogic;

    private final SupplierSapClient sapClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult processor(String workflowId, OaStatus status, String remark, String processCode, String data1,
                               String data2)
    {
        final List<SupplierPurchaseCategory> list = supplierPurchaseCategoryService.list(
                new LambdaQueryWrapper<SupplierPurchaseCategory>()
                        .eq(SupplierPurchaseCategory::getOaId, workflowId));
        if (CollUtil.isEmpty(list)) {
            return ApiResult.builder().code(RestCode.SAP_ERROR.getCode()).message("未找到匹配的流程数据!").build();
        }
        if (status.equals(OaStatus.PASS)) {
            //如果是特批供应商直接推送oa
            final Supplier dbSupplier = supplierService.getById(list.get(0).getSupplierId());
            //需要修改供应商编码，修改用户编码，发送邮件
            for (SupplierPurchaseCategory supplierPurchaseCategory : list) {
                //如果是非生产信息
                final List<PurchaseCategoryClientDTO> list1 = purchaseCategoryClient.getAll();
                final Map<String, String> code = list1.stream().collect(
                        Collectors.toMap(PurchaseCategoryClientDTO::getFirstLevelPurchaseCode,
                                a -> a.getSecondLevelPurchaseCode()));
                final String purchaseCategoryCode = supplierPurchaseCategory.getPurchaseCategoryCode();
                final String secondLevelPurchaseCode = code.get(purchaseCategoryCode);
                if (secondLevelPurchaseCode.equals(PurchaseCategoryType.NO_PRODUCTION_TYPE.getCode()) ||
                        dbSupplier.getAssessType().equals("3")) {
                    supplierPurchaseCategory.setState(AuthenticationState.QUALIFIED.getState());
                    supplierPurchaseCategory.setSmallTime(LocalDateTime.now());
                    supplierPurchaseCategory.setQualifiedTime(LocalDateTime.now());
                } else {
                    //如果是客供品类供应商，oa审批通过，要把SupplierAttribution=30 置为空 邓京术 2025-07-08
                    //Z011-代收款供应商 ,Z012-手板供应商,潜在转小批量，抛OA审批，审批通过后，更新为合格供应商
                    if(!Objects.isNull(dbSupplier.getSupplierAttribution())
                            && (dbSupplier.getSupplierAttribution().equals(30))) {
                        LambdaUpdateWrapper<Supplier> supplierLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        supplierLambdaUpdateWrapper.eq(Supplier::getId, dbSupplier.getId()).set(Supplier::getSupplierAttribution, null);
                        supplierService.update(supplierLambdaUpdateWrapper);
                    }

                    supplierPurchaseCategory.setState(AuthenticationState.SMALL_BATCH.getState());
                    if(!Objects.isNull(dbSupplier.getSupplierAttribution())
                            && (dbSupplier.getSupplierAttribution().equals(50)||dbSupplier.getSupplierAttribution().equals(60))) {
                        supplierPurchaseCategory.setState(AuthenticationState.QUALIFIED.getState());
                        //手板类或代收款供应商转正常材料供应商时  回调清除标识
                        if ( list.size()>1  ) {
                            final Set<String> collected = list.stream().map(a -> a.getPurchaseCategoryCode()).collect(Collectors.toSet());
                            if ( (collected.contains("Z011") || collected.contains("Z012"))   ) {
                                LambdaUpdateWrapper<Supplier> supplierLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                                supplierLambdaUpdateWrapper.eq(Supplier::getId, dbSupplier.getId()).set(Supplier::getSupplierAttribution, null);
                                supplierService.update(supplierLambdaUpdateWrapper);
                            }
                        }

                    }
                    supplierPurchaseCategory.setSmallTime(LocalDateTime.now());
                }
                supplierPurchaseCategory.setApprState(PurchaseCategoryApprStatus.AGREE.getStatus());

            }
            supplierPurchaseCategoryService.updateBatchById(list);
            final Supplier supplier = supplierService.getById(list.get(0).getSupplierId());
            //更新供应商编码
            //如果已经存在erpCode就不需要重复更新
            supplierLogic.updateFormalCode(supplier.getId(), data1);

            //创建后传输小批量状态到SAP
            List<SupplierStateToSapDTO.Item>  items=new ArrayList<>();
            SupplierStateToSapDTO.IT_ITEM it_item= new SupplierStateToSapDTO.IT_ITEM();
            SupplierStateToSapDTO.Item item = new SupplierStateToSapDTO.Item();
            item.setLIFNR(data1);
            if(!Objects.isNull(dbSupplier.getSupplierAttribution())
                    && (dbSupplier.getSupplierAttribution().equals(50)||dbSupplier.getSupplierAttribution().equals(60))) {
                item.setZZJDZT("H");
            }else{
                item.setZZJDZT("X");
            }
            items.add(item);
            it_item.setItem(items);
            SupplierStateToSapDTO supplierStateToSapDTO = new SupplierStateToSapDTO();
            supplierStateToSapDTO.setIT_ITEM(it_item);
            final SapResposeBody sapResposeBody = sapClient.updateSupplierState(supplierStateToSapDTO);
            if (!sapResposeBody.getES_RET().getCODE().equals(RestCode.SAP_SUCCESS.getCode())) {
                throw new DaoException(StrUtil.format("推送SAP错误:{}", sapResposeBody.getES_RET().getMSG()));
            }

        } else if (status.equals(OaStatus.REFUSE)) {
            //驳回，修改状态
            for (SupplierPurchaseCategory supplierPurchaseCategory : list) {
                supplierPurchaseCategory.setApprState(PurchaseCategoryApprStatus.REJECT.getStatus());
            }
            supplierPurchaseCategoryService.updateBatchById(list);
        }
        return ApiResult.builder().code(RestCode.SAP_SUCCESS.getCode()).build();
    }

    @Override
    public OaProcessType getProcessType() {
        return OaProcessType.SUPPLIER_ACCESS;
    }
}
