package com.app.ydl.pay_v3.service;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.app.framework.core.support.view.form.AjaxResult;
import com.app.framework.core.support.view.grid.Paging;
import com.app.ydl.pay_v3.view.YdlDmpPayApplyEditView;
import com.app.ydl.pay_v3.view.YdlDmpPayApplyView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 壹点灵支付应用管理
 */
@Service
public class YdlDmpPayApplyService {
    private static Logger logger = LoggerFactory.getLogger(YdlDmpPayApplyService.class.getName());

    @Value("${ydl.dmp.pay_apply.query}")
    private String query;

    @Value("${ydl.dmp.pay_apply.manger}")
    private String manger;

    private JSONObject queryByDmp(YdlDmpPayApplyView view, Paging paging) {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-App-Id", "finance_cloud");

        Map<String, Object> filter = new HashMap<>();
        if (StringUtils.isNotBlank(view.getType())) {
            filter.put("pay_config.type", view.getType());
        }
        if (StringUtils.isNotBlank(view.getAppId())) {
            filter.put("id", view.getAppId());
        }

        Map<String, Object> params = new HashMap<>();
        params.put("filter", filter);
        params.put("hasNot", false);
        params.put("ignoreNull", true);
        params.put("minimumOrMatch", 0);
        params.put("skip", paging.getStart());
        params.put("limit", paging.getLimit());
        params.put("count", paging.getIsCountPage());
        String s = null;
        try {
            HttpRequest request = HttpUtil.createPost(query);
            request.headerMap(headers, true);
            request.body(JSONObject.toJSONString(params));
            s = request.execute().body();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(s);
    }

    public List<JSONObject> query(YdlDmpPayApplyView view, Paging paging) {
        JSONObject object = this.queryByDmp(view, paging);
        List<JSONObject> list = new ArrayList<>();
        if (!"200".equals(object.getString("code"))) {
            return list;
        }
        JSONObject data = object.getJSONObject("data");
        paging.setTotalCount(data.getLong("amount"));
        JSONArray jsonArray = data.getJSONArray("objects");
        list = jsonArray.toJavaList(JSONObject.class);
        return list;
    }

    public JSONObject queryById(String appId) {
        YdlDmpPayApplyView view = new YdlDmpPayApplyView();
        view.setAppId(appId);
        Paging paging = new Paging();
        paging.setIsCountPage(false);
        JSONObject object = this.queryByDmp(view, paging);
        if (!"200".equals(object.getString("code"))) {
            return null;
        }
        JSONObject data = object.getJSONObject("data");
        paging.setTotalCount(data.getLong("amount"));
        JSONArray jsonArray = data.getJSONArray("objects");
        return jsonArray.getJSONObject(0);
    }

    public AjaxResult save(YdlDmpPayApplyEditView editView) {
        String url = StringUtils.isNotBlank(editView.getId()) ? manger + "/" + editView.getId() : manger;

        Map<String, String> headers = new HashMap<>();
        headers.put("X-App-Id", "finance_cloud");

        String channel_type = editView.getChannel_type();
        LinkedHashMap<String, Object> params = new LinkedHashMap<>();
        params.put("app_name", editView.getApp_name());
        params.put("app_secret", editView.getApp_secret());
        params.put("sign_type", editView.getSign_type());
        params.put("status", editView.getStatus());
        params.put("channel_type", channel_type);
        params.put("business_notice_url", editView.getBusiness_notice_url());
        params.put("desc", editView.getDesc());

        LinkedHashMap<String, Object> pay_config = new LinkedHashMap<>();
        pay_config.put("app_id", editView.getPay_config().getApp_id());
        if ("ALI_APP".equals(channel_type) || "ALI_WAP".equals(channel_type)
                || "1".equals(channel_type) || "2".equals(channel_type)) { //支付宝
            String pay_notify_url;
            if ("dev".equals(SpringUtil.getActiveProfile())) {
                pay_notify_url = "https://testapi.ydl.com/api/auth/cashierV3/aliPay/payNotify";
            } else if ("test".equals(SpringUtil.getActiveProfile())) {
                pay_notify_url = "https://api-test.ydl.com/api/auth/cashierV3/aliPay/payNotify";
            } else {
                pay_notify_url = "https://api.ydl.com/api/auth/cashierV3/aliPay/payNotify";
            }
            pay_config.put("type", "aliPayConfig");
            pay_config.put("rsa_private_key", editView.getPay_config().getRsa_private_key());
            pay_config.put("ali_pay_application_public_key", editView.getPay_config().getAli_pay_application_public_key());
            pay_config.put("ali_pay_common_public_key", editView.getPay_config().getAli_pay_common_public_key());
            pay_config.put("pay_notify_url", pay_notify_url);
        } else { //微信
            String pay_notify_url;
            if ("dev".equals(SpringUtil.getActiveProfile())) {
                pay_notify_url = "https://testapi.ydl.com/api/auth/cashierV3/wx/payNotify";
            } else if ("test".equals(SpringUtil.getActiveProfile())) {
                pay_notify_url = "https://api-test.ydl.com/api/auth/cashierV3/wx/payNotify";
            } else {
                pay_notify_url = "https://api.ydl.com/api/auth/cashierV3/wx/payNotify";
            }
            pay_config.put("type", "wxPayConfig");
            pay_config.put("merchant_id", editView.getPay_config().getChannel_account());
            pay_config.put("merchant_api_key", editView.getPay_config().getMerchant_api_key());
            pay_config.put("pay_notify_url", pay_notify_url);
            pay_config.put("refund_notify_url", "xxx");
            pay_config.put("cert_path", editView.getPay_config().getCert_path());
        }
        pay_config.put("channel_account", editView.getPay_config().getChannel_account());
        pay_config.put("return_url", editView.getPay_config().getReturn_url());
        pay_config.put("quit_url", editView.getPay_config().getQuit_url());
        pay_config.put("is_sand_box", 0);
        params.put("pay_config", pay_config);
        String content = JSONObject.toJSONString(params);
        logger.info("更新:{},参数:{}", url, content);

        String s = null;
        try {
            if (StringUtils.isNotBlank(editView.getId())) { //修改
                HttpRequest request = HttpUtil.createRequest(Method.PATCH, url);
                request.headerMap(headers, true);
                request.body(content);
                s = request.execute().body();
            } else { //新增
                HttpRequest request = HttpUtil.createPost(url);
                request.headerMap(headers, true);
                request.body(content);
                s = request.execute().body();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("更新结果:{}", s);

        JSONObject res = JSONObject.parseObject(s);
        return AjaxResult.wrap(res.getString("code"), StringUtils.isNotBlank(res.getString("err_msg")) ? res.getString("err_msg") : res.getString("msg"));
    }
}
