package com.ningdatech.carapi.irs.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.cache.redis.RedisOps;
import com.ningdatech.carapi.common.contants.IrsConst;
import com.ningdatech.carapi.driver.entity.DriverInfo;
import com.ningdatech.carapi.driver.service.IDriverInfoService;
import com.ningdatech.carapi.irs.entity.DriversLicenseRaw;
import com.ningdatech.carapi.irs.model.dto.irs.DrivingLicenseDTO;
import com.ningdatech.carapi.irs.model.dto.irs.ResponseDataDTO;
import com.ningdatech.carapi.irs.service.AbstractLicenseGetByIrsService;
import com.ningdatech.carapi.irs.service.IDriversLicenseRawService;
import com.ningdatech.carapi.irs.service.PullLicenseByIrsService;
import com.ningdatech.carapi.irs.service.RefreshKeyService;
import com.ningdatech.carapi.irs.utils.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * DriverLicensePullServiceImpl
 * </p>
 *
 * @author WendyYang
 * @since 2023/5/16
 **/
@Slf4j
@Service("drivingLicensePullByIrsService")
public class PullDrivingLicenseByIrsServiceImpl extends AbstractLicenseGetByIrsService implements PullLicenseByIrsService {


    public PullDrivingLicenseByIrsServiceImpl(IDriverInfoService driverInfoService,
                                              RestTemplate restTemplate,
                                              RefreshKeyService refreshKeyService,
                                              RedisOps redisOps,
                                              IDriversLicenseRawService driversLicenseRawService) {
        super(driverInfoService, restTemplate, refreshKeyService, redisOps, driversLicenseRawService);
    }

    @Override
    public boolean runningStatus() {
        String statusKey = RK_DRIVING_LICENSE + StrPool.COLON + "STATUS";
        return Boolean.TRUE.equals(redisOps.exists(statusKey));
    }

    @Override
    public long getLeftCount() {
        String dataKey = RK_DRIVING_LICENSE + StrPool.COLON + "IDCARD";
        return ObjectUtil.defaultIfNull(redisOps.lLen(dataKey), 0L);
    }

    /**
     * 获取行驶证信息
     *
     * @param idcard 身份正好
     * @return /
     */
    @Override
    public String getLicenseDetail(String idcard) {
        // 刷新密钥
        String requestSecret = refreshKeyService.getRequestSecret(APP_KEY, APP_SECRET);
        // 请求签名
        Long requestTime = System.currentTimeMillis();
        String sign = Md5Utils.hash(APP_KEY + requestSecret + requestTime);

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        // 附加信息
        map.add("additional", "{\"powerMatters\":\"许可0000-00\",\"subPowerMatters\":\"许可0000-0101\",\"accesscardId\":\"33071918******784523\",\"materialName\":\"社会团体变更登记申请表\",\"sponsorName\":\"阿里巴巴（中国）有限公司\",\"sponsorCode\":\"91330100799655058B\",\"projectId\":\"330000261711151100004\"}");
        map.add("appKey", APP_KEY);
        map.add("requestTime", requestTime);
        map.add("sign", sign);
        map.add("sfzmhm", idcard);
        String res;
        try {
            log.info("请求参数：{}", map);
            res = restTemplate.postForObject(IrsConst.DRIVING_LICENSE_URL, map, String.class);
            log.info("行驶证信息查询：{}", res);
        } catch (Exception e) {
            log.error("行驶证信息查询：", e);
            res = null;
        }
        return res;
    }

    @Override
    public void pullLicense() {
        String statusKey = RK_DRIVING_LICENSE + StrPool.COLON + "STATUS";
        try {
            if (Boolean.FALSE.equals(redisOps.setNx(statusKey, "RUNNING"))) {
                return;
            }
            pullLicenseDetail();
        } finally {
            redisOps.del(statusKey);
        }
    }

    @Override
    public void pullLicenseDetail() {
        String dataKey = RK_DRIVING_LICENSE + StrPool.COLON + "IDCARD";
        List<String> currIdcards = redisOps.lPop(dataKey);
        if (CollUtil.isEmpty(currIdcards)) {
            LambdaQueryWrapper<DriverInfo> query = Wrappers.lambdaQuery(DriverInfo.class)
                    .select(DriverInfo::getIdCard);
            List<DriverInfo> driverInfos = driverInfoService.list(query);
            Set<String> idCards = driverInfos.stream()
                    .map(DriverInfo::getIdCard)
                    .filter(IdcardUtil::isValidCard)
                    .collect(Collectors.toSet());
            if (idCards.isEmpty()) {
                return;
            }
            List<List<String>> parts = new ArrayList<>(ListUtil.partition(new ArrayList<>(idCards), LIMIT_BY_DAY));
            currIdcards = parts.remove(0);
            if (!parts.isEmpty()) {
                redisOps.lPush(dataKey, parts.toArray());
            }
        }
        List<Object> failedIdcards = currIdcards.stream().filter(idcard -> {
            try {
                String resData = getLicenseDetail(idcard);
                if (StrUtil.isBlank(resData)) {
                    return true;
                }
                ResponseDataDTO<DrivingLicenseDTO> response = JSON.parseObject(resData,
                        new TypeReference<ResponseDataDTO<DrivingLicenseDTO>>() {
                        });
                if (response.succeed()) {
                    List<DrivingLicenseDTO> list = response.getDatas();
                    if (CollUtil.isNotEmpty(list)) {
                        DrivingLicenseDTO dl = list.get(0);
                        DriversLicenseRaw raw = new DriversLicenseRaw();
                        raw.setIdcard(idcard);
                        raw.setDrivingLicenseDetail(JSONUtil.toJsonStr(dl));
                        LambdaQueryWrapper<DriversLicenseRaw> query = Wrappers
                                .lambdaQuery(DriversLicenseRaw.class)
                                .eq(DriversLicenseRaw::getIdcard, idcard);
                        driversLicenseRawService.saveOrUpdate(raw, query);
                        return false;
                    }
                }
                return true;
            } catch (Exception e) {
                log.error("获取行驶证信息异常：", e);
                return true;
            }
        }).collect(Collectors.toList());
        if (!failedIdcards.isEmpty()) {
            redisOps.lPush(dataKey, failedIdcards.toArray());
        }
    }

    @Override
    public void initPullLicenseTask() {
        long leftCnt = getLeftCount();
        boolean runningStatus = runningStatus();
        if (runningStatus || leftCnt > 0) {
            startPullLicenseTask(INIT_DELAY_MINUTES);
        }
    }

    @Override
    public void startPullLicenseTask(int delayMinutes) {
        startLicensePullTask(RK_DRIVING_LICENSE, this, delayMinutes);
    }

}
