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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.module.common.api.dao.ESEquipmentCategory;
import com.yeejoin.amos.boot.module.common.api.dto.ESEquipmentCategoryDto;
import com.yeejoin.amos.boot.module.jg.biz.service.*;
import com.yeejoin.amos.boot.module.ymt.api.entity.*;
import com.yeejoin.amos.boot.module.ymt.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.ymt.api.mapper.CategoryOtherInfoMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

import static com.alibaba.fastjson.JSON.toJSONString;

@Slf4j
@Service
public class XiAnDataDockServiceImpl {

    @Autowired
    private ESEquipmentCategory esEquipmentCategory;
    @Autowired
    private CategoryOtherInfoMapper categoryOtherInfoMapper;
    @Autowired
    private IIdxBizJgUseInfoService idxBizJgUseInfoService;
    @Autowired
    private IdxBizJgDesignInfoServiceImpl idxBizJgDesignInfoService;
    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;
    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoServiceImpl;
    @Autowired
    private IdxBizJgSupervisionInfoServiceImpl idxBizJgSupervisionInfoService;
    @Autowired
    private IdxBizJgOtherInfoServiceImpl idxBizJgOtherInfoService;

    @Autowired
    IIdxBizJgTechParamsVehicleService iIdxBizJgTechParamsVehicleService;

    @Autowired
    IIdxBizJgTechParamsLiftingService iIdxBizJgTechParamsLiftingService;

    @Autowired
    IIdxBizJgTechParamsBoilerService iIdxBizJgTechParamsBoilerService;

    @Autowired
    IIdxBizJgTechParamsVesselService iIdxBizJgTechParamsVesselService;

    @Autowired
    IIdxBizJgTechParamsPipelineService iIdxBizJgTechParamsPipelineService;

    @Autowired
    IIdxBizJgTechParamsRidesService iIdxBizJgTechParamsRidesService;

    @Autowired
    IIdxBizJgTechParamsRopewayService iIdxBizJgTechParamsRopewayService;

    @Autowired
    private TransactionTemplate transactionTemplate;


    /**
     * 保存设备信息
     *
     * @param equLists 数据集
     * @return 保存结果
     */
    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public boolean saveEquipmentData(List<Map<?, ?>> equLists) {
        CompletableFuture.allOf(equLists.stream().map(equ -> CompletableFuture.runAsync(() -> saveEquipmentDataInTransaction(equ))).toArray(CompletableFuture[]::new)).join();
        return Boolean.TRUE;
    }

    private void saveEquipmentDataInTransaction(Map<?, ?> equ) {
        try {
            transactionTemplate.execute(status -> {
                String record = UUID.randomUUID().toString();
                String equList = String.valueOf(equ.get("equList"));
                // 保存到设备表
                saveUseInfo(equ, record);
                saveDesignInfo(equ, record);
                saveFactoryInfo(equ, record);
                saveRegisterInfo(equ, record);
                saveSupervisionInfo(equ, record);
                saveOtherInfo(equ, record);
                // 保存技术参数
                saveTechParams(equ, record, equList);
                // 保存到ES
                saveEquInfoToEs(record);
                return null;
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("西安数据：保存时出现异常，对应数据：{}", JSONObject.toJSONString(equ));
            log.error("异常信息：{}", e.getMessage());
            log.error("异常原因：{}", e.getMessage());
        }
    }

    /**
     * 保存使用信息表
     *
     * @param equ
     * @param record
     */
    private void saveUseInfo(Map<?, ?> equ, String record) {
        IdxBizJgUseInfo useInfo = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgUseInfo.class);
        if (!ValidationUtil.isEmpty(useInfo)) {
            useInfo.setRecDate(new Date());
            useInfo.setRecord(record);
            useInfo.setDataSource("jg_his_xa");
            useInfo.setIsNotEs("1");
            useInfo.setIsIntoManagement(Boolean.FALSE);
            useInfo.setUseUnitCreditCode(String.valueOf(equ.get("useUnitCode")).trim());
            useInfo.setUseUnitName(String.valueOf(equ.get("useUnit")).trim());
            idxBizJgUseInfoService.save(useInfo);
        }
    }

    /**
     * 保存设计信息表
     *
     * @param equ
     * @param record
     */
    private void saveDesignInfo(Map<?, ?> equ, String record) {
        IdxBizJgDesignInfo designInfo = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgDesignInfo.class);
        if (!ValidationUtil.isEmpty(designInfo)) {
            designInfo.setRecord(record);
            designInfo.setRecDate(new Date());
            idxBizJgDesignInfoService.save(designInfo);
        }
    }

    /**
     * 保存制造信息
     *
     * @param equ
     * @param record
     */
    private void saveFactoryInfo(Map<?, ?> equ, String record) {
        IdxBizJgFactoryInfo factoryInfo = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgFactoryInfo.class);
        if (!ValidationUtil.isEmpty(factoryInfo)) {
            factoryInfo.setRecord(record);
            factoryInfo.setRecDate(new Date());
            idxBizJgFactoryInfoService.save(factoryInfo);
        }
    }

    /**
     * 保存注册登记信息表
     *
     * @param equ
     * @param record
     */
    private void saveRegisterInfo(Map<?, ?> equ, String record) {
        IdxBizJgRegisterInfo registerInfo = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgRegisterInfo.class);
        if (!ValidationUtil.isEmpty(registerInfo)) {
            registerInfo.setRecord(record);
            registerInfo.setRecDate(new Date());
            registerInfo.setRegisterState("6045");
            idxBizJgRegisterInfoServiceImpl.save(registerInfo);
        }
    }

    /**
     * 保存监督管理信息表
     *
     * @param equ
     * @param record
     */
    private void saveSupervisionInfo(Map<?, ?> equ, String record) {
        IdxBizJgSupervisionInfo supervisionInfo = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgSupervisionInfo.class);
        if (!ValidationUtil.isEmpty(supervisionInfo)) {
            supervisionInfo.setRecord(record);
            supervisionInfo.setRecDate(new Date());
            idxBizJgSupervisionInfoService.save(supervisionInfo);
        }
    }

    /**
     * 保存其他信息表
     *
     * @param equ
     * @param record
     */
    private void saveOtherInfo(Map<?, ?> equ, String record) {
        IdxBizJgOtherInfo otherInfo = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgOtherInfo.class);
        if (!ValidationUtil.isEmpty(otherInfo)) {
            otherInfo.setRecord(record);
            otherInfo.setClaimStatus("已认领");
            otherInfo.setRecDate(new Date());
            idxBizJgOtherInfoService.save(otherInfo);
        }
    }

    /**
     * 保存技术参数
     *
     * @param equ
     * @param record
     * @param equList
     */
    private void saveTechParams(Map<?, ?> equ, String record, String equList) {
        if (EquipmentClassifityEnum.QZJX.getCode().equals(equList)) {
            saveLiftingParams(equ, record);
        } else if (EquipmentClassifityEnum.CC.getCode().equals(equList)) {
            saveVehicleParams(equ, record);
        } else if (EquipmentClassifityEnum.GL.getCode().equals(equList)) {
            saveBoilerParams(equ, record);
        } else if (EquipmentClassifityEnum.YLRQ.getCode().equals(equList)) {
            saveVesselParams(equ, record);
        } else if (EquipmentClassifityEnum.YLGD.getCode().equals(equList)) {
            savePipelineParams(equ, record);
        } else if (EquipmentClassifityEnum.YLSS.getCode().equals(equList)) {
            saveRidesParams(equ, record);
        } else if (EquipmentClassifityEnum.KYSD.getCode().equals(equList)) {
            saveRopewayParams(equ, record);
        }
    }

    /**
     * 保存起重机械技术参数
     *
     * @param equ
     * @param record
     */
    private void saveLiftingParams(Map<?, ?> equ, String record) {
        IdxBizJgTechParamsLifting equipTechParamLifting = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgTechParamsLifting.class);
        if (!ValidationUtil.isEmpty(equipTechParamLifting)) {
            equipTechParamLifting.setRecord(record);
            equipTechParamLifting.setRecDate(new Date());
            iIdxBizJgTechParamsLiftingService.saveOrUpdateData(equipTechParamLifting);
        }
    }

    /**
     * 保存场内机动车辆技术参数
     *
     * @param equ
     * @param record
     */
    private void saveVehicleParams(Map<?, ?> equ, String record) {
        IdxBizJgTechParamsVehicle equipTechParamVehicle = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgTechParamsVehicle.class);
        if (!ValidationUtil.isEmpty(equipTechParamVehicle)) {
            equipTechParamVehicle.setRecord(record);
            equipTechParamVehicle.setRecDate(new Date());
            iIdxBizJgTechParamsVehicleService.saveOrUpdateData(equipTechParamVehicle);
        }
    }

    /**
     * 保存锅炉技术参数
     *
     * @param equ
     * @param record
     */
    private void saveBoilerParams(Map<?, ?> equ, String record) {
        IdxBizJgTechParamsBoiler equipTechParamBoiler = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgTechParamsBoiler.class);
        if (!ValidationUtil.isEmpty(equipTechParamBoiler)) {
            equipTechParamBoiler.setRecord(record);
            equipTechParamBoiler.setRecDate(new Date());
            iIdxBizJgTechParamsBoilerService.saveOrUpdateData(equipTechParamBoiler);
        }
    }

    /**
     * 保存压力容器技术参数
     *
     * @param equ
     * @param record
     */
    private void saveVesselParams(Map<?, ?> equ, String record) {
        IdxBizJgTechParamsVessel equipTechParamVessel = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgTechParamsVessel.class);
        if (!ValidationUtil.isEmpty(equipTechParamVessel)) {
            equipTechParamVessel.setRecord(record);
            equipTechParamVessel.setRecDate(new Date());
            iIdxBizJgTechParamsVesselService.saveOrUpdateData(equipTechParamVessel);
        }
    }

    /**
     * 保存压力管道技术参数
     *
     * @param equ
     * @param record
     */
    private void savePipelineParams(Map<?, ?> equ, String record) {
        IdxBizJgTechParamsPipeline equipTechParamPipeline = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgTechParamsPipeline.class);
        if (!ValidationUtil.isEmpty(equipTechParamPipeline)) {
            equipTechParamPipeline.setWallThickness(String.valueOf(equ.get("wallThickness_YLGD")));
            equipTechParamPipeline.setMedium(String.valueOf(equ.get("medium_YLGD")));
            equipTechParamPipeline.setTemperature(String.valueOf(equ.get("temperature_YLGD")));
            equipTechParamPipeline.setDeviceLevel(String.valueOf(equ.get("deviceLevel_YLGD")));
            equipTechParamPipeline.setRecord(record);
            equipTechParamPipeline.setRecDate(new Date());
            iIdxBizJgTechParamsPipelineService.saveOrUpdateData(equipTechParamPipeline);
        }
    }

    /**
     * 保存大型游乐设施技术参数
     *
     * @param equ
     * @param record
     */
    private void saveRidesParams(Map<?, ?> equ, String record) {
        IdxBizJgTechParamsRides equipTechParamRides = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgTechParamsRides.class);
        if (!ValidationUtil.isEmpty(equipTechParamRides)) {
            equipTechParamRides.setRecord(record);
            equipTechParamRides.setRecDate(new Date());
            equipTechParamRides.setRunningSpeed(String.valueOf(equ.get("runningSpeed_DXYLSS")));
            equipTechParamRides.setSlideLength(String.valueOf(equ.get("slideLength_DXYLSS")));
            equipTechParamRides.setOperatingHeight(String.valueOf(equ.get("operatingHeight_DXYLSS")));
            iIdxBizJgTechParamsRidesService.saveOrUpdateData(equipTechParamRides);
        }
    }

    /**
     * 保存客运索道技术参数
     *
     * @param equ
     * @param record
     */
    private void saveRopewayParams(Map<?, ?> equ, String record) {
        IdxBizJgTechParamsRopeway equipTechParamRopeway = JSON.parseObject(JSON.toJSONString(equ), IdxBizJgTechParamsRopeway.class);
        if (!ValidationUtil.isEmpty(equipTechParamRopeway)) {
            equipTechParamRopeway.setRecord(record);
            equipTechParamRopeway.setRecDate(new Date());
            iIdxBizJgTechParamsRopewayService.saveOrUpdateData(equipTechParamRopeway);
        }
    }


    /**
     * 保存设备数据至es
     *
     * @param record 设备唯一编码
     */
    private void saveEquInfoToEs(String record) {
        Map<String, Object> map = categoryOtherInfoMapper.selectDataById(record);
        ESEquipmentCategoryDto equipmentCategoryDto = JSON.parseObject(toJSONString(map), ESEquipmentCategoryDto.class);
        if (!ObjectUtils.isEmpty(equipmentCategoryDto)) {
            long time = Timestamp.valueOf(map.get("REC_DATE").toString().substring(0, 19)).getTime();
            equipmentCategoryDto.setREC_DATE(time);
            esEquipmentCategory.save(equipmentCategoryDto);
        }
    }

}
