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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
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.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.JgUseRegistration;
import com.yeejoin.amos.boot.module.jg.api.entity.JgUseRegistrationEq;
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.boot.module.ymt.api.entity.IdxBizJgProjectContraption;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgRegisterInfo;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

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 JgUseRegistrationEqServiceImpl useRegistrationEqService;

    private final JgUseRegistrationMapper jgUseRegistrationMapper;

    private final CommonEquipDataProcessService commonEquipDataProcessService;

    private final PieLineDataChangeServiceImpl pieLineDataChangeService;

    private final IdxBizJgProjectContraptionServiceImpl idxBizJgProjectContraptionService;


    public BatchDataChangeProcessStrategy(JgUseRegistrationServiceImpl useRegistrationService, JgUseRegistrationEqServiceImpl useRegistrationEqService, JgUseRegistrationMapper jgUseRegistrationMapper, CommonEquipDataProcessService commonEquipDataProcessService, PieLineDataChangeServiceImpl pieLineDataChangeService, IdxBizJgProjectContraptionServiceImpl idxBizJgProjectContraptionService) {
        this.useRegistrationService = useRegistrationService;
        this.useRegistrationEqService = useRegistrationEqService;
        this.jgUseRegistrationMapper = jgUseRegistrationMapper;
        this.commonEquipDataProcessService = commonEquipDataProcessService;
        this.pieLineDataChangeService = pieLineDataChangeService;
        this.idxBizJgProjectContraptionService = idxBizJgProjectContraptionService;
    }


    @Override
    public List<ChangeDataDto> handle(Map<String, Object> changeData, String defaultChangeId) {
        JSONObject data = (JSONObject) changeData;
        JSONArray equips = data.getJSONArray(RequestChangeData.multiDataKey);
        List<ChangeDataDto> allChangeColumns = new ArrayList<>();
        JgUseRegistration jgUseRegistration = useRegistrationService.getOne(new LambdaQueryWrapper<JgUseRegistration>().eq(JgUseRegistration::getApplyNo, defaultChangeId));
        // 判断是压力管道还是气瓶
        IdxBizJgRegisterInfo jgRegisterInfo = useRegistrationService.getRegisterInfo(jgUseRegistration);
        if (EquipmentClassifityEnum.YLGD.getCode().equals(jgRegisterInfo.getEquList())) { // 管道逻辑
            List<PipelineChangeItemDto> items = equips.toJavaList(PipelineChangeItemDto.class);
            // 1.装置基本信息校验、保存(前端返回的装置信息为大写 需注意)
            ProjectContraptionChangeDataDto projectContraptionChangeDataDto = commonEquipDataProcessService.castMap2Bean(changeData, ProjectContraptionChangeDataDto.class);
            this.calTotalPieLineLength(projectContraptionChangeDataDto, items);
            pieLineDataChangeService.update(projectContraptionChangeDataDto, allChangeColumns);
            // 2.使用登记表的装置名称更新
            updateUseRegisterProjectInfo(jgUseRegistration, projectContraptionChangeDataDto);
            // 设备技术参数入库前校验，约束：同一个装置下的管道编号不能重复
            if (items.size() != items.stream().map(TechParamsPipelineChangeFieldDto::getPipelineNumber).distinct().count()) {
                throw new BadRequest("同一工程装置下管道编号不能重复！");
            }
            // 3.管道信息入库保存
            items.forEach(item -> {
                String record = item.getRecord();
                // 设计信息更新
                pieLineDataChangeService.saveDesignForPieLine(record, allChangeColumns, item);
                // 技术参数入库保存
                TechParamsPipelineChangeFieldDto paramsPipelineChangeFieldDto = new TechParamsPipelineChangeFieldDto();
                BeanUtil.copyProperties(item, paramsPipelineChangeFieldDto, false);
                commonEquipDataProcessService.savePieLineTechParam(record, allChangeColumns, paramsPipelineChangeFieldDto);
            });
            // 4.更新所有管道的的冗余的管道名称字段（重点注意包括本次没做使用登记的管道也要更新)
            pieLineDataChangeService.updateEs(projectContraptionChangeDataDto);
        } else { // 气瓶逻辑
            List<MultiChangeItemData> items = equips.toJavaList(MultiChangeItemData.class);
            // 校验
            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);
                    EquipOtherInfoChangeDataDto otherInfoChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipOtherInfoChangeDataDto.class);
                    EquipUseInfoChangeDataDto useInfoChangeDataDto = commonEquipDataProcessService.castMap2Bean(itemData, EquipUseInfoChangeDataDto.class);
                    commonEquipDataProcessService.buildChangeFields(record, designChangeDataDto, factoryChangeDataDto, registerChangeDataDto, otherInfoChangeDataDto, useInfoChangeDataDto, allChangeColumns);
                    // 设备制造、设计、注册信息业务处理落库
                    commonEquipDataProcessService.dealBizDataForEquip(record, registerChangeDataDto);
                    commonEquipDataProcessService.dealBizDataForEquip(record, factoryChangeDataDto);
                    commonEquipDataProcessService.dealBizDataForEquip(record, designChangeDataDto);
                    commonEquipDataProcessService.dealBizDataForEquip(record, otherInfoChangeDataDto);
                    commonEquipDataProcessService.dealBizDataForEquip(record, useInfoChangeDataDto);
                    // 设备技术参数入库处理
                    commonEquipDataProcessService.updateTechParamInfo(registerChangeDataDto, record, itemData, allChangeColumns);
                }
            });
        }
        // 单位办理不能修改设备品种，如果修改无法保证单据下的所有设备都一致
        return allChangeColumns;
    }

    private void updateUseRegisterProjectInfo(JgUseRegistration jgUseRegistration, ProjectContraptionChangeDataDto projectContraptionChangeDataDto) {
        LambdaUpdateWrapper<JgUseRegistration> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(JgUseRegistration::getSequenceNbr, jgUseRegistration.getSequenceNbr());
        updateWrapper.set(JgUseRegistration::getProjectContraption, projectContraptionChangeDataDto.getProjectContraption());
        useRegistrationService.update(null, updateWrapper);
    }

    private void calTotalPieLineLength(ProjectContraptionChangeDataDto projectContraptionChangeDataDto, List<PipelineChangeItemDto> items) {
        projectContraptionChangeDataDto.setPipelineLength(items.stream().filter(i -> i.getPipeLength() != null).mapToDouble(TechParamsPipelineChangeFieldDto::getPipeLength).sum());
    }


    @Override
    public Map<String, Object> getDetail(String applyNo, String bizId) {
        Map<String, Object> result = new HashMap<>();
        JgUseRegistration jgUseRegistration = useRegistrationService.getOne(new LambdaQueryWrapper<JgUseRegistration>()
                .eq(JgUseRegistration::getApplyNo, applyNo).select(BaseEntity::getSequenceNbr, JgUseRegistration::getProjectContraptionId));
        LambdaQueryWrapper<JgUseRegistrationEq> lambda = new QueryWrapper<JgUseRegistrationEq>().lambda();
        lambda.eq(JgUseRegistrationEq::getEquipTransferId, jgUseRegistration.getSequenceNbr());
        lambda.select(JgUseRegistrationEq::getEquId);
        List<JgUseRegistrationEq> eqs = useRegistrationEqService.getBaseMapper().selectList(lambda);
        List<String> records = eqs.stream().map(JgUseRegistrationEq::getEquId).collect(toList());
        IdxBizJgRegisterInfo registerInfo = useRegistrationService.getRegisterInfo(jgUseRegistration);
        List<Map<String, Object>> tableData;
        if (EquipmentClassifityEnum.YLGD.getCode().equals(registerInfo.getEquList())) {
            IdxBizJgProjectContraption idxBizJgProjectContraption = idxBizJgProjectContraptionService.getById(jgUseRegistration.getProjectContraptionId());
            Map<String, Object> map = IdxBizJgRegisterInfoServiceImpl.convertCamelToUnderscore(idxBizJgProjectContraption, IdxBizJgProjectContraptionServiceImpl.jsonFields);
            result.putAll(map);
            result.put("projectContraptionId", idxBizJgProjectContraption.getSequenceNbr());
            tableData = jgUseRegistrationMapper.queryForUnitPipelineEquipmentForEdit(records);
        } else {
            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"))));
        }
        result.put("tableData", tableData);
        return result;
    }

    private Map<String, Object> cast2UnderCase(Map<String, Object> re) {
        // 由于历史遗留问题，和前端保存统一，要转成大写下滑线驼峰
        Map<String, Object> result = new HashMap<>();
        re.forEach((k, v) -> {
            result.put(CharSequenceUtil.toUnderlineCase(k).toUpperCase(), v);
        });
        return result;
    }


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