package com.xjrsoft.module.personnel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xjrsoft.module.hikvision.entity.HikvisionData;
import com.xjrsoft.module.hikvision.mapper.HikvisionDataMapper;
import com.xjrsoft.module.hikvision.util.ApiUtil;
import com.xjrsoft.module.personnel.entity.CarMessageApply;
import com.xjrsoft.module.personnel.mapper.CarMessageApplyMapper;
import com.xjrsoft.module.personnel.service.ICarMessageApplyService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @title: 车辆信息审核
* @Author dzx
* @Date: 2024-05-12
* @Version 1.0
*/
@Service
@AllArgsConstructor
public class CarMessageApplyServiceImpl extends MPJBaseServiceImpl<CarMessageApplyMapper, CarMessageApply> implements ICarMessageApplyService {

    private final HikvisionDataMapper hikvisionDataMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteBatchByIds(List<Long> ids) {
        List<HikvisionData> hikvisionData = hikvisionDataMapper.selectList(
                new QueryWrapper<HikvisionData>().lambda()
                        .in(HikvisionData::getSourceId, ids)
        );
        JsonObject paramJson = new JsonObject();
        JsonArray vehicleIds = new JsonArray();
        Map<String, String> idsMap = new HashMap<>();
        for (HikvisionData el : hikvisionData) {
            vehicleIds.add(el.getHikvisionId());
            idsMap.put(el.getHikvisionId(), el.getSourceId());
        }
        paramJson.add("vehicleIds", vehicleIds);

        ApiUtil apiUtil = new ApiUtil();
        String apiUrl = "/api/resource/v1/vehicle/batch/delete";
        String result = apiUtil.doPost(apiUrl, paramJson.toString(), null);

        JsonParser parser = new JsonParser();
        JsonObject resultJson = parser.parse(result).getAsJsonObject();
        if(resultJson.get("code").getAsInt() == 0 && !resultJson.get("data").isJsonNull()){
            JsonArray data = resultJson.get("data").getAsJsonArray();
            for (JsonElement datum : data) {
                JsonObject object = datum.getAsJsonObject();
                idsMap.remove(object.get("vehicleId").getAsString());
            }
            Collection<String> values = idsMap.values();
//            this.removeBatchByIds(values); 远程没有数据
        }
//        else{
            this.removeBatchByIds(ids);
//        }
        return true;
    }
}
