package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.module.jg.api.dto.*;
import com.yeejoin.amos.boot.module.jg.api.entity.JgRegistrationHistory;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistration;
import com.yeejoin.amos.boot.module.jg.api.enums.CylinderTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IBizDataChangeHandleStrategy;
import com.yeejoin.amos.boot.module.jg.biz.service.IChangeDataProcessStrategy;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 批量维护使用登记策略实现类
 */
@Component
public class BatchDataChangeProcessStrategy implements IChangeDataProcessStrategy {

    private final JgUseRegistrationServiceImpl useRegistrationService;

    private final JgRegistrationHistoryServiceImpl jgRegistrationHistoryService;

    private final JgUseRegistrationMapper jgUseRegistrationMapper;

    private final CommonEquipDataProcessService commonEquipDataProcessService;

    public BatchDataChangeProcessStrategy(JgUseRegistrationServiceImpl useRegistrationService, JgRegistrationHistoryServiceImpl jgRegistrationHistoryService, JgUseRegistrationMapper jgUseRegistrationMapper, CommonEquipDataProcessService commonEquipDataProcessService) {
        this.useRegistrationService = useRegistrationService;
        this.jgRegistrationHistoryService = jgRegistrationHistoryService;
        this.jgUseRegistrationMapper = jgUseRegistrationMapper;
        this.commonEquipDataProcessService = commonEquipDataProcessService;
    }

    @Override
    public List<ChangeDataDto> handle(Map<String, Object> changeData, String defaultChangeId) {
        JSONObject data = (JSONObject) changeData;
        JSONArray equips = data.getJSONArray(RequestChangeData.multiDataKey);
        List<MultiChangeItemData> items = equips.toJavaList(MultiChangeItemData.class);
        List<ChangeDataDto> allChangeColumns = new ArrayList<>();
        // 校验
        items.forEach(item -> {
            String record = item.getRecord();
            Map<String, Object> itemData = item.getDetail();
            if (itemData != null) {
                EquipRegisterChangeDataDto registerChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipRegisterChangeDataDto.class);
                EquipFactoryChangeDataDto factoryChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipFactoryChangeDataDto.class);
                EquipDesignChangeDataDto designChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipDesignChangeDataDto.class);
                // 前置检验
                commonEquipDataProcessService.checkValidField(record, registerChangeDataDto, null, null, null);
                commonEquipDataProcessService.checkValidField(record, factoryChangeDataDto, registerChangeDataDto.getEquList(), registerChangeDataDto.getEquCategory(), registerChangeDataDto.getEquDefine());
                commonEquipDataProcessService.checkValidField(record, designChangeDataDto, registerChangeDataDto.getEquList(), registerChangeDataDto.getEquCategory(), registerChangeDataDto.getEquDefine());
            }
        });
        // 入库
        items.forEach(item -> {
            String record = item.getRecord();
            Map<String, Object> itemData = item.getDetail();
            if (itemData != null) {
                EquipRegisterChangeDataDto registerChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipRegisterChangeDataDto.class);
                EquipFactoryChangeDataDto factoryChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipFactoryChangeDataDto.class);
                EquipDesignChangeDataDto designChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipDesignChangeDataDto.class);
                commonEquipDataProcessService.buildChangeFields(record, designChangeDataDto, factoryChangeDataDto, registerChangeDataDto, allChangeColumns);
                // 设备制造、设计、注册信息业务处理落库
                commonEquipDataProcessService.dealBizDataForEquip(record, registerChangeDataDto);
                commonEquipDataProcessService.dealBizDataForEquip(record, factoryChangeDataDto);
                commonEquipDataProcessService.dealBizDataForEquip(record, designChangeDataDto);
                // 设备技术参数入库处理
                commonEquipDataProcessService.updateTechParamInfo(registerChangeDataDto, record, itemData, allChangeColumns);
            }
        });
        // 单位办理不能修改设备品种，如果修改无法保证单据下的所有设备都一致
        return allChangeColumns;
    }


    @Override
    public Map<String, List<Map<String, Object>>> getDetail(String applyNo, String bizId) {
        Map<String, List<Map<String, Object>>> result = new HashMap<>();
        JgUseRegistration jgUseRegistration = useRegistrationService.getOne(new LambdaQueryWrapper<JgUseRegistration>()
                .eq(JgUseRegistration::getApplyNo, applyNo).select(BaseEntity::getSequenceNbr));
        LambdaQueryWrapper<JgRegistrationHistory> lambda = new QueryWrapper<JgRegistrationHistory>().lambda();
        lambda.eq(JgRegistrationHistory::getCurrentDocumentId, jgUseRegistration.getSequenceNbr());
        lambda.eq(JgRegistrationHistory::getIsDelete, false);
        JgRegistrationHistory jgRegistrationHistory = jgRegistrationHistoryService.getBaseMapper().selectOne(lambda);
        JSONObject jsonObject = JSONObject.parseObject(jgRegistrationHistory.getChangeData());
        List<Map<String, Object>> equipmentLists = (List<Map<String, Object>>) jsonObject.get("equipmentLists");
        List<String> records = equipmentLists.stream().map(v -> (String) v.get("record")).collect(toList());
        List<Map<String, Object>> tableData;
        if (CylinderTypeEnum.CYLINDER.getCode().equals(jsonObject.get("EQU_CATEGORY_CODE"))) {
            List<DictionarieValueModel> fillingMedium = Systemctl.dictionarieClient.dictValues("FILLING_MEDIUM").getResult();
            Map<String, Object> fillingMediumMap = fillingMedium.stream().collect(Collectors.toMap(DictionarieValueModel::getDictDataKey, DictionarieValueModel::getDictDataValue));
            tableData = jgUseRegistrationMapper.queryForUnitVesselEquipment(records);
            tableData.forEach(i -> i.put("chargingMedium", fillingMediumMap.get(i.get("chargingMedium"))));
        } else {
            tableData = jgUseRegistrationMapper.queryForUnitPipelineEquipment(records);
        }
        result.put("tableData", tableData);
        return result;
    }


    @Override
    public IBizDataChangeHandleStrategy.ModelType canHandleMode() {
        return IBizDataChangeHandleStrategy.ModelType.batch;
    }
}
