package com.saye.hospitalgd.scheduler.jobMethod;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.commons.getBean.GetBeanUtil;
import com.saye.hospitalgd.commons.log.LogUtil;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.entity.BankbillHistory;
import com.saye.hospitalgd.service.BankbillGetinfoService;
import com.saye.hospitalgd.service.BankbillHistoryService;
import com.saye.hospitalgd.service.impl.BankbillGetinfoServiceImpl;
import com.saye.hospitalgd.service.impl.BankbillHistoryServiceImpl;
import com.saye.hospitalgd.service.system.ServiceParamsService;
import com.saye.hospitalgd.service.system.impl.ServiceParamsServiceImpl;
import com.saye.hospitalgd.util.HttpDutil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;

/**
 * 银行医保账单获取（通过中转服务）
 * 
 * @author Mr.zs
 * @date 2025/11/17
 */
@Slf4j
public class BankGetDataByMedicalInsuranceAPI {

    public HashMap<Object, Object> getDate(String id, String name, String trade_date, HashMap<Object, Object> map) {

        HashMap<Object, Object> resultMap = new HashMap<>();
        String errCode = "0";
        String errMsg = "";

        BankbillHistoryService bankbillHistoryService = GetBeanUtil.getBean(BankbillHistoryServiceImpl.class);
        BankbillGetinfoService bankbillGetinfoService = GetBeanUtil.getBean(BankbillGetinfoServiceImpl.class);
        ServiceParamsService serviceParamsService = GetBeanUtil.getBean(ServiceParamsServiceImpl.class);

        boolean isOk = false;

        int num = "".equals(trade_date) ? 0 : 9;
        while (!isOk && num < 10) {
            num++;

            String bill_table_name = StringDUtil.changeNullToEmpty(map.get("BILL_TABLE_NAME"));
            String thirdConfigId = StringDUtil.changeNullToEmpty(map.get("ID"));
            String dateStr = "";

            if (StrUtil.isNotBlank(trade_date)) {
                DateTime parse = DateUtil.parse(trade_date);
                dateStr = DateUtil.format(parse, "yyyyMMdd");
            } else {
                DateTime yesterday = DateUtil.yesterday();
                dateStr = DateUtil.format(yesterday, "yyyyMMdd");
                trade_date = DateUtil.format(yesterday, "yyyy-MM-dd");
            }
            map.put("trade_date", dateStr);

            try {
                List<HashMap<Object, Object>> serviceParams = serviceParamsService.findParamValByParamCode("hgd_dmz");
                String dmz_url = StringDUtil.changeNullToEmpty(serviceParams.get(0).get("PARAM_VAL"));

                log.info("开始调用中转服务获取银行医保账单，URL: {}", dmz_url + "/getBankDataByMedicalInsuranceAPI");
                String result = HttpDutil.post(dmz_url + "/getBankDataByMedicalInsuranceAPI", map);

                JSONObject jsonObject = JSONObject.parseObject(result);

                errCode = StringDUtil.changeNullToEmpty(jsonObject.get("errCode"));
                errMsg = StringDUtil.changeNullToEmpty(jsonObject.get("errMsg"));

                if ("0".equals(errCode)) {
                    String listStr = StringDUtil.changeNullToEmpty(jsonObject.get("list"));
                    log.info("微信医保账单获取成功，返回数据: {}", listStr);
                    List<BankbillHistory> bankbillHistories = JSONArray.parseArray(listStr, BankbillHistory.class);

                    if (bankbillHistories != null && !bankbillHistories.isEmpty()) {
                        bankbillHistoryService.insertBankBillOriginal(bankbillHistories, trade_date, bill_table_name);
                        bankbillHistoryService.insertAllBankHistory(bankbillHistories, trade_date, bill_table_name);
                    }
                    isOk = true;
                } else {
                    isOk = false;
                }

            } catch (Exception e) {
                e.printStackTrace();
                errCode = "999";
                errMsg = "处理数据错误,原因:" + e.getMessage();
                isOk = false;
            }

            HashMap<Object, Object> addMap = new HashMap<>();
            addMap.put("trade_date", trade_date);
            addMap.put("quartz_id", id);
            addMap.put("quartz_name", name);
            addMap.put("bill_table_name", bill_table_name);
            addMap.put("thirdConfigId", thirdConfigId);
            addMap.put("is_ok", isOk ? "1" : "0");
            addMap.put("modify_time", DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd_HH_mm_ss));

            bankbillGetinfoService.insertBankbillGetinfo(addMap);

            if (!isOk && num < 10) {
                try {
                    LogUtil.error(this.getClass(), errMsg);
                    System.out.println("获取对账记录没有成功，1小时后重新执行");
                    Thread.sleep(1000 * 60 * 60);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        resultMap.put("errCode", errCode);
        resultMap.put("errMsg", errMsg);
        return resultMap;
    }
}
