package com.ruoyi.tc.regular;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.tc.entity.AssetCurrent;
import com.ruoyi.tc.regular.entity.AssetDbxx;
import com.ruoyi.tc.regular.entity.AssetJcxx;
import com.ruoyi.tc.service.AssetCurrentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统定时任务
 *
 * @author du
 * @since 2024/12/3 17:06
 */
@Configuration
@EnableScheduling
public class AssetCurrentChange {

    @Value("${isTime}")
    private Boolean isTime;

    @Value("${systemInfo}")
    private String systemInfo;

    @Value("${systemDb}")
    private String systemDb;

    @Resource
    private AssetCurrentService assetCurrentService;

    /**
     * 定时更新系统基础信息
     */
    @Scheduled(cron = "0 0 3 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void assetTotal() {
        if (isTime) {
            Map<String, Object> params = new HashMap<>();
            params.put("sign", "1BAE256B66FE09BFCFC3436930C2C986");
            params.put("resourceName", "org_dm_xtxgxxb");
            params.put("userName", "wxb_tc");
            params.put("subResourceName", "wxb001");
            params.put("offset", "1");
            HttpResponse response = HttpRequest.post(systemInfo + "?" + urlEdit(params))
                    .header("Content-Type", "application/json;charset=utf-8")
                    .formStr(new HashMap<>())
                    .execute();
            if (response.getStatus() == 200) {
                JSONObject jsonObj = JSONUtil.parseObj(response.body());
                if ("200".equals(jsonObj.get("code").toString())) {
                    JSONObject reqData = JSONUtil.parseObj(jsonObj.get("data"));
                    JSONArray arr = reqData.getJSONArray("result"); // 直接获取数组，无需再次解析
                    int total = reqData.getInt("total"); // 只需解析一次total并转换为整数
                    changeAsset(arr);
                    if (total / 1000 > 1) {
                        for (int i = 1; i < (total / 1000) + 1; i++) {
                            assetFor(1 + 1000 * i);
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据页数进行系统基础信息下次循环
     */
    public void assetFor(Integer offset) {
        Map<String, Object> params = new HashMap<>();
        params.put("sign", "1BAE256B66FE09BFCFC3436930C2C986");
        params.put("resourceName", "org_dm_xtxgxxb");
        params.put("userName", "wxb_tc");
        params.put("subResourceName", "wxb001");
        params.put("offset", offset);
        HttpResponse response = HttpRequest.post(systemInfo + "?" + urlEdit(params))
                .header("Content-Type", "application/json;charset=utf-8")
                .formStr(new HashMap<>())
                .execute();
        if (response.getStatus() == 200) {
            JSONObject jsonObj = JSONUtil.parseObj(response.body());
            if ("200".equals(jsonObj.get("code").toString())) {
                JSONObject reqData = JSONUtil.parseObj(jsonObj.get("data"));
                JSONArray arr = reqData.getJSONArray("result"); // 直接获取数组，无需再次解析
                changeAsset(arr);
            }
        }
    }

    /**
     * url地址修改
     */
    public String urlEdit(Map<String, Object> params) {
        StringBuilder queryParamBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            if (queryParamBuilder.length() > 0) {
                queryParamBuilder.append("&");
            }
            queryParamBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return queryParamBuilder.toString();
    }


    /**
     * 解析系统基础信息数据
     */
    public void changeAsset(JSONArray arr) {
        //解析数据
        for (Object o : arr) {
            JSONConfig jsonConfig = new JSONConfig();
            jsonConfig.setIgnoreCase(true);
            AssetJcxx res = JSONUtil.toBean(o.toString(),jsonConfig, AssetJcxx.class);
            //根据现有资产表单位名称和系统名称查询对应的数据
            AssetCurrent one = assetCurrentService.lambdaQuery()
                    .eq(AssetCurrent::getDwmc, res.getBmmc())
                    .eq(AssetCurrent::getXtmc, res.getXtmc()).one();
            //准备要新增或者修改的数据
            AssetCurrent na = new AssetCurrent();
            BeanUtil.copyProperties(res, na, "id");
            na.setDwmc(res.getBmmc());
            na.setXtym(res.getYm());
            na.setGjxt(res.getSfgjxt());
            na.setDgzkf(res.getSfdgzkf());
            //查询对接的系统基础信息对应的系统等保信息
            AssetDbxx assetDbxx = searchDbxx(res.getId());
            if (assetDbxx != null) {
                na.setDbxxDjsj(assetDbxx.getDjsj());
                na.setDbxxDbdj(assetDbxx.getDbjb());
                na.setDbxxDbcpbah(assetDbxx.getDbcpbah());
                na.setDbxxDbcpbah(assetDbxx.getDbcpbah());
                na.setDbxxCpdf(assetDbxx.getDbcpdf());
                na.setMpSfmpxt(assetDbxx.getSfmmcp());
                na.setMpMpdf(assetDbxx.getMpdf());
                na.setIpcSfba(assetDbxx.getIcpsfba());
                na.setIpcSfba(assetDbxx.getIcpsfba());
                na.setIpcIpcbabh(assetDbxx.getIcpbabh());
                na.setIpcIpcbabh(assetDbxx.getIcpbabh());
                na.setGajgSfba(assetDbxx.getSfgaba());
                na.setGajgBajg(assetDbxx.getBajg());
                na.setGajgBah(assetDbxx.getGajgbah());
                na.setGajgBah(assetDbxx.getGajgbah());
                na.setGajgBarq(assetDbxx.getBarq());
            }
            if (one != null) {
                //修改
                if (one.getUpdateTime() != null && res.getUpdatetime() != null) {
                    if (!getDateBoolean(one.getUpdateTime(), res.getUpdatetime())) {
                        na.setId(one.getId());
                        assetCurrentService.updateById(na);
                    }
                } else {
                    na.setId(one.getId());
                    assetCurrentService.updateById(na);
                }
            } else {
                assetCurrentService.save(na);
            }
        }
    }

    /**
     * 根据系统档案的id获取对应的系统等保信息
     */
    public AssetDbxx searchDbxx(String xtid) {
        Map<String, Object> params = new HashMap<>();
        params.put("sign", "9D0DBC61467D4C2D2087266DF4CA7BCF");
        params.put("resourceName", "org_dm_xtdbxxb");
        params.put("userName", "wxb_tc");
        params.put("subResourceName", "wxb001");
        JSONObject jo = new JSONObject();//存放参数
        jo.set("xtid", xtid);
        HttpResponse response = HttpRequest.post(systemDb + "?" + urlEdit(params))
                .header("Content-Type", "application/json;charset=utf-8")
                .formStr(new HashMap<>())
                .body(jo.toString())
                .execute();
        if (response.getStatus() == 200) {
            JSONObject jsonObj = JSONUtil.parseObj(response.body());
            if ("200".equals(jsonObj.get("code").toString())) {
                JSONArray arr = jsonObj.getJSONArray("data"); // 直接获取数组，无需再次解析
                if (arr.size() > 0) {
                    JSONConfig jsonConfig = new JSONConfig();
                    jsonConfig.setIgnoreCase(true);
                    return JSONUtil.toBean(arr.get(0).toString(),jsonConfig, AssetDbxx.class);
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 判断两个LocalDateTime哪个离现在时间最近
     */
    public Boolean getDateBoolean(Date a, Date b) {
        long diff1 = Math.abs(System.currentTimeMillis() - a.getTime());
        long diff2 = Math.abs(System.currentTimeMillis() - b.getTime());
        if (diff1 < diff2) {
            return true;
        } else if (diff1 > diff2) {
            return false;
        }
        return false;
    }

}
