package com.saye.hospitalgd.scheduler.jobMethod;

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 java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author thuang
 * @version 1.0
 * @description: 获取商户POS通对账单 调用dmz服务器部署的接口
 * @date 2021/9/13 14:46
 */
public class BankGetDataBySHPOS {

    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;

        // 重新执行最多10次 还没获取到肯定有问题 不执行了
        // 如果有传入时间 那就只执行一次 获取不到就还是获取不到
        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 ftp_file_name = StringDUtil.changeNullToEmpty(map.get("FTP_FILE_NAME"));
            String mch_id = StringDUtil.changeNullToEmpty(map.get("MCH_ID"));

            // 替换其中的标记
            Matcher mat = Pattern.compile("\\{([^}]*)\\}").matcher(ftp_file_name);

            while (mat.find()) {
                String group = mat.group();
                group = group.substring(1, group.length() - 1);

                // 替换商户id
                if ("MCH_ID".equals(group)) {
                    ftp_file_name = ftp_file_name.replaceFirst("\\{([^}]*)\\}", mch_id);
                }

                // 替换日期 主要试t+1 还是t+2这种
                if (group.contains("DATE")) {
                    String dateStr = "";

                    // 如果有传入时间 那就使用传入时间
                    if ("".equals(trade_date)) {
                        group = group.replaceFirst("DATE", "");

                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date());

                        // 执行修改日期
                        if (!"".equals(group)) {
                            int t = Integer.parseInt(group);
                            calendar.add(Calendar.DATE, t);
                        }
                        Date searchDate = calendar.getTime();
                        trade_date = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, searchDate);
                        dateStr = DateDUtil.DateToStr(DateDUtil.yyyyMMdd, searchDate);
                    } else {
                        Date date = DateDUtil.strToDate(DateDUtil.yyyy_MM_dd, trade_date);
                        dateStr = DateDUtil.DateToStr(DateDUtil.yyyyMMdd, date);
                    }
                    ftp_file_name = ftp_file_name.replaceFirst("\\{([^}]*)\\}", dateStr);
                }
            }

            map.put("FTP_FILE_NAME", ftp_file_name);
            map.put("trade_date", trade_date);


            try {

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

                 String result = HttpDutil.post(dmz_url + "/getBankDataBySHPOS", map);

                 // 解析返回的json字符串
                 JSONObject jsonObject = JSONObject.parseObject(result);

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

                // 如果没问题 解析返回的集合
                if ("0".equals(errCode)) {
                    String list = StringDUtil.changeNullToEmpty(jsonObject.get("list"));
                    List<BankbillHistory> bankbillHistories = JSONArray.parseArray(list, BankbillHistory.class);

                    // 如果有数据
                    if (bankbillHistories != null && bankbillHistories.size() > 0) {
                        // 先存一份原始的 这份只是留底查询
                        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);

            if (isOk) {
                addMap.put("is_ok", "1");
            } else {
                addMap.put("is_ok", "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;
    }


}
