package com.glxp.mipsdl.service.yb;

import cn.hsa.zephyr.apisdk.ZephyrMedicalClient;
import cn.hsa.zephyr.apisdk.internal.exception.ZephyrApiException;
import cn.hsa.zephyr.apisdk.internal.util.StringUtils;
import cn.hsa.zephyr.apisdk.internal.util.encrypt.EncryptionModeEnum;
import cn.hsa.zephyr.apisdk.internal.util.encrypt.SignTypeEnum;
import cn.hsa.zephyr.apisdk.request.ZephyrMedicalRequest;
import cn.hsa.zephyr.apisdk.response.ChsMedicalResponse;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.glxp.mipsdl.entity.system.ThrYbSetup;
import com.glxp.mipsdl.entity.system.ThrYbSetupMapper;
import com.glxp.mipsdl.res.BaseResponse;
import com.glxp.mipsdl.service.basic.RelCodeDetailService;
import com.glxp.mipsdl.service.system.ThrYbSetupService;
import com.glxp.mipsdl.util.DateUtil;
import com.glxp.mipsdl.util.ResultVOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class YbClient {

    @Resource
    ThrYbSetupService thrYbSetupService;
    @Resource
    ThrYbSetupMapper thrYbSetupMapper;
    @Resource
    RelCodeDetailService relCodeDetailService;

    /**
     * 易联众
     *
     * @param apiNo
     * @param data
     * @return
     */
    public ChsMedicalResponse ybPost(String apiNo, JSONObject data) {

        log.info("[" + apiNo + "]医保接口请求参数：" + data);
        ThrYbSetup thrYbSetup = thrYbSetupService.getSetUp();
        if (thrYbSetup == null)
            throw new RuntimeException("未配置医保接口");
        String infno = apiNo;

        SignTypeEnum signType = SignTypeEnum.SM3;
        EncryptionModeEnum encType = EncryptionModeEnum.SM4;
        String msgId = thrYbSetup.getFixmedins_code() + DateUtil.formatYbDateTime(new Date()) + thrYbSetup.getSequenceNum();
        try {

            ZephyrMedicalClient client = new ZephyrMedicalClient(thrYbSetup.getUrl(), infno, thrYbSetup.getAppId(), thrYbSetup.getAppSecret(),
                    signType, thrYbSetup.getSignKey(), encType, thrYbSetup.getEncKey());
            ZephyrMedicalRequest req = new ZephyrMedicalRequest();
            req.setMsgid(msgId);
            req.setMdtrtAreaAdmdvs(thrYbSetup.getMdtrtarea_admvs());
            req.setInsuplcAdmdvs(thrYbSetup.getInsuplc_admdvs());
            req.setOpter(thrYbSetup.getOpter());
            req.setOpterType(thrYbSetup.getOpter_type());
            req.setOpterName(thrYbSetup.getOpter_name());
            req.setInfTime(DateUtil.formatDateTime(new Date()));
            req.setFixmedinsCode(thrYbSetup.getFixmedins_code());
            req.setFixmedinsName(thrYbSetup.getFixmedins_name());

            req.setInput(data);
            req.setSignNo(thrYbSetup.getSignNo());
            log.info("【" + apiNo + "】医保接口请求参数：" + JSONObject.toJSONString(req));
            ChsMedicalResponse resp = client.execute(req);
            return resp;
        } catch (ZephyrApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 四川银海
     */
    public BaseResponse ybPostScyh(String apiNo, JSONObject data) {

        log.info("[" + apiNo + "]医保接口请求参数：" + data);
        ThrYbSetup thrYbSetup = thrYbSetupService.getSetUp();
        if (thrYbSetup == null)
        {
            throw new RuntimeException("未配置医保接口");
        }
        // 组装访问数据
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        // 获取当前日期和时间
        Date now = new Date();
        // 使用format方法格式化日期和时间
        String formattedDate = dateFormat.format(now);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("infno", apiNo);
        jsonObject.put("msgid", thrYbSetup.getFixmedins_code() + formattedDate + "0001");
        jsonObject.put("insuplc_admdvs", thrYbSetup.getInsuplc_admdvs());
        jsonObject.put("mdtrtarea_admvs", thrYbSetup.getMdtrtarea_admvs());
        jsonObject.put("recer_sys_code", thrYbSetup.getRecer_sys_code());
        jsonObject.put("dev_no", "");
        jsonObject.put("dev_safe_info", "");
        jsonObject.put("cainfo", thrYbSetup.getAppSecret());
        jsonObject.put("signtype", "");
        jsonObject.put("infver", thrYbSetup.getInfver());
        jsonObject.put("opter_type", thrYbSetup.getOpter_type());
        jsonObject.put("opter", thrYbSetup.getOpter());
        jsonObject.put("opter_name", thrYbSetup.getOpter_name());
        jsonObject.put("inf_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        jsonObject.put("fixmedins_code", thrYbSetup.getFixmedins_code());
        jsonObject.put("fixmedins_name", thrYbSetup.getFixmedins_name());
        jsonObject.put("app_id", "");
        jsonObject.put("enc_type", "");
        jsonObject.put("pw_ecToken", "");
        // 签到信息时间不为今天就进行签到刷新
        String signNo = null;
        if (StringUtils.isEmpty(thrYbSetup.getSignNo())
                || Objects.isNull(thrYbSetup.getSignData())
                || !thrYbSetup.getSignData().equals(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))) {
            // 签到系统刷新
            jsonObject.put("infno", "9001");
            JSONObject jsonObjectSignIn = new JSONObject();
            JSONObject jsonObjectSignInObg = new JSONObject();
            jsonObjectSignInObg.put("opter_no", thrYbSetup.getOpter_no());
            jsonObjectSignInObg.put("mac", thrYbSetup.getMac());
            jsonObjectSignInObg.put("ip", thrYbSetup.getIp());
            jsonObjectSignIn.put("signIn", jsonObjectSignInObg);

            jsonObject.put("input", jsonObjectSignIn);
            try {
                log.info("医保签到入参===" +  JSONUtil.toJsonStr(jsonObject));
                String json = HttpUtil.post(thrYbSetup.getUrl(), JSONUtil.toJsonStr(jsonObject));
                log.info("医保签到返回===" +  json);

//                String json = "{\n" +
//                        "    \"output\":{\n" +
//                        "        \"signinoutb\":{\n" +
//                        "            \"sign_no\":\"510700G0000005207526\",\n" +
//                        "            \"sign_time\":\"2024-11-09 00:00:00\"\n" +
//                        "        }\n" +
//                        "    },\n" +
//                        "    \"infcode\":0,\n" +
//                        "    \"warn_msg\":null,\n" +
//                        "    \"cainfo\":null,\n" +
//                        "    \"err_msg\":\"success\",\n" +
//                        "    \"refmsg_time\":\"20241109171206549\",\n" +
//                        "    \"signtype\":null,\n" +
//                        "    \"respond_time\":\"20241109171206598\",\n" +
//                        "    \"inf_refmsgid\":\"510000202411091712060847645203\"\n" +
//                        "}";
                Map map = JSONUtil.toBean(json, Map.class);
                Map output = (Map) map.get("output");
                Map signinoutb = (Map) output.get("signinoutb");
                signNo = (String) signinoutb.get("sign_no");
                String signTime = (String) signinoutb.get("sign_time");

                // 插入签到值和签到时间更新
                ThrYbSetup thrYbSetupUpdate = new ThrYbSetup();
                thrYbSetupUpdate.setSignNo(signNo);
                thrYbSetupUpdate.setSignData(signTime);
                thrYbSetupMapper.update(thrYbSetupUpdate, new QueryWrapper<ThrYbSetup>()
                        .last("limit 1")
                );

            } catch (Exception e) {
                return ResultVOUtils.error(500, "第三方医保签到失败！！"+e.getMessage());
            }

//                            .eq("","")
//                    ,);
        } else {
            signNo = thrYbSetup.getSignNo();
        }
        jsonObject.put("infno", apiNo);
        jsonObject.put("input", data);
        jsonObject.put("sign_no", signNo);
        log.info("上传医保入参===" +  JSONUtil.toJsonStr(jsonObject));
        String json;
        try {
            json= HttpUtil.post(thrYbSetup.getUrl(), JSONUtil.toJsonStr(jsonObject));
            log.info("上传医保结果===" + json);
            return ResultVOUtils.success("上传医保结果===" + json);

        }catch (Exception e){
            return ResultVOUtils.error(500, "上传医保失败！！"+e.getMessage());

        }
//

    }

    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("infno", "111");
        jsonObject.put("data", "222");
        System.out.println(JSONUtil.toJsonStr(jsonObject));
    }
}
