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

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.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.ymt.api.entity.IdxBizJgRegisterInfo;
import com.yeejoin.amos.boot.module.ymt.api.mapper.IdxBizJgRegisterInfoMapper;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

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

@Service
public class UseRegisterUpdateService {

    private final IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper;

    private final JgUseRegistrationServiceImpl useRegistrationService;

    private final CommonServiceImpl commonService;

    private final JgRegistrationHistoryServiceImpl jgRegistrationHistoryService;

    public UseRegisterUpdateService(IdxBizJgRegisterInfoMapper idxBizJgRegisterInfoMapper, JgUseRegistrationServiceImpl useRegistrationService, CommonServiceImpl commonService, JgRegistrationHistoryServiceImpl jgRegistrationHistoryService) {
        this.idxBizJgRegisterInfoMapper = idxBizJgRegisterInfoMapper;
        this.useRegistrationService = useRegistrationService;
        this.commonService = commonService;
        this.jgRegistrationHistoryService = jgRegistrationHistoryService;
    }

    public void updateHisData(String applyNo) {
        JgUseRegistration jgUseRegistration = useRegistrationService.getOne(new LambdaQueryWrapper<JgUseRegistration>().eq(JgUseRegistration::getApplyNo, applyNo));
        // 构建更新json数据
        JSONObject hisData = this.buildLastDetailData(jgUseRegistration);
        // 更新数据
        useRegistrationService.updateHistory(hisData, null, jgUseRegistration.getSequenceNbr().toString(), jgUseRegistration.getSupervisoryCode());
    }

    public JSONObject buildLastDetailData(JgUseRegistration jgUseRegistration) {
        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());
        jsonObject.put("receiveOrgCode", jgUseRegistration.getReceiveCompanyCode() + "_" + jgUseRegistration.getReceiveOrgName());
        jsonObject.put("status", jgUseRegistration.getStatus());
        jsonObject.put("applyNo", jgUseRegistration.getApplyNo());
        jsonObject.remove("submit");
        jsonObject.remove("instanceId");
        if (!ObjectUtils.isEmpty(jsonObject.get("factoryUseSiteStreet"))) {
            jsonObject.put("factoryUseSiteStreet", String.valueOf(Long.valueOf(jsonObject.get("factoryUseSiteStreet").toString())));
        }
        if (!"unit".equals(jgUseRegistration.getManageType())) {
            String record = useRegistrationService.setDefaultRecord(jgUseRegistration, null);
            // 需求：当申请信息由于设备信息错误被驳回及撤回时显示的数据还是旧设备数据，导致该申请单无法使用
            // 解决方案：设备基本信息、制造信息、设计信息、安装信息、维保信息，已完成时显示历史数据、非完成时显示最新设备数据
            useRegistrationService.fillHistoryDataWithNewEquip(jsonObject, jgUseRegistration, record);
            // 补充"车牌号"字段
            LambdaQueryWrapper<IdxBizJgRegisterInfo> wrapper = new QueryWrapper<IdxBizJgRegisterInfo>().lambda().eq(IdxBizJgRegisterInfo::getRecord, record);
            IdxBizJgRegisterInfo idxBizJgRegisterInfo = idxBizJgRegisterInfoMapper.selectOne(wrapper);
            jsonObject.put("carNumber", idxBizJgRegisterInfo.getCarNumber());
            jsonObject.put("regType", jgUseRegistration.getRegType());
        } else {
            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());
            jsonObject.remove("equipmentLists");
            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));
                List<Map<String, Object>> result = useRegistrationService.getBaseMapper().queryForUnitVesselEquipment(records);
                result.forEach(i -> {
                    i.put("chargingMedium", fillingMediumMap.get(i.get("chargingMedium")));
                });
                jsonObject.put("equipmentLists", result);
            } else {
                jsonObject.put("equipmentLists", useRegistrationService.getBaseMapper().queryForUnitPipelineEquipment(records));
            }
        }
        jsonObject.put("useRegistrationCode", jgUseRegistration.getUseRegistrationCode());
        // 转化 附件 字段
        commonService.convertStringToJsonobject(jsonObject, JgUseRegistrationServiceImpl.jsonFields);
        return jsonObject;
    }

}
