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.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.ISupplierBankInfoService;
import com.jwipc.supplier.service.ISupplierBankService;
import com.jwipc.supplier.service.ISupplierPurchaseCategoryService;
import com.jwipc.supplier.service.ISupplierService;
import com.jwipc.sys.client.PurchaseCategoryClient;
import com.jwipc.sys.client.dto.PurchaseCategoryClientDTO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 导入供应商OA回调 （资源整合部）*
 *1.需要新建一个供应商主数据列表以状态进行区分
 *2.在新建的列表上加一个提交OA审批和导入供应商信息按钮
 *3.需要复制潜在供应商提交OA审批获取数据方式推送到OA
 *4.需要复制供应商准入OA回调更新正式SRM系统编号*
 *5.
 */
@Service("SupplierImportAccessCallBack")
@RequiredArgsConstructor
public class SupplierimportAccessCallBack implements OaCallBackLogic {
    private final ISupplierService supplierService;
    private final ISupplierPurchaseCategoryService supplierPurchaseCategoryService;
    private final PurchaseCategoryClient purchaseCategoryClient;
    private final SupplierLogic supplierLogic;

    @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();
        }
        final Supplier supplier = supplierService.getById(list.get(0).getSupplierId());
        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 {
                    //资源整合部
                    if(!Objects.isNull(dbSupplier.getSupplierAttribution()) && dbSupplier.getSupplierAttribution().equals(10)  ){
                        if(supplierPurchaseCategory.getState().equals(AuthenticationState.POTENTIAL.getState())){

                            if(StringUtils.isNotEmpty(dbSupplier.getSignUpRemark())){
                                //潜在转小批量
                                supplierPurchaseCategory.setState(AuthenticationState.SMALL_BATCH.getState());
                                LambdaUpdateWrapper<Supplier> supplierLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                                supplierLambdaUpdateWrapper.eq(Supplier::getId, supplier.getId()).set(Supplier::getSupplierAttribution, null);
                                supplierService.update(supplierLambdaUpdateWrapper);
                                supplier.setSupplierAttribution(null);
                            }else{
                                //导入
                                supplierPurchaseCategory.setState(AuthenticationState.QUALIFIED.getState());
                            }
                        }else{
                            supplierPurchaseCategory.setState(AuthenticationState.QUALIFIED.getState());
                        }

                    }else{
                        if(supplierPurchaseCategory.getState().equals(AuthenticationState.SMALL_BATCH.getState())){
                            supplierPurchaseCategory.setState(AuthenticationState.QUALIFIED.getState());
                        }else{
                            supplierPurchaseCategory.setState(AuthenticationState.SMALL_BATCH.getState());
                        }

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

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

        } 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_IMPORT_ACCESS;
    }
}
