package com.sw.mes.sap.reconciliation;

import cc.cczn.matrix.common.monitor.RecordLogger;
import com.alibaba.fastjson.JSON;
import com.sw.mes.sap.reconciliation.framework.ReconResult;
import com.sw.mes.sap.reconciliation.sap.SAPReconciliation;
import com.sw.mes.sap.reconciliation.warehouse.InventoryReconciliation;
import com.sw.mes.sap.reconciliation.warehouse.LineWarehouseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 对账逻辑入口
 *
 * @Author：wanjia
 * @Date：2024/2/24 21:57
 */
@Controller
@RequestMapping("/recon")
public class ReconciliationController {

    private static final Logger logger = LoggerFactory.getLogger(ReconciliationController.class);
    @Autowired
    private InventoryReconciliation inventoryReconciliation;

    @Autowired
    private LineWarehouseData lineWarehouseData;

    @Autowired
    private SAPReconciliation sapReconciliation;

    //防止运行时重复提交
    private AtomicBoolean inventoryRunning = new AtomicBoolean(false);

    @RequestMapping("/sap/{date}")
    @ResponseBody
    public String sap(@PathVariable("date") String date) {
        return JSON.toJSONString(sapReconciliation.sapReconciliation(date));
    }


    /**
     * 根据当前已经有的物料号进行线边仓库内全量对账，确保数据的库存=入库单-出库单
     *
     * @return
     */
    @RequestMapping("/warehouse/inventory/code")
    @ResponseBody
    public String warehouseReconciliationPerDay() {
        if (inventoryRunning.compareAndSet(false, true)) {
            int total, success = 0, error = 0, interrupt = 0;
            try {
                RecordLogger.warn("start WarehouseReconciliationPerDay....");
                Set<String> codeSet = lineWarehouseData.getDistinctMaterialCode(1, 1);
                if (CollectionUtils.isEmpty(codeSet)) {
                    return "codeSet is empty";
                }
                total = codeSet.size();
                for (String code : codeSet) {
                    try {
                        ReconResult result = inventoryReconciliation.checkInventory("Inventory", code);
                        if (result != null && result.isEqual()) {
                            success++;
                            continue;
                        }
                        error++;
                    } catch (Exception e) {
                        logger.error("", e);
                        interrupt++;
                    }
                }
                RecordLogger.warn("end for WarehouseReconciliationPerDay....");
                RecordLogger.error("WarehouseReconciliationPerDay, total:{}  success:{}  error:{} interrupt:{}", total, success, error, interrupt);
            } finally {
                inventoryRunning.set(false);
            }
        } else {
            return "全量任务正在进行中，请不要重复提交...";
        }
        return "SUCCESS";
    }

    /**
     * 对账单个数据
     *
     * @param code
     * @return
     */
    @RequestMapping("/warehouse/inventory/code/{code}")
    @ResponseBody
    public String warehouseReconciliationByCode(@PathVariable("code") String code) {
        return JSON.toJSONString(inventoryReconciliation.checkInventory("Inventory", code));
    }


    /**
     * 线边仓出库和sap上报记录进行全量对账
     *
     * @return
     */
    @RequestMapping("/warehouse/inventory/outandsap")
    @ResponseBody
    public String OutputAndSAPReconciliation() {
        RecordLogger.warn("start OutputAndSAPReconciliation....");
        inventoryReconciliation.outputAndSAPReconciliation();
        RecordLogger.warn("end OutputAndSAPReconciliation....");
        return "SUCCESS";
    }

}
