package com.project.zcustom.tools;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.project.common.utils.StringUtils;
import com.project.common.utils.http.HttpUtils;
import com.project.zcustom.domain.addional.LargeAssetDirs;
import com.project.zcustom.domain.addional.LargeLogistics;
import com.project.zcustom.domain.basics.PlatAppOrg;
import com.project.zcustom.domain.plat.AssetMonitoringResponse;
import com.project.zcustom.domain.plat.PlatApiRecord;
import com.project.zcustom.mapper.logistics.PlatAssetMapper;
import com.project.zcustom.service.plat.IPlatApiRecordService;
import com.project.zcustom.service.service.basics.IPlatAppOrgService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 后勤资源监控服务
 * @Author bqyang
 * @Date 2025/2/10 17:23
 * @Version 1.0
 */
@Service
public class LogisticsService {

    @Autowired
    private PlatAssetMapper platAssetMapper;
    @Autowired
    private IPlatAppOrgService platAppOrgService;
    @Resource
    IPlatApiRecordService iPlatApiRecordService;


    public void getLogisticsData(){
        List<LargeLogistics> list = new ArrayList<>();
        List<LargeAssetDirs> officeAssetList = new ArrayList<>();
        List<LargeAssetDirs> buildingAssetList = new ArrayList<>();
        List<LargeAssetDirs> serviceAssetList = new ArrayList<>();
        String logistUrl = ApiUrlConfig.getLogisticsUrl();
        // 查询所有组织信息
        List<PlatAppOrg> orgList = platAppOrgService.selectAppCodeList();
        Map<String, String> orgMap = orgList.stream().collect(Collectors.toMap(PlatAppOrg::getAppCode, PlatAppOrg::getAppName, (v1, v2) -> v1));

        int current = 1;
        this.postLoginRequest(current, logistUrl, orgMap, list, officeAssetList, buildingAssetList, serviceAssetList);

        this.batchSaveData(list, officeAssetList, buildingAssetList, serviceAssetList);
    }

    private void postLoginRequest(int current,String logistUrl,Map<String, String> orgMap,List<LargeLogistics> list,List<LargeAssetDirs> officeAssetList,List<LargeAssetDirs> buildingAssetList,List<LargeAssetDirs> serviceAssetList){
        // 分页查询页数
        JSONObject jsonObject = this.repeat(logistUrl, current);

        if (Objects.isNull(jsonObject)) {
            return;
        }
        AssetMonitoringResponse request = jsonObject.getJSONObject("data").getJSONObject("quotaAssetMonitoringList").toJavaObject(AssetMonitoringResponse.class);

        this.saveLogisticsData(jsonObject, orgMap, list, officeAssetList, buildingAssetList, serviceAssetList);

        current ++;
        if (current <= request.getPages()) {
            this.postLoginRequest(current, logistUrl, orgMap, list, officeAssetList, buildingAssetList, serviceAssetList);
        }
    }

    private void batchSaveData(List<LargeLogistics> list, List<LargeAssetDirs> officeAssetList,
                               List<LargeAssetDirs> buildingAssetList,List<LargeAssetDirs> serviceAssetList){
        platAssetMapper.deleteLogistics();
        platAssetMapper.insertLargePlatLogistics(list);
        platAssetMapper.deleteOfficeAssetDirs();
        platAssetMapper.insertOfficeAssetDirs(officeAssetList);
        platAssetMapper.deleteBuildingAssetDirs();
        platAssetMapper.insertBuildingAssetDirs(buildingAssetList);
        platAssetMapper.deleteServiceAssetDirs();
        platAssetMapper.insertServiceAssetDirs(serviceAssetList);
    }


    /**
     *  数据处理
     * @param jsonObject
     * @param orgMap
     * @param list
     * @param officeAssetList
     * @param buildingAssetList
     * @param serviceAssetList
     */
    private void saveLogisticsData(JSONObject jsonObject, Map<String, String> orgMap, List<LargeLogistics> list, List<LargeAssetDirs> officeAssetList,
                                   List<LargeAssetDirs> buildingAssetList,List<LargeAssetDirs> serviceAssetList){
        JSONArray dataArray = jsonObject.getJSONObject("data").getJSONObject("quotaAssetMonitoringList").getJSONArray("records");

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject dataItem = dataArray.getJSONObject(i);
            LargeLogistics largeLogistics = JSON.parseObject(dataItem.toString(), LargeLogistics.class);
            // 业务方提供的数据包含一些不需要的部门数据进行过滤
            if ( !orgMap.containsKey(largeLogistics.getOrgId())){
                continue;
            }

            // 资产列表数据提取
            List<LargeAssetDirs> officeList = getAssetList(dataItem, largeLogistics.getOrgId(), "officeAssetDistrs");
            officeAssetList.addAll(officeList);

            List<LargeAssetDirs> buildingList = getAssetList(dataItem, largeLogistics.getOrgId(),"buildingAssetDistrs");
            buildingAssetList.addAll(buildingList);

            List<LargeAssetDirs> serviceList = getAssetList(dataItem, largeLogistics.getOrgId(), "serviceAssetDistrs");
            serviceAssetList.addAll(serviceList);

            list.add(largeLogistics);
        }
    }

    /**
     * officeAssetDistrs 办公资产分布列表
     * buildingAssetDistrs 楼宇设备分布列表
     * serviceAssetDistrs 服务设备分布列表
     * @param dataItem
     * @param appCode
     * @param jsonKey
     * @return
     */
    private List<LargeAssetDirs> getAssetList(JSONObject dataItem, String appCode, String jsonKey){
        List<LargeAssetDirs> list = Lists.newArrayList();
        try {
            JSONArray buildingAssetArray = dataItem.getJSONArray(jsonKey);
            for (int k = 0; k < buildingAssetArray.size(); k++) {
                LargeAssetDirs largeAssetDirs = new LargeAssetDirs();
                JSONObject assetItem = buildingAssetArray.getJSONObject(k);
                largeAssetDirs.setAppCode(appCode);
                largeAssetDirs.setCategoryName(assetItem.getString("categoryName"));
                largeAssetDirs.setAssetNum(assetItem.getLong("assetNum"));
                list.add(largeAssetDirs);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }


    private JSONObject repeat(String url, int current){
        Map<String, Object> map = new HashMap<>();
        map.put("current", current);
        map.put("size", 200);
        try {
            String res = HttpUtils.sendJsonPost(url, map);
            // 添加接口请求记录
            PlatApiRecord platApiRecord = new PlatApiRecord();
            platApiRecord.setApiUrl(url);
            platApiRecord.setApiResult(res);
            iPlatApiRecordService.save(platApiRecord);

            if (StringUtils.isNotBlank(res)){
                if (JSONObject.parseObject(res).getString("code").equals("200")){
                    return JSONObject.parseObject(res);
                }
            }
        }catch (Exception e){
            PlatApiRecord platApiRecord = new PlatApiRecord();
            platApiRecord.setApiUrl(url);
            platApiRecord.setApiResult(e.getMessage());
            iPlatApiRecordService.save(platApiRecord);
        }
        return null;
    }

}
