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.dto.UseFlagParamDto;
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.entity.JgUseRegistrationManage;
import com.yeejoin.amos.boot.module.jg.api.enums.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgRegistrationHistoryMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationEqMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationManageMapper;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgUseRegistrationMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgUseRegistrationManageService;
import com.yeejoin.amos.boot.module.jg.api.dto.JgUseRegistrationManageDto;
import com.yeejoin.amos.boot.module.ymt.api.entity.EquipmentCategory;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgFactoryInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgRegisterInfo;
import com.yeejoin.amos.boot.module.ymt.api.entity.IdxBizJgUseInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2024-07-03
 */
@Service
public class JgUseRegistrationManageServiceImpl extends BaseService<JgUseRegistrationManageDto, JgUseRegistrationManage, JgUseRegistrationManageMapper> implements IJgUseRegistrationManageService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    private JgUseRegistrationManageMapper jgUseRegistrationManageMapper;

    @Autowired
    private JgUseRegistrationMapper jgUseRegistrationMapper;

    @Autowired
    private JgUseRegistrationEqMapper jgUseRegistrationEqMapper;

    @Autowired
    private JgRegistrationHistoryMapper jgRegistrationHistoryMapper;

    @Autowired
    private CommonServiceImpl commonServiceImpl;

    @Autowired
    private IdxBizJgUseInfoServiceImpl idxBizJgUseInfoService;

    @Autowired
    private IdxBizJgRegisterInfoServiceImpl idxBizJgRegisterInfoService;

    @Autowired
    private IdxBizJgFactoryInfoServiceImpl idxBizJgFactoryInfoService;
    
    @Autowired
    private JgUseRegistrationServiceImpl jgUseRegistrationServiceImpl;

    /**
     * 将已经通过使用登记审批的证信息录入到 jg-use-registration-manage 表中
     */
    public Boolean brushHistoryCertificate() {
        this.baseMapper.delete(new LambdaQueryWrapper<>());
        // 使用登记表中已经审批通过的单子
        List<JgUseRegistration> jgUseRegistrations = jgUseRegistrationMapper.selectList(new LambdaQueryWrapper<JgUseRegistration>()
                .eq(JgUseRegistration::getStatus, "已完成"));
        for (JgUseRegistration useRegistration : jgUseRegistrations) {
            // 设备种类/类别/品种
            Map<String, String> equType = jgUseRegistrationMapper.getEquTypeByUseRegSeq(String.valueOf(useRegistration.getSequenceNbr()));
            // 组装数据
            JgUseRegistrationManage jgUseRegistrationManage = new JgUseRegistrationManage();
            jgUseRegistrationManage.setUseUnitName(useRegistration.getUseUnitName());
            jgUseRegistrationManage.setApplyNo(useRegistration.getApplyNo());
            jgUseRegistrationManage.setCertificateStatus("登记");
            jgUseRegistrationManage.setReceiveOrgName(useRegistration.getReceiveOrgName());
            jgUseRegistrationManage.setAuditPassDate(useRegistration.getAuditPassDate());
            jgUseRegistrationManage.setRegType(BusinessTypeEnum.JG_USAGE_REGISTRATION.getName());
            jgUseRegistrationManage.setRegDate(useRegistration.getRegDate());
            jgUseRegistrationManage.setEquList(equType.get("equList"));
            jgUseRegistrationManage.setEquCategory(equType.get("equCategory"));
            jgUseRegistrationManage.setEquDefine(equType.get("equDefine"));
            jgUseRegistrationManage.setIsDelete(Boolean.FALSE);
            jgUseRegistrationManage.setRecUserId(useRegistration.getRecUserId());
            jgUseRegistrationManage.setRecUserName(useRegistration.getRecUserName());
            jgUseRegistrationManage.setRecDate(useRegistration.getRecDate());
            jgUseRegistrationManage.setCreateUserId(useRegistration.getCreateUserId());
            jgUseRegistrationManage.setCreateDate(useRegistration.getCreateDate());
            jgUseRegistrationManage.setUseRegistrationCode(useRegistration.getUseRegistrationCode());
            jgUseRegistrationManage.setUseUnitCreditCode(useRegistration.getUseUnitCreditCode());
            jgUseRegistrationManage.setReceiveCompanyCode(useRegistration.getReceiveCompanyCode());
            jgUseRegistrationManage.setCertificateNo(commonServiceImpl.generateCertificateNo(equType,useRegistration.getAuditPassDate(),useRegistration.getReceiveCompanyCode()));
            // jgUseRegistrationManage.setUseRegistrationCertificateParam(this.buildUseRegistrationCertificateParam(useRegistration));
            // jgUseRegistrationManage.setUseFlagCertificateParam(this.buildUseFlagCertificateParam());
            this.baseMapper.insert(jgUseRegistrationManage);
        }
        // 车用气瓶使用登记表中已经审批通过的单子

        return Boolean.TRUE;
    }

    /**
     * 组装使用登记证参数
     */
    // private String buildUseRegistrationCertificateParam(JgUseRegistration useRegistration) {
    //     Map<String, Object> exportParamsMap = getStringObjectMap(useRegistration);
    //     return JSON.toJSONString(exportParamsMap);
    // }

    // private Map<String, Object> getStringObjectMap(JgUseRegistration useRegistration) {
    //     Map<String, Object> exportParamsMap = new HashMap<>();
    //     exportParamsMap.put("manageType", useRegistration.getManageType());
    //     LambdaQueryWrapper<JgUseRegistrationEq> useEqLambda = new QueryWrapper<JgUseRegistrationEq>().lambda();
    //     useEqLambda.eq(JgUseRegistrationEq::getEquipTransferId, useRegistration.getSequenceNbr());
    //     List<JgUseRegistrationEq> useRegistrationEqList = jgUseRegistrationEqMapper.selectList(useEqLambda);
    //
    //     if (ValidationUtil.isEmpty(useRegistration) || ValidationUtil.isEmpty(useRegistrationEqList)) {
    //         throw new BadRequest("使用登记证导出失败,请稍后重试!");
    //     }
    //     // 登记机关
    //     if (ValidationUtil.isEmpty(useRegistration.getReceiveOrgName())) {
    //         throw new BadRequest("使用登记证导出失败,登记机关为空!");
    //     }
    //     exportParamsMap.put("receiveOrgName", useRegistration.getReceiveOrgName());
    //     // 使用登记证编号
    //     if (ValidationUtil.isEmpty(useRegistration.getUseRegistrationCode())) {
    //         throw new BadRequest("使用登记证导出失败,使用登记证编号为空!");
    //     }
    //     exportParamsMap.put("useRegistrationCode", useRegistration.getUseRegistrationCode());
    //     // 使用单位名称
    //     if (ValidationUtil.isEmpty(useRegistration.getUseUnitName())) {
    //         throw new BadRequest("使用登记证导出失败,使用单位名称为空!");
    //     }
    //     exportParamsMap.put("useUnitName", useRegistration.getUseUnitName());
    //
    //     // 监管码
    //     if (ValidationUtil.isEmpty(useRegistration.getSupervisoryCode())) {
    //         throw new BadRequest("使用登记证导出失败,监管码为空!");
    //     }
    //     exportParamsMap.put("supervisoryCode", useRegistration.getSupervisoryCode());
    //
    //     JgUseRegistrationServiceImpl.getAuditPassedDate(useRegistration.getAuditPassDate(), exportParamsMap);
    //
    //     // 查询设备注册信息
    //     IdxBizJgRegisterInfo registerInfo = idxBizJgRegisterInfoService.getOne(new QueryWrapper<IdxBizJgRegisterInfo>().eq("RECORD", useRegistrationEqList.get(0).getEquId()));
    //     if (!ValidationUtil.isEmpty(registerInfo)) {
    //         // 设备种类、类别、品种
    //         String equList = registerInfo.getEquList();// 设备种类
    //         String equCategory = registerInfo.getEquCategory();// 设备类别
    //         String equDefine = registerInfo.getEquDefine();// 设备品种
    //         List<EquipmentCategory> categoryList0 = commonServiceImpl.getEquipmentCategoryList(equList, null);
    //         List<EquipmentCategory> categoryList1 = commonServiceImpl.getEquipmentCategoryList(equCategory, null);
    //         List<EquipmentCategory> categoryList2 = commonServiceImpl.getEquipmentCategoryList(equDefine, null);
    //         if (CollectionUtils.isNotEmpty(categoryList0)) {
    //             if (ValidationUtil.isEmpty(categoryList0.get(0).getName())) {
    //                 throw new BadRequest("使用登记证导出失败,设备种类为空!");
    //             }
    //             exportParamsMap.put("equList", categoryList0.get(0).getName());
    //         }
    //         if (CollectionUtils.isNotEmpty(categoryList1)) {
    //             if (ValidationUtil.isEmpty(categoryList1.get(0).getName())) {
    //                 throw new BadRequest("使用登记证导出失败,设备类别为空!");
    //             }
    //             exportParamsMap.put("equCategory", categoryList1.get(0).getName());
    //         }
    //         if (CollectionUtils.isNotEmpty(categoryList2)) {
    //             if (ValidationUtil.isEmpty(categoryList2.get(0).getName())) {
    //                 throw new BadRequest("使用登记证导出失败,设备品种为空!");
    //             }
    //             exportParamsMap.put("equDefine", categoryList2.get(0).getName());
    //         }
    //         // 设备代码
    //         if (ValidationUtil.isEmpty(registerInfo.getEquCode())) {
    //             throw new BadRequest("使用登记证导出失败,设备代码为空!");
    //         }
    //         exportParamsMap.put("equCode", registerInfo.getEquCode());
    //     }
    //
    //     IdxBizJgUseInfo useInfo = idxBizJgUseInfoService.getOneData(useRegistrationEqList.get(0).getEquId());
    //     if (!ValidationUtil.isEmpty(useInfo)) {
    //         if (ValidationUtil.isEmpty(useInfo.getUseInnerCode())) {
    //             throw new BadRequest("使用登记证导出失败,设备单位内部编码为空!");
    //         }
    //         // 单位内部编码
    //         exportParamsMap.put("useInnerCode", useInfo.getUseInnerCode());
    //         // 设备使用地址
    //         String fullAddress = "";
    //         if (!ObjectUtils.isEmpty(useInfo.getProvinceName())) {
    //             fullAddress += useInfo.getProvinceName();
    //         }
    //         if (!ObjectUtils.isEmpty(useInfo.getCityName())) {
    //             fullAddress += useInfo.getCityName();
    //         }
    //         if (!ObjectUtils.isEmpty(useInfo.getCountyName())) {
    //             fullAddress += useInfo.getCountyName();
    //         }
    //         if (!ObjectUtils.isEmpty(useInfo.getStreetName())) {
    //             fullAddress += useInfo.getStreetName();
    //         }
    //         if (!ObjectUtils.isEmpty(useInfo.getAddress())) {
    //             fullAddress += useInfo.getAddress();
    //         }
    //         if (ValidationUtil.isEmpty(fullAddress)) {
    //             throw new BadRequest("使用登记证导出失败,设备使用地址为空!");
    //         }
    //         exportParamsMap.put("fullAddress", fullAddress);
    //     }
    //     IdxBizJgFactoryInfo factoryInfo = idxBizJgFactoryInfoService.getOneData(useRegistrationEqList.get(0).getEquId());
    //     // 产品编号(出厂编号)
    //     if (!ValidationUtil.isEmpty(factoryInfo)) {
    //         if (ValidationUtil.isEmpty(factoryInfo.getFactoryNum())) {
    //             throw new BadRequest("使用登记证导出失败,产品编号为空!");
    //         }
    //         exportParamsMap.put("factoryNum", factoryInfo.getFactoryNum());
    //     }
    //     exportParamsMap.put("applyNo", useRegistration.getApplyNo());
    //     return exportParamsMap;
    // }

    /**
     * 组装使用标志参数
     */
    // private String buildUseFlagCertificateParam(JgUseRegistration useRegistration) {
    //     Map<String, Object> exportParamsMap = getStringObjectMap(useRegistration);
    //     UseFlagParamDto useFlagParamDto = new UseFlagParamDto();
    //     useFlagParamDto.setReceiveCompanyCode(useRegistration.getReceiveCompanyCode());
    //     useFlagParamDto.setEquList(exportParamsMap.get("equList").toString());
    //     useFlagParamDto.setEquListCode(registerInfo.getEquList());
    //     useFlagParamDto.setEquipCode(registerInfo.getEquCode());
    //     useFlagParamDto.setEquipCategory(exportParamsMap.get("equCategory").toString());
    //     useFlagParamDto.setEquipDefine(Optional.ofNullable(exportParamsMap.get("equDefine"))
    //             .orElse(exportParamsMap.get("equCategory").toString())
    //             .toString());
    //     useFlagParamDto.setUseUnitName(exportParamsMap.get("useUnitName").toString());
    //     useFlagParamDto.setUseInnerCode(exportParamsMap.get("useInnerCode").toString());
    //     useFlagParamDto.setReceiveOrgName(useRegistration.getReceiveOrgName());
    //     useFlagParamDto.setUseRegistrationCode(exportParamsMap.get("useRegistrationCode").toString());
    //     useFlagParamDto.setFactoryNumber(factoryInfo.getFactoryNum());
    //     useFlagParamDto.setCarNumber(registerInfo.getCarNumber());
    //     useFlagParamDto.setApplyNo(useRegistration.getApplyNo());
    //     // 检验信息字段设置
    //     jgUseRegistrationServiceImpl.setInspectField(registerInfo, useFlagParamDto);
    //     // 电梯维保信息字段设置
    //     jgUseRegistrationServiceImpl.setMainInfoField(registerInfo, useFlagParamDto);
    //     // 车用气瓶专用字段 暂无数据源 需车用气瓶功能开发完成后进行
    //     useFlagParamDto.setCylinderNumOrVolume("");
    //     useFlagParamDto.setFillingMedium("");
    //     return JSON.toJSONString(useFlagParamDto);
    // }

    /**
     * 分页查询
     */
    public Page<JgUseRegistrationManageDto> queryForJgUseRegistrationManagePage(Page<JgUseRegistrationManageDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询
     */
    public List<JgUseRegistrationManageDto> queryByUseUnitCreditCode(JgUseRegistrationManageDto dto) {
        return jgUseRegistrationManageMapper.queryByUseUnitCreditCode(dto);
    }

    /**
     * 根据证的sequenceNbr 查询证下面的所有设备
     */
    public List<JSONObject> queryEquByCertificateSeq(Long sequenceNbr) {
        JgUseRegistrationManage jgUseRegistrationManage = this.baseMapper.selectOne(new LambdaQueryWrapper<JgUseRegistrationManage>()
                .eq(JgUseRegistrationManage::getSequenceNbr, sequenceNbr)
                .eq(JgUseRegistrationManage::getIsDelete, 0));
        if (ValidationUtil.isEmpty(jgUseRegistrationManage) || ValidationUtil.isEmpty(jgUseRegistrationManage.getApplyNo())){
            return new ArrayList<>();
        }
        JgUseRegistration useRegistration = jgUseRegistrationMapper.selectOne(new LambdaQueryWrapper<JgUseRegistration>()
                .eq(JgUseRegistration::getApplyNo, jgUseRegistrationManage.getApplyNo()));
        // es中通过查询【使用登记证编号】所有设备
        SearchRequest request = new SearchRequest();
        request.indices("idx_biz_view_jg_all");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        builder.query(boolMust);
        BoolQueryBuilder pBuilder = QueryBuilders.boolQuery();
        pBuilder.must(QueryBuilders.termQuery("USE_ORG_CODE", useRegistration.getUseRegistrationCode()));
        boolMust.must(pBuilder);
        request.source(builder);
        List<JSONObject> result = new ArrayList<>();
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits()) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject dto2 = jsonObject.getJSONObject("sourceAsMap");
                result.add(dto2);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}