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.Unit;
import com.ruoyi.tc.entity.UnitOtherConcat;
import com.ruoyi.tc.regular.entity.UnitArchives;
import com.ruoyi.tc.regular.entity.UnitConcat;
import com.ruoyi.tc.service.UnitOtherConcatService;
import com.ruoyi.tc.service.UnitService;
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.List;
import java.util.Map;

/**
 * 单位对接定时任务
 *
 * @author du
 * @since 2024/12/3 10:59
 */
@Configuration
@EnableScheduling
public class UnitChange {

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

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

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

    @Resource
    private UnitService unitService;

    @Resource
    private UnitOtherConcatService unitOtherConcatService;

    /**
     * 定时更新单位档案信息
     */
    @Scheduled(cron = "0 0 2 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void unitTotal() {
        if (isTime) {
            Map<String, Object> params = new HashMap<>();
            params.put("sign", "D46D877537EA76E1D4EDC8DF5C95F040");
            params.put("resourceName", "org_dm_dwdaxxb");
            params.put("userName", "wxb_tc");
            params.put("subResourceName", "wxb001");
            params.put("offset", "1");
            HttpResponse response = HttpRequest.post(unitDocking + "?" + 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并转换为整数
                    changeUnit(arr);
                    if (total / 1000 > 1) {
                        for (int i = 1; i < (total / 1000) + 1; i++) {
                            unitFor(1 + 1000 * i);
                        }
                    }
                }
            }
        }
    }

    /**
     * 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 unitFor(Integer offset) {
        Map<String, Object> params = new HashMap<>();
        params.put("sign", "D46D877537EA76E1D4EDC8DF5C95F040");
        params.put("resourceName", "org_dm_dwdaxxb");
        params.put("userName", "wxb_tc");
        params.put("subResourceName", "wxb001");
        params.put("offset", offset);
        HttpResponse response = HttpRequest.post(unitDocking + "?" + 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"); // 直接获取数组，无需再次解析
                changeUnit(arr);
            }
        }
    }

    /**
     * 解析单位数据
     */
    public void changeUnit(JSONArray arr) {
        //解析数据
        for (Object o : arr) {
            JSONConfig jsonConfig = new JSONConfig();
            jsonConfig.setIgnoreCase(true);
            UnitArchives res = JSONUtil.toBean(o.toString(), jsonConfig, UnitArchives.class);
            Unit one = unitService.lambdaQuery().eq(Unit::getNickName, res.getDwmc())
                    .eq(Unit::getUserName, res.getTyshxydm()).one();
            //需要新增或者修改的单位
            Unit djUnit = new Unit();
            BeanUtil.copyProperties(res, djUnit, "id");
            djUnit.setUserName(res.getTyshxydm());
            djUnit.setNickName(res.getDwmc());
            djUnit.setGjdw(res.getSfgjdw());
            djUnit.setGw(res.getWz());
            djUnit.setDtjd(res.getJd());
            djUnit.setDtwd(res.getWd());
            if (one != null) {
                //修改
                if (one.getUpdateTime() != null && res.getUpdatetime() != null) {
                    if (!getDateBoolean(one.getUpdateTime(), res.getUpdatetime())) {
                        djUnit.setId(one.getId());
                        unitService.updateById(djUnit);
                    }
                } else {
                    djUnit.setId(one.getId());
                    unitService.updateById(djUnit);
                }
                updateUnitConcat(one.getId(), res.getId());
            } else {
                //添加
                unitService.save(djUnit);
                unitService.validUser(djUnit);
                updateUnitConcat(djUnit.getId(), res.getId());
            }

        }
    }

    /**
     * 修改单位的联系人
     */
    public void updateUnitConcat(Long id1, String id2) {
        //我们单位联系人
        List<UnitOtherConcat> list = unitOtherConcatService.lambdaQuery().eq(UnitOtherConcat::getUnitId, id1).list();
        //对接联系人
        Map<String, Object> params = new HashMap<>();
        params.put("sign", "DB84C68B1B6D3E2E937E97406394EB7C");
        params.put("resourceName", "org_dm_dwlxrb");
        params.put("userName", "wxb_tc");
        params.put("subResourceName", "wxb001");
        JSONObject jo = new JSONObject();//存放参数
        jo.set("dwid", id2);
        HttpResponse response = HttpRequest.post(unitDockingContact + "?" + 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"); // 直接获取数组，无需再次解析
                for (Object o : arr) {
                    JSONConfig jsonConfig = new JSONConfig();
                    jsonConfig.setIgnoreCase(true);
                    UnitConcat res = JSONUtil.toBean(o.toString(), jsonConfig, UnitConcat.class);
                    UnitOtherConcat uc = new UnitOtherConcat();
                    uc.setUnitId(id1);
                    uc.setQtlxrxm(res.getXm());
                    uc.setQtlxrlxfs(res.getLxfs());
                    uc.setQtlxrzwzc(res.getZwzc());
                    if (list != null && !list.isEmpty()) {
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getQtlxrxm().equals(res.getXm())) {
                                if (list.get(i).getUpdateTime() != null && res.getUpdatetime() != null) {
                                    if (!getDateBoolean(list.get(i).getUpdateTime(), res.getUpdatetime())) {
                                        uc.setConcatId(list.get(i).getConcatId());
                                        unitOtherConcatService.updateById(list.get(i));
                                    }
                                } else {
                                    uc.setConcatId(list.get(i).getConcatId());
                                    unitOtherConcatService.updateById(list.get(i));
                                }
                            } else {
                                if (i == list.size() - 1 && !list.get(i).getQtlxrxm().equals(res.getXm())) {
                                    unitOtherConcatService.save(uc);
                                }
                            }
                        }
                    } else {
                        unitOtherConcatService.save(uc);
                    }
                }
            }
        }
    }

    /**
     * 判断两个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;
    }

}
