package com.cnd3b.utility.wechatpay.apppay;

import com.cnd3b.utility.wechatpay.apppay.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 apppay extends BaseClass {
    /**
     * 创建支付订单
     *
     * @param siteid    站点
     * @param userid    用户ID
     * @param fappmodel 版本号
     * @param famount   金额,单位分
     * @param custip    客户端IP地址
     * @return
     */
    public APPCreateOrderResponse createOrder(String siteid, long userid, String fappmodel, int famount, String custip) {
        /**
         * 创建本地订单，并返回一个客户订单号
         */
        String out_trade_no = Calendar.getInstance().getTimeInMillis() + siteid + userid;
        /**
         * 开始创建微信支付订单
         */
        APPCreateOrderRequest order = new APPCreateOrderRequest();
        order.setAppid(parameter.appid);
        order.setBody("多三边-使用年费");
        order.setMch_id(parameter.mch_id);
        order.setNotify_url(parameter.notify_url);
        order.setOut_trade_no(out_trade_no);
        order.setSpbill_create_ip(custip);
        order.setTotal_fee(famount);
        order.setTrade_type("APP");//APP、JSAPI、
        APPCreateOrderResponse response = order.getOrderResponse();
        createLocalOrder(out_trade_no, siteid, userid, "系统授权", fappmodel, famount);
        return response;
    }

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


    /**
     * 订单查询
     *
     * @param out_trade_no 商户订单号
     * @return
     */
    public void queryOrder(String out_trade_no) {
        APPQueryOrderRequest queryOrderRequest = new APPQueryOrderRequest();
        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 APPCloseOrderResponse closeOrder(String out_trade_no) {
        APPCloseOrderRequest closeOrderRequest = new APPCloseOrderRequest();
        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", "APP", 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(AppWechatOrder wechatOrder) {

        PaoSetRemote twechatpayorderSet = null;
        try {
            twechatpayorderSet=getP2ServerSystemPaoSet("twechatpayorder","out_trade_no='" + wechatOrder.getOut_trade_no() + "'");
            if (!twechatpayorderSet.isEmpty()) {
                System.err.println("更新本地微信付款订单"+wechatOrder.getOut_trade_no());
                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())) {

                    String ftype = pao.getString("ftype");
                    switch (ftype) {
                        case "账户充值": {
                            System.err.println("账户充值中"+wechatOrder.getOut_trade_no());
                            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触发器实现
                                 */
                            }
                            break;
                        }
                        case "系统授权": {
                            System.err.println("系统授权"+wechatOrder.getOut_trade_no());
                            PaoSetRemote tpayinfoSet = pao.getPaoSet("$tpayinfo", "tpayinfo", "fsourceobject='" + pao.getName() + "' and fsourceid=" + pao.getUniqueIDValue());
                            PaoRemote payinfo = null;
                            Row userrow = getUser(pao.getString("siteid"), pao.getString("tenterprise_userid"));
                            if (tpayinfoSet.isEmpty()) {
                                payinfo = tpayinfoSet.addAtEnd();
                                payinfo.setValue("fsourceobject", pao.getName());
                                payinfo.setValue("fsourceid", pao.getUniqueIDValue());
                                payinfo.setValue("FTYPE", "微信支付");
                                payinfo.setValue("createdate", Calendar.getInstance().getTime());
                                payinfo.setValue("createby", userrow.getString("fname"));
                            } else {
                                payinfo = tpayinfoSet.getPao(0);
                            }
                            payinfo.setValue("famount", pao.getDouble("famount"), 11L);
                            payinfo.setValue("fappmodel", pao.getString("fappmodel"), 11L);
                            Calendar calendar = Calendar.getInstance();
                            payinfo.setValue("FBEGDATE", calendar.getTime(), 11L);
                            calendar.add(Calendar.YEAR, 1);
                            payinfo.setValue("FENDDATE", calendar.getTime(), 11L);
                            payinfo.setValue("tenterprise_userid", pao.getLong("tenterprise_userid"), 11L);
                            payinfo.setValue("tagentsid", userrow.getLong("tagentsid"), 11L);
                            break;
                        }
                        default:break;
                    }
                }else{
                    System.err.println("微信付款订单"+wechatOrder.getOut_trade_no()+"未付款");
                }
                twechatpayorderSet.save();
                return true;
            } else {
                System.err.println("找不到本地微信付款订单"+wechatOrder.getOut_trade_no());
                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);
    }
}
