package com.chinaweal.aiccs.aiccs.claim.service.impl;

import com.chinaweal.aiccs.aiccs.claim.entity.SolrExGongan128Xdzkdy;
import com.chinaweal.aiccs.aiccs.claim.repository.SolrExGongan128XdzkdyRepository;
import com.chinaweal.aiccs.common.util.CsvReaderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * solr（六）新地址库-单元房屋，服务类
 */
@Slf4j
@Service
public class SolrExGongan128XdzkdyServiceImpl {

    @Autowired
    private SolrExGongan128XdzkdyRepository solrExGongan128XdzkdyRepository;

    public static void main(String[] args) throws IOException {
        SolrExGongan128XdzkdyServiceImpl t = new SolrExGongan128XdzkdyServiceImpl();
//        t.csvToSolr("D:\\desktop\\128_202507161355\\128_202507161355.csv");
        String key = t.extractStreet("广州市增城区新塘镇光华路19号2513号A202");
        String skey = key.substring(0, key.length() / 2);
        System.out.println(key);
        System.out.println(skey);
    }


    /**
     * 通过csv导入数据，初始化使用
     */
    public int csvToSolr(String csvPath) throws IOException {
        AtomicInteger i = new AtomicInteger();
        //读取csv
        CsvReaderUtil.readCsv(
                csvPath,
                true, // 跳过表头
                ',', // 分隔符为逗号
                ((String[] fields) -> {// 自定义映射函数
                    //"S_GUID","YYWXTDZBM","SSSSXQ","SSXZJD","SSSQCJ_DM","DZMC","GZDB_ADDTIME"
                    SolrExGongan128Xdzkdy entity = new SolrExGongan128Xdzkdy();
                    entity.setSGuid(fields[0].replaceAll("\"", ""));
                    entity.setYywxtdzbm(fields[1].replaceAll("\"", ""));
                    entity.setSsssxq(fields[2].replaceAll("\"", ""));
                    entity.setSsxzjd(fields[3].replaceAll("\"", ""));
                    entity.setSssqcjDm(fields[4].replaceAll("\"", ""));
                    entity.setDzmc(fields[5].replaceAll("\"", ""));
                    try {
                        if (fields.length == 7) {
                            entity.setGzdbAddtime(LocalDateTime.parse(fields[6], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
                        } else {
                            entity.setDzmc(entity.getDzmc() + fields[6]);
                            entity.setGzdbAddtime(LocalDateTime.parse(fields[7], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
                        }
                    } catch (Exception e) {
                        log.error(fields[6]);
                        log.error(fields[7]);
                        log.error("转换时间出错！", e);
                    }
                    return entity;
                }),
                100000,//每批处理 100000 条
                ((List<SolrExGongan128Xdzkdy> list) -> {// 批量保存
                    solrExGongan128XdzkdyRepository.saveAll(list);
                    i.addAndGet(list.size());
                }
                ), "UTF-8"
        );
        return i.get();
    }

    /**
     * 通过地址名，查询四标四实的数据记录
     * @param dom
     * @return
     */
    public SolrExGongan128Xdzkdy getTop1AddressMatchingDegree(String dom) {
        try {
            String key = extractStreet(dom);
            String skey = key.substring(0, key.length() / 2);
            Pageable pageable = PageRequest.of(0, 20); // 明确设置rows=20
            List<SolrExGongan128Xdzkdy> solrExGongan128Xdzkdies = solrExGongan128XdzkdyRepository.fuzzySearchAddress(key, skey, pageable);
            if (!solrExGongan128Xdzkdies.isEmpty()) {
                return solrExGongan128Xdzkdies.get(0);
            }
        } catch (Exception e) {
            log.error("通过地址名，查询四标四实的数据记录失败", e);
        }
        return null;
    }

    public String extractStreet(String address) {
        int districtIndex = address.indexOf("区");
        int cityIndex = address.indexOf("市");
        int provinceIndex = address.indexOf("省");

        // 直接去掉后面的数字开始的字符，就是去掉多少号多少室等。
        address = address.replaceAll("\\d+.*", "");

        int startIndex = Math.max(Math.max(districtIndex, cityIndex), provinceIndex);
        if (startIndex == -1) return address;

        return address.substring(startIndex + 1);
    }

    /**
     * 去除通用的字符
     * @param fullAddress
     * @return
     */
    private String extractNgramPart(String fullAddress) {
        // 实现提取地址关键词的逻辑，例如：
        return fullAddress.replaceAll("(区|街道|路|号|巷)", "");
    }
}
