package com.cnd3b.utility.wechatpay.jsapipay;

import com.cnd3b.utility.wechatdock.WechatDock_xcx;
import com.cnd3b.utility.wechatpay.jsapipay.POJO.*;
import com.cnd3b.utility.Math;
import com.cnd3b.common.BaseClass;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.db.DBConnect;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.application.tuseraccountdetails.tuseraccountdetails;

import java.util.Calendar;

public class jsapipay extends BaseClass {
    /**
     * 微信小程序账户充值
     *
     * @param siteid  站点
     * @param userid  用户ID
     * @param famount 金额,单位分
     * @param custip  客户端IP地址
     * @return
     */
    public JSCreateOrderResponse createOrder(String siteid, long userid, int famount, String custip, String wechat_code) {
        WechatDock_xcx wechatDock_xcx = new WechatDock_xcx();
        String wechat_openid = wechatDock_xcx.getOpenId(wechat_code);
        /**
         * 创建本地订单，并返回一个客户订单号
         */
        String out_trade_no = Calendar.getInstance().getTimeInMillis() + siteid + userid;
        /**
         * 开始创建微信支付订单
         */
        JSCreateOrderRequest order = new JSCreateOrderRequest();
        order.setAppid(parameter.appid);
        order.setBody("多三边-账户充值");
        order.setMch_id(parameter.mch_id);
        order.setNotify_url(parameter.notify_url);
        order.setOpenid(wechat_openid);
        order.setOut_trade_no(out_trade_no);
        order.setSpbill_create_ip(custip);
        order.setTotal_fee(famount);
        order.setTrade_type("JSAPI");//APP、JSAPI、
        JSCreateOrderResponse response = order.getOrderResponse();
        createLocalOrder(out_trade_no, siteid, userid, "账户充值", "", famount);
        return response;
    }

    /**
     * 订单查询
     *
     * @param out_trade_no 商户订单号
     * @return
     */
    public void queryOrder(String out_trade_no) {
        JSQueryOrderRequest queryOrderRequest = new JSQueryOrderRequest();
        queryOrderRequest.setAppid(parameter.appid);
        queryOrderRequest.setMch_id(parameter.mch_id);
        queryOrderRequest.setOut_trade_no(out_trade_no);
        updateLocalOrder(queryOrderRequest.getOrder());
    }

    /**
     * 订单关闭
     *
     * @param out_trade_no 商户订单号
     * @return
     */
    public JSCloseOrderResponse closeOrder(String out_trade_no) {
        JSCloseOrderRequest closeOrderRequest = new JSCloseOrderRequest();
        closeOrderRequest.setAppid(parameter.appid);
        closeOrderRequest.setMch_id(parameter.mch_id);
        closeOrderRequest.setOut_trade_no(out_trade_no);
        return closeOrderRequest.getOrderResponse();
    }

    /**
     * 创建本地订单信息?
     */
    public void createLocalOrder(String out_trade_no, String siteid, long userid, String ftype, String fappmodel, double famount) {
        PaoSetRemote twechatpayorderSet = null;
        try {
            twechatpayorderSet=getP2ServerSystemPaoSet("twechatpayorder");
            PaoRemote pao = twechatpayorderSet.addAtEnd();
            pao.setValue("siteid", siteid);
            pao.setValue("createdate", Calendar.getInstance().getTime());
            pao.setValue("tenterprise_userid", userid);
            pao.setValue("fappmodel", fappmodel);
            pao.setValue("famount", Math.div(famount, 100, 2));
            pao.setValue("out_trade_no", out_trade_no);
            pao.setValue("trade_type", "JSAPI", 11L);
            pao.setValue("ftype", ftype, 11L);
            twechatpayorderSet.save();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                twechatpayorderSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 更新本地数据库的订单信息
     */
    public boolean updateLocalOrder(JSWechatOrder wechatOrder) {
        PaoSetRemote twechatpayorderSet = null;
        try {
            twechatpayorderSet=getP2ServerSystemPaoSet("twechatpayorder","out_trade_no='" + wechatOrder.getOut_trade_no() + "'");
            if (!twechatpayorderSet.isEmpty()) {
                PaoRemote pao = twechatpayorderSet.getPao(0);
                pao.setValue("ERR_CODE", wechatOrder.getErr_code());
                pao.setValue("ERR_CODE_DES", wechatOrder.getErr_code_des());
                pao.setValue("RESULT_CODE", wechatOrder.getResult_code());
                pao.setValue("RETURN_CODE", wechatOrder.getReturn_code());
                pao.setValue("RETURN_MSG", wechatOrder.getReturn_msg());

                pao.setValue("BANK_TYPE", wechatOrder.getBank_type());
                pao.setValue("CASH_FEE", wechatOrder.getCash_fee());
                pao.setValue("TIME_END", wechatOrder.getTime_end());
                pao.setValue("TOTAL_FEE", wechatOrder.getTotal_fee());
                pao.setValue("TRADE_STATE", wechatOrder.getTrade_state());
                pao.setValue("TRADE_STATE_DESC", wechatOrder.getTrade_state_desc());
                pao.setValue("TRANSACTION_ID", wechatOrder.getTransaction_id());
                pao.setValue("orderxml", wechatOrder.getXml());
                if ("SUCCESS".equals(wechatOrder.getReturn_code()) && "SUCCESS".equals(wechatOrder.getResult_code()) && "SUCCESS".equals(wechatOrder.getTrade_state())) {
                    PaoSetRemote tuseraccountdetailsSet = pao.getPaoSet("$tuseraccountdetails", "tuseraccountdetails", "fsourceobject='" + pao.getName() + "' and fsourceid=" + pao.getUniqueIDValue());
                    Row userrow = getUser(pao.getString("siteid"), pao.getString("tenterprise_userid"));
                    if (tuseraccountdetailsSet.isEmpty()) {
                        tuseraccountdetails tuseraccountdetails = (tuseraccountdetails) tuseraccountdetailsSet.addAtEnd();
                        int famount = wechatOrder.getCash_fee();
                        String siteid = pao.getString("siteid");
                        String fname = userrow.getString("fname");
                        long userid = pao.getLong("tenterprise_userid");
                        tuseraccountdetails.setValues("收入", "充值", famount, "微信支付充值", fname, siteid, userid);
                        /**
                         * 账户余额通过tuseraccountdetails触发器实现
                         */
                    }
                }
                twechatpayorderSet.save();
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                twechatpayorderSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Row getUser(String siteid, String userid) {
        return new DBConnect().runSqlQuery("select  * from tenterprise_users where siteid='" + siteid + "' and tenterprise_userid=" + userid).get(0);
    }
}
