package com.yeejoin.amos.api.openapi.face.service;


import cn.hutool.core.collection.ConcurrentHashSet;
import com.google.common.collect.Lists;
import com.yeejoin.amos.api.openapi.enums.*;
import com.yeejoin.amos.api.openapi.face.model.*;
import com.yeejoin.amos.api.openapi.face.orm.dao.MidEquipRegistrationInfoMapper;
import com.yeejoin.amos.boot.module.cylinder.api.dto.TzBaseEnterpriseInfoDto;
import com.yeejoin.amos.boot.module.cylinder.api.entity.CylinderFillingMessageEntity;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * 气瓶数据校验
 */
@Component
public class CylinderFillingDataValidationService {

    @Autowired
    BaseEnterpriseInfoService enterpriseInfoService;

    @Autowired
    MidEquipRegistrationInfoMapper registrationInfoMapper;

    @Autowired
    TmCylinderInfoService cylinderInfoService;

    @Autowired
    TmCylinderFillingMessageService cylinderFillingMessageService;

    /**
     * 企业信息校验
     *
     * @param unitData
     */
    public void validateCylinderUnit(List<TmCylinderUnitModel> unitData) {
//        JSONArray jsonArray = JSONArray.fromObject(unitData);
//        // 1.必填校验
//        List<String> errorRows = validateRequired(CylinderUnitFieldEnum.getAllRequireKeys(), jsonArray);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject( errorRows.stream().map(e -> "必填字段不能为空：" + e).collect(Collectors.toList())).toString());
//        }
//        // 2.本次上传数据唯一性校验
//        errorRows = validateUnique(CylinderUnitFieldEnum.getAllUniqueKeys(), jsonArray, errorCylinderSet);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject( errorRows.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList())).toString());
//        }
//        // 3.检查企业统一社会信用代码是否存在
//        Set<String> creditCodes = getAllData(FillingBeforeFieldEnum.creditCode.name(), jsonArray);
//        errorRows = getNotExistEnterpriseInfoByCreditCode(creditCodes);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(errorRows.stream().map(e -> "企业统一社会信用代码不存在：" + e).collect(Collectors.toList())).toString());
//        }
    }


    /**
     * 校验气瓶基本信息数据
     *
     * @param infoData
     */
    public void validateCylinderInfo(List<TmCylinderInfoModel> infoData) {
//        JSONArray jsonArray = JSONArray.fromObject(infoData);
//        // 1.必填校验
//        List<String> errorRows = validateRequired(CylinderInfoFieldEnum.getAllRequireKeys(), jsonArray);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject( errorRows.stream().map(e -> "必填字段不能为空：" + e).collect(Collectors.toList())).toString());
//        }
//        // 2.本次上传数据唯一性校验
//        errorRows = validateUnique(CylinderInfoFieldEnum.getAllUniqueKeys(), jsonArray, errorCylinderSet);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList())).toString());
//        }
//        // 3.检查气瓶唯一标识码是否存在
//        Set<String> sequenceCodes = getAllData(FillingBeforeFieldEnum.sequenceCode.name(), jsonArray);
//        errorRows = getNotExistSequenceCodes(sequenceCodes);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "气瓶唯一标识码不存在：" + e).collect(Collectors.toList())).toString());
//        }
//        // 4.检查企业统一社会信用代码是否存在
//        Set<String> creditCodes = getAllData(FillingBeforeFieldEnum.creditCode.name(), jsonArray);
//        errorRows = getNotExistEnterpriseInfoByCreditCode(creditCodes);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "企业统一社会信用代码不存在：" + e).collect(Collectors.toList())).toString());
//        }
    }

    /**
     * 校验气瓶标签
     *
     * @param tagData
     */
    public void validateCylinderTag(List<TmCylinderTagsModel> tagData) {
//        JSONArray jsonArray = JSONArray.fromObject(tagData);
//        // 1.必填校验
//        List<String> errorRows = validateRequired(CylinderTagFieldEnum.getAllRequireKeys(), jsonArray);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject( errorRows.stream().map(e -> "必填字段不能为空：" + e).collect(Collectors.toList())).toString());
//        }
//
//        // 2.本次上传数据唯一性校验
//        errorRows = validateUnique(CylinderTagFieldEnum.getAllUniqueKeys(), jsonArray, errorCylinderSet);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList())).toString());
//        }
        // 3.检查气瓶唯一标识码是否存在
//        Set<String> sequenceCodes = getAllData(FillingBeforeFieldEnum.sequenceCode.name(), jsonArray);
//        errorRows = getNotExistSequenceCodes(sequenceCodes);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "气瓶唯一标识码不存在：" + e).collect(Collectors.toList())).toString());
//        }
    }

    /**
     * 气瓶检验信息
     *
     * @param inspectionData
     */
    public void validateCylinderInspection(List<TmCylinderInspectionModel> inspectionData) {
//        JSONArray jsonArray = JSONArray.fromObject(inspectionData);
//        // 1.必填校验
//        List<String> errorRows = validateRequired(CylinderInspectionFieldEnum.getAllRequireKeys(), jsonArray);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject( errorRows.stream().map(e -> "必填字段不能为空：" + e).collect(Collectors.toList())).toString());
//        }
//
//        // 2.本次上传数据唯一性校验
//        errorRows = validateUnique(CylinderInspectionFieldEnum.getAllUniqueKeys(), jsonArray, errorCylinderSet);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList())).toString());
//        }
        // 3.检查气瓶唯一标识码是否存在
//        Set<String> sequenceCodes = getAllData(FillingBeforeFieldEnum.sequenceCode.name(), jsonArray);
//        errorRows = getNotExistSequenceCodes(sequenceCodes);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "气瓶唯一标识码不存在：" + e).collect(Collectors.toList())).toString());
//        }
    }


    /**
     * 校验审核信息
     *
     * @param inspectionData
     */
    public void validateCylinderFillingExamineModel(List<TmCylinderFillingExamineModel> inspectionData) {
//        JSONArray jsonArray = JSONArray.fromObject(inspectionData);
//        // 1.必填校验
//        List<String> errorRows = validateRequired(CylinderFillingAuditFieldEnum.getAllRequireKeys(), jsonArray);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject( errorRows.stream().map(e -> "必填字段不能为空：" + e).collect(Collectors.toList())).toString());
//        }
//
//        // 2.本次上传数据唯一性校验
//        errorRows = validateUnique(CylinderFillingAuditFieldEnum.getAllUniqueKeys(), jsonArray, errorCylinderSet);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList())).toString());
//        }
        // 3.检查气瓶唯一标识码是否存在
//        Set<String> sequenceCodes = getAllData(FillingBeforeFieldEnum.sequenceCode.name(), jsonArray);
//        errorRows = getNotExistSequenceCodes(sequenceCodes);
//        if (!ObjectUtils.isEmpty(errorRows)) {
//            throw new BadRequest(JSONArray.fromObject(  errorRows.stream().map(e -> "气瓶唯一标识码不存在：" + e).collect(Collectors.toList())).toString());
//        }
    }

    /**
     * 验证气瓶充装数据
     * @return
     */
    public CylinderFillingDataValidationResultModel validateFilling(JSONObject jsonobject) throws ExecutionException, InterruptedException {
        CylinderFillingDataValidationResultModel result = new CylinderFillingDataValidationResultModel();
        if (ObjectUtils.isEmpty(jsonobject)) {
          throw new BadRequest("上传数据不能为空！！！");
        }
        if (!jsonobject.containsKey("fillingBefore") || ObjectUtils.isEmpty(jsonobject.get("fillingBefore"))) {
            throw new BadRequest("充装前检查数据不能为空！！！");
        }
        if (!jsonobject.containsKey("filling") || ObjectUtils.isEmpty(jsonobject.get("filling"))) {
            throw new BadRequest("充装数据不能为空！！！");
        }
        if (!jsonobject.containsKey("fillingAfter") || ObjectUtils.isEmpty(jsonobject.get("fillingAfter"))) {
            throw new BadRequest("充装后复查数据不能为空！！！");
        }

        Set<String> cylinderCodeSet = new ConcurrentHashSet<>();
        Set<String> beforeErrorCylinderSet = new ConcurrentHashSet<>();
        Set<String> recordErrorCylinderSet = new ConcurrentHashSet<>();
        Set<String> afterErrorCylinderSet = new ConcurrentHashSet<>();

        CompletableFuture<List<String>> beforeFuture = CompletableFuture.supplyAsync(() -> {
            // 异步校验充装前数据
            JSONArray fillingBefore = jsonobject.getJSONArray("fillingBefore");
            if (!ObjectUtils.isEmpty(fillingBefore)) {
                for (int i = 0; i < fillingBefore.size(); i++) {
                    JSONObject row = fillingBefore.getJSONObject(i);
                    cylinderCodeSet.add(row.getString("sequenceCode"));
                }
            }
            return validateFillingBeforeData(fillingBefore, beforeErrorCylinderSet);
        });
        CompletableFuture<List<String>> recordFuture = CompletableFuture.supplyAsync(() -> {
            //  异步校验检充装时数据
            JSONArray filling = jsonobject.getJSONArray("filling");
            if (!ObjectUtils.isEmpty(filling)) {
                for (int i = 0; i < filling.size(); i++) {
                    JSONObject row = filling.getJSONObject(i);
                    cylinderCodeSet.add(row.getString("sequenceCode"));
                }
            }
            return validateFillingRecordData(filling, recordErrorCylinderSet);
        });

        CompletableFuture<List<String>> afterFuture = CompletableFuture.supplyAsync(() -> {
            // 异步校验充装后数据
            JSONArray fillingAfter = jsonobject.getJSONArray("fillingAfter");
            if (!ObjectUtils.isEmpty(fillingAfter)) {
                for (int i = 0; i < fillingAfter.size(); i++) {
                    JSONObject row = fillingAfter.getJSONObject(i);
                    cylinderCodeSet.add(row.getString("sequenceCode"));
                }
            }
            return validateFillingAfterData(fillingAfter, afterErrorCylinderSet);
        });

        // 等待校验结果
        CompletableFuture.allOf(beforeFuture, recordFuture, afterFuture);
        result.setBeforeErrorData(beforeFuture.get());
        result.setRecordErrorData(recordFuture.get());
        result.setAfterErrorData(afterFuture.get());
        result.setCylinderNumber(cylinderCodeSet.size());

        result.setBeforeErrorCylinderNumber(beforeErrorCylinderSet.size());
        result.setRecordErrorCylinderNumber(recordErrorCylinderSet.size());
        result.setAfterErrorCylinderNumber(afterErrorCylinderSet.size());
        cylinderCodeSet.removeAll(beforeErrorCylinderSet);
        cylinderCodeSet.removeAll(recordErrorCylinderSet);
        cylinderCodeSet.removeAll(afterErrorCylinderSet);

        if (!ObjectUtils.isEmpty(cylinderCodeSet)) {
            // 检查气瓶唯一标识码在系统是否存在
            List<String> errorRows = getNotExistSequenceCodes(cylinderCodeSet);
            result.setSeqCodeErrorData(errorRows);
        }

        result.setSuccessCylinderNumber(cylinderCodeSet.size());
        return result;
    }


    /**
     * 验证检验前数据
     * @param jsonArray
     * @return List 异常数据
     */
    public List<String> validateFillingBeforeData(JSONArray jsonArray, Set<String> errorCylinderSet) {
        List<String> errorRows = Lists.newArrayList();
        // 1.必填校验
        errorRows.addAll(validateRequiredByStage(CylinderField.FillStage.BEFORE, jsonArray, errorCylinderSet));
        // 2.本次上传数据唯一性校验
        errorRows.addAll(validateUniqueByStage(CylinderField.FillStage.BEFORE, jsonArray, errorCylinderSet));
        return errorRows;
    }

    /**
     * 验证检验记录数据
     * @param jsonArray
     * @return List 异常数据
     */
    public List<String> validateFillingRecordData(JSONArray jsonArray, Set<String>  errorCylinderSet) {
        List<String> errorRows = Lists.newArrayList();
        // 1.必填校验
        errorRows.addAll(validateRequiredByStage(CylinderField.FillStage.FILLING, jsonArray, errorCylinderSet));
        // 2.本次上传数据唯一性校验
        errorRows.addAll(validateUniqueByStage(CylinderField.FillStage.FILLING, jsonArray, errorCylinderSet));
        return errorRows;
    }

    /**
     * 验证检验后数据
     * @param jsonArray
     * @return List 异常数据
     */
    public List<String> validateFillingAfterData(JSONArray jsonArray, Set<String>  errorCylinderSet) {
        List<String> errorRows = Lists.newArrayList();
        // 1.必填校验
        errorRows.addAll(validateRequiredByStage(CylinderField.FillStage.AFTER, jsonArray, errorCylinderSet));
        // 2.本次上传数据唯一性校验
        errorRows.addAll(validateUniqueByStage(CylinderField.FillStage.AFTER, jsonArray, errorCylinderSet));
        return errorRows;
    }

    /**
     * 必填校验
     * @param jsonArray 被校验数据
     * @param errorCylinderSet 错误气瓶集合
     * @return 校验结果 通过为 true，不通过为false
     */
    public List<String> validateRequiredByStage(CylinderField.FillStage stage, JSONArray jsonArray, Set<String> errorCylinderSet) {
        List<String> errorList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);
            CylinderType type = CylinderType.getByCode(row.getString("cylinderType"));
            List<String> keys = CylinderTypeFieldValidation.getRequiredFieldsForType(type, stage.getCode());
            for (String key : keys) {
                if (!row.containsKey(key) || ObjectUtils.isEmpty(row.get(key)) || row.get(key).equals(JSONNull.getInstance())) {
                    errorList.add(row.toString());
                }
            }
        }

        if (!ObjectUtils.isEmpty(errorList)) {
            errorList.forEach(json -> {
                String sequenceCode = JSONObject.fromObject(json).getString("sequenceCode");
                errorCylinderSet.add(sequenceCode);
            });
            JSONObject result = new JSONObject();
            result.put("result", "必填字段不能为空");
            return errorList.stream().map(e -> { result.put("errorData", e); return result.toString(); }).collect(Collectors.toList());
        }

        return errorList;
    }

    /**
     * 数据唯一性校验
     *
     * @param jsonArray        被校验数据
     * @param errorCylinderSet 错误气瓶集合
     * @return 校验结果 通过为 true，不通过为false
     */
    public List<String> validateUniqueByStage(CylinderField.FillStage stage, JSONArray jsonArray, Set<String> errorCylinderSet) {
        Map<String, Set<Object>> valuesMap = new HashMap<>();
        List<String> errorList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);
            CylinderType type = CylinderType.getByCode(row.getString("cylinderType"));
            List<String> keys = CylinderTypeFieldValidation.getUniqueFieldsForType(type, stage.getCode());
            for (String key : keys) {
                if (!valuesMap.containsKey(key)) {
                    valuesMap.put(key, new HashSet<>());
                }
                if (valuesMap.get(key).contains(row.get(key))) {
                    errorList.add(row.toString());
                }
                valuesMap.get(key).add(row.get(key));
            }
        }

        if (!ObjectUtils.isEmpty(errorList)) {
            errorList.forEach(json -> {
                String sequenceCode = JSONObject.fromObject(json).getString("sequenceCode");
                errorCylinderSet.add(sequenceCode);
            });
            return errorList.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList());
        }

        return errorList;
    }

    /**
     * 必填校验
     * @param keys 需要校验的key
     * @param jsonArray 被校验数据
     * @return 校验结果 通过为 true，不通过为false
     */
    public List<String> validateRequired(List<String> keys, JSONArray jsonArray) {
        List<String> errorList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);
            for (String key : keys) {
                if (!row.containsKey(key) || ObjectUtils.isEmpty(row.get(key)) || row.get(key).equals(JSONNull.getInstance())) {
                    errorList.add(row.toString());
                }
            }
        }

        if (!ObjectUtils.isEmpty(errorList)) {
            return errorList.stream().map(e -> "必填字段不能为空：" + e).collect(Collectors.toList());
        }

        return errorList;
    }

    /**
     * 数据唯一性校验
     *
     * @param keys             需要校验的key
     * @param jsonArray        被校验数据
     * @return 校验结果 通过为 true，不通过为false
     */
    public List<String> validateUnique(List<String> keys, JSONArray jsonArray) {
        Map<String, Set<Object>> valuesMap = new HashMap<>();
        List<String> errorList = new ArrayList<>();
        for (String key : keys) {
            valuesMap.put(key, new HashSet<>());
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);
            for (String key : keys) {
                if (valuesMap.get(key).contains(row.get(key))) {
                    errorList.add(row.toString());
                }
                valuesMap.get(key).add(row.get(key));
            }
        }

        if (!ObjectUtils.isEmpty(errorList)) {
            return errorList.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList());
        }

        return errorList;
    }

    /**
     * 获取指定 key的所有数据
     * @param key
     * @param jsonArray
     * @return
     */
    public Set<String> getAllData(String key, JSONArray jsonArray) {
        Set<String> sequenceCode = new HashSet<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);
            sequenceCode.add(row.get(key).toString());
        }
        return sequenceCode;
    }

    /**
     * 校验企业唯一信用代码
     * @param creditCodes
     * @return
     */
    public List<String> getNotExistEnterpriseInfoByCreditCode(Set<String> creditCodes) {
        List<TzBaseEnterpriseInfoDto> enterpriseInfos = enterpriseInfoService.getEnterpriseInfoByCreditCode(creditCodes);
        if (enterpriseInfos.size() < creditCodes.size()) {
            List<String> userCodes = enterpriseInfos.stream().map(TzBaseEnterpriseInfoDto::getUseCode).collect(Collectors.toList());
            return creditCodes.stream().filter(c -> !userCodes.contains(c)).collect(Collectors.toList());
        }
        return null;
    }

    /**
     *  获取不存在的气瓶编码
     * @param sequenceCodes
     * @return
     */
    public List<String> getNotExistSequenceCodes(Set<String> sequenceCodes) {
        List<String> usedSeqCodeList = registrationInfoMapper.getUsedCountBySeqCodes(sequenceCodes);
        if (usedSeqCodeList.size() < sequenceCodes.size()) {
            return sequenceCodes.stream().filter(c -> !usedSeqCodeList.contains(c)).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 气站卸液量记录数据校验
     *
     * @param offloadingData 卸液量数据
     */
    public void validateCylinderOffloadingData(List<TmCylinderOffloadingModel> offloadingData) {
        CylinderFillingMessageEntity logMessage = new CylinderFillingMessageEntity();
        JSONArray jsonArray = JSONArray.fromObject(offloadingData);
        // 1.必填校验
        List<String> errorRows = validateRequired(CylinderOffloadingFieldEnum.getAllRequireKeys(), jsonArray);
        if (!ObjectUtils.isEmpty(errorRows)) {
            String errorMsg = JSONArray.fromObject(errorRows.stream().map(e -> "必填字段不能为空：" + e).collect(Collectors.toList())).toString();
            logMessage.setMessage(errorMsg);
            cylinderFillingMessageService.save(logMessage);
            throw new BadRequest(errorMsg);
        }
        // 2.本次上传数据唯一性校验
        errorRows = validateUnique(CylinderOffloadingFieldEnum.getAllUniqueKeys(), jsonArray);
        if (!ObjectUtils.isEmpty(errorRows)) {
            String errorMsg = JSONArray.fromObject(errorRows.stream().map(e -> "上传数据重复：" + e).collect(Collectors.toList())).toString();
            logMessage.setMessage(errorMsg);
            cylinderFillingMessageService.save(logMessage);
            throw new BadRequest(errorMsg);
        }
    }
}
