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

import com.alibaba.fastjson.JSON;
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.IdxBizJgProjectContraption;
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 JgRegistrationHistoryServiceImpl jgRegistrationHistoryService;

    private final IdxBizJgProjectContraptionServiceImpl idxBizJgProjectContraptionService;

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

    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);
            // 更新 设计、制造、基本信息json
            useRegistrationService.fillLastEquipBaseInfo(jsonObject, 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 {
                // 管道逻辑 更新装置、管道有关数据
                IdxBizJgProjectContraption projectContraption = idxBizJgProjectContraptionService.getById(jgUseRegistration.getProjectContraptionId());
                jsonObject.put("pipelineLength", projectContraption.getPipelineLength());
                jsonObject.put("projectContraption",projectContraption.getProjectContraption());
                jsonObject.put("projectContraptionNo", projectContraption.getProjectContraptionNo());
                jsonObject.put("equipmentLists", useRegistrationService.getBaseMapper().queryForUnitPipelineEquipment(records));
            }
        }
        jsonObject.put("useRegistrationCode", jgUseRegistration.getUseRegistrationCode());
        // 转化 附件 字段
        this.convertStringToJsonObject(jsonObject, JgUseRegistrationServiceImpl.jsonFields);
        return jsonObject;
    }

    public void convertStringToJsonObject(Object obj, String[] jsonFields) {
        if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) obj;
            for (String field : jsonFields) {
                if (jsonObject.get(field) != null && jsonObject.get(field) instanceof String) {
                    jsonObject.put(field, JSON.parse(JSONObject.toJSONString(jsonObject.get(field))));
                }
            }
        } else if (obj instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) obj;
            for (String field : jsonFields) {
                if (map.containsKey(field) && map.get(field) instanceof String) {
                    map.put(field, JSON.parse(JSONObject.toJSONString(map.get(field))));
                }
            }
        } else {
            // 处理其他类型
            System.out.println("Unsupported Object Type");
        }
    }

}
