package com.zksy.data.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.data.annotation.XhDataLogRecord;
import com.zksy.data.domain.po.XcrEnterprisePollutionPermitInfo;
import com.zksy.data.domain.response.XcrEnterprisePollutionPermitInfoResponse;
import com.zksy.data.service.XcrEnterprisePollutionPermitInfoService;
import com.zksy.data.mapper.XcrEnterprisePollutionPermitInfoMapper;
import com.zksy.data.utils.RedisService;
import com.zksy.data.utils.XhRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * @author 邵洋
 * @description 针对表【xcr_enterprise_pollution_permit_info(企业排污许可信息表)】的数据库操作Service实现
 * @createDate 2024-10-25 10:12:46
 */
@Service
@Slf4j
public class XcrEnterprisePollutionPermitInfoServiceImpl extends ServiceImpl<XcrEnterprisePollutionPermitInfoMapper, XcrEnterprisePollutionPermitInfo>
        implements XcrEnterprisePollutionPermitInfoService {
    @Autowired
    private XhRequestUtil xhRequestUtil;
    @Autowired
    private RedisService redisService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @XhDataLogRecord("同步企业排污许可信息")
    public void saveDataByUniCode(String address) {
        //模拟从数据库中取数据大约为3000-4000条
        List<String> creditCodes = (List<String>) redisService.getList("creditCodes").get(0);
        Vector<XcrEnterprisePollutionPermitInfo> toDatabaseList = new Vector<>();
        creditCodes.parallelStream().forEach(creditCode -> {
            List<XcrEnterprisePollutionPermitInfo> list = xhRequestUtil.httpRequestByUniCode(creditCode, address,
                    XcrEnterprisePollutionPermitInfoResponse.class,
                    XcrEnterprisePollutionPermitInfo.class,
                    "SHXYDM"
            );
            if (list != null) {
                toDatabaseList.addAll(list);
            }
        });
        // 定义多种日期格式
        String[] datePatterns = {
                "dd-MMM-yy", // 09-DEC-21
                "dd-MMM-yy HH.mm.ss.SSSSSSSSS a", // 09-7月 -20 12.00.00.000000000 上午
                "yyyy/MM/dd HH:mm:ss.SSS", // 2020/04/16 00:00:00.000
                "yyyy-MM-dd",
                "yyyy.MM.dd",
                "MM-MMMM -yy hh.mm.ss.SSSSSSSSS a"
        };
        List<XcrEnterprisePollutionPermitInfo> enterprisePollutionPermitInfoList = toDatabaseList.stream().map(q -> {
            Date date = parseDate(q.getXKZFFSJ(), datePatterns);
            q.setA(formatDate(date));
            return q;
        }).collect(Collectors.toList());
        this.remove(null);
        this.saveBatch(enterprisePollutionPermitInfoList);
        log.info("企业排污许可信息同步完成");
    }

    // 尝试多种日期格式进行解析
    private Date parseDate(String dateString, String[] patterns) {
        if (dateString == null || dateString.trim().isEmpty()) {
            log.warn("日期字符串为空或空白: {}", dateString);
            return null; // 或者返回一个默认日期
        }
        for (String pattern : patterns) {
            try {
                // 使用正确的 Locale
                Locale locale = pattern.contains("a") ? Locale.CHINA : Locale.US;
                SimpleDateFormat inputFormat = new SimpleDateFormat(pattern, locale);
                return inputFormat.parse(dateString);
            } catch (ParseException e) {
                // 继续尝试下一个格式
            }
        }
        throw new IllegalArgumentException("无法识别的日期格式: " + dateString);
    }

    private Date formatDate(Date date) {
        if (date == null) {
            return null; // 或者返回一个默认值
        }
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        String formattedDateStr = outputFormat.format(date);
        try {
            return outputFormat.parse(formattedDateStr);
        } catch (ParseException e) {
            throw new RuntimeException("日期格式化失败", e);
        }
    }
}




