package com.chinapnr.pos.pay.demo.trans;

import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.chinapnr.pos.config.ChannelId;
import com.chinapnr.pos.config.InterfaceType;
import com.chinapnr.pos.config.PnrRequestKey;
import com.chinapnr.pos.config.PnrResponseKey;
import com.chinapnr.pos.config.key.trans.PayRequestKey;
import com.chinapnr.pos.pay.demo.R;
import com.chinapnr.pos.pay.demo.trans.bean.AccSplitBunchEntity;
import com.chinapnr.pos.pay.demo.trans.bean.AcctInfosEntity;
import com.chinapnr.pos.trans.PnrService;
import com.chinapnr.pos.trans.PnrTransListener;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import timber.log.Timber;

public class PayActivity extends AppCompatActivity {

    Button btnAcquire, btnScanW, btnScanA;
    TextView tvRequest, tvResult;
    EditText etMemberId, merOperId, merOperIdPrinted, etOrdAmt, etOrdNo, et_pay_limit;
    RadioGroup radioGroup;
    RadioButton qrcodeU, qrcodeA, qrcodeW, qrcodeJ;
    String payType;
    EditText divRate1, divRate2, divRate3, divRate4;
    EditText merid1, merid2, merid3, merid4;
    EditText divnum, divmember;
    EditText goodsDesc,isdelayacct;

    EditText printKey1, printValue1, printKey2, printValue2, printKey3, printValue3;
    EditText printQrcodeValue;
    private Map<String, Object> outPrintData;
    private View view_line;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        btnAcquire = (Button) findViewById(R.id.btn_acquire);
        btnScanW = (Button) findViewById(R.id.btn_scan_w);
        btnScanA = (Button) findViewById(R.id.btn_scan_a);
        tvRequest = (TextView) findViewById(R.id.tv_request);
        tvResult = (TextView) findViewById(R.id.tv_result);
        etMemberId = (EditText) findViewById(R.id.et_member_id);
        merOperId = (EditText) findViewById(R.id.et_merOperId);
        merOperIdPrinted = (EditText) findViewById(R.id.et_merOperId_printed);
        etOrdAmt = (EditText) findViewById(R.id.et_amount);
        etOrdNo = (EditText) findViewById(R.id.et_ord_no);
        isdelayacct = (EditText) findViewById(R.id.et_isdelay_acct);

        goodsDesc = (EditText) findViewById(R.id.et_goods_desc);

        divRate1 = (EditText) findViewById(R.id.divRate1);
        divRate2 = (EditText) findViewById(R.id.divRate2);
        divRate3 = (EditText) findViewById(R.id.divRate3);
        divRate4 = (EditText) findViewById(R.id.divRate4);
        merid1 = (EditText) findViewById(R.id.merid1);
        merid2 = (EditText) findViewById(R.id.merid2);
        merid3 = (EditText) findViewById(R.id.merid3);
        merid4 = (EditText) findViewById(R.id.merid4);

        divnum = (EditText) findViewById(R.id.divnum);
        divmember = (EditText) findViewById(R.id.divmember);
        //获取实例
        radioGroup = (RadioGroup) findViewById(R.id.radioGroupID);
        qrcodeU = (RadioButton) findViewById(R.id.qrcode_u);
        qrcodeA = (RadioButton) findViewById(R.id.qrcode_a);
        qrcodeW = (RadioButton) findViewById(R.id.qrcode_w);
        qrcodeJ = (RadioButton) findViewById(R.id.qrcode_j);

        //获取自定义打印数据
        printKey1 = (EditText) findViewById(R.id.printKey1);
        printKey2 = (EditText) findViewById(R.id.printKey2);
        printKey3 = (EditText) findViewById(R.id.printKey3);
        printValue1 = (EditText) findViewById(R.id.printValur1);
        printValue2 = (EditText) findViewById(R.id.printValur2);
        printValue3 = (EditText) findViewById(R.id.printValur3);

        //获取自定义打印二维码字符串
        printQrcodeValue = (EditText) findViewById(R.id.printQrcodeValue);
        view_line = findViewById(R.id.view_line);
        updateOrdNo();

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == qrcodeU.getId()) {
                    System.out.println("选中了银联钱包!");
                    payType = "U";
                } else if (checkedId == qrcodeA.getId()) {
                    System.out.println("选中了支付宝!");
                    payType = "A";
                } else if (checkedId == qrcodeW.getId()) {
                    System.out.println("选中了微信!");
                    payType = "W";
                } else if (checkedId == qrcodeJ.getId()) {
                    System.out.println("选中了聚合码!");
                    payType = "J";
                }
            }
        });

        btnAcquire.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPay(ChannelId.CHANNEL_BANK);
            }
        });
        btnScanA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPay(ChannelId.CHANNEL_SCAN);
            }
        });
        btnScanW.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPay(ChannelId.CHANNEL_QR_CODE);
            }
        });
    }

    private void doPay(String channelId){
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty(PayRequestKey.KEY_CHANNEL_ID, channelId);
        jsonObject.addProperty(PayRequestKey.KEY_MEMBER_ID, etMemberId.getText().toString());
        jsonObject.addProperty(PayRequestKey.KEY_MER_OPER_ID, merOperId.getText().toString());
        jsonObject.addProperty(PayRequestKey.KEY_MER_OPER_ID_PRINTED, merOperIdPrinted.getText().toString());
        jsonObject.addProperty(PayRequestKey.KEY_ORD_AMT, etOrdAmt.getText().toString());
        jsonObject.addProperty(PayRequestKey.KEY_OUT_ORD_ID, etOrdNo.getText().toString());
        jsonObject.addProperty(PayRequestKey.KEY_IS_DELAY_ACCT, isdelayacct.getText().toString());
        jsonObject.addProperty(PayRequestKey.KEY_GOODS_DESC, goodsDesc.getText().toString());
        jsonObject.addProperty(PayRequestKey.KEY_ORD_REMARK, "5201314");
        if (isSplitBunchEntity()){
            jsonObject.addProperty(PayRequestKey.KEY_ACC_SPLIT_BUNCH, new Gson().toJson(getGson()));

        }
        if (isPrintOutData()){
            jsonObject.addProperty(PayRequestKey.KEY_OUT_PRINT_DATA, new Gson().toJson(getPrintData()));
        }
        jsonObject.addProperty(PayRequestKey.KEY_OUT_PRINT_QR_CODE, printQrcodeValue.getText().toString());
        if (ChannelId.CHANNEL_QR_CODE.equals(channelId)){
            jsonObject.addProperty(PayRequestKey.KEY_MOBILE_PAY_TYPE, payType);
        }
        tvRequest.setText("接口:" + InterfaceType.Trans.IT_PAY + "\n" + "参数：" + jsonObject.toString());
        view_line.setVisibility(View.VISIBLE);

        jsonObject.addProperty(PnrRequestKey.KEY_INTERFACE_TYPE, InterfaceType.Trans.IT_PAY);
        PnrService.getInstance(getApplicationContext()).doTrans(jsonObject.toString(), new PnrTransListener() {
            @Override
            public void onResult(String result) {
                Timber.e(result);
                Map resultMap = new Gson().fromJson(result, Map.class);
                String responseCode = resultMap.get(PnrResponseKey.KEY_RESPONSECODE).toString();
                if ("00".equals(responseCode)){
                    tvResult.setText("支付成功："+result);
                }else {
                    tvResult.setText("支付失败：" + result);
                }
            }

        });
    }


    private void updateOrdNo() {
        etOrdNo.setText(getMerOrdNo());
    }
    private boolean isPrintOutData(){
        return !TextUtils.isEmpty(printKey1.getText().toString()) || !TextUtils.isEmpty(printKey2.getText().toString()) || !TextUtils.isEmpty(printKey3.getText().toString());
    }

    private Map<String, Object> getPrintData() {
        outPrintData = new HashMap<String, Object>();
        if (printKey1.getText().toString() != null && printKey1.getText().toString().length() > 0) {
            outPrintData.put(printKey1.getText().toString(), printValue1.getText().toString());
        }
        if (printKey2.getText().toString() != null && printKey2.getText().toString().length() > 0) {
            outPrintData.put(printKey2.getText().toString(), printValue2.getText().toString());
        }
        if (printKey3.getText().toString() != null && printKey3.getText().toString().length() > 0) {
            outPrintData.put(printKey3.getText().toString(), printValue3.getText().toString());
        }
        return outPrintData;
    }

    public AccSplitBunchEntity getGson() {
        AccSplitBunchEntity accSplitBunchEntity = new AccSplitBunchEntity();
        accSplitBunchEntity.setFeeMemberId(divmember.getText().toString());
        accSplitBunchEntity.setDivCusCount(divnum.getText().toString());
        List<AccSplitBunchEntity.AcctInfoslist> acctInfoslists = new ArrayList<AccSplitBunchEntity.AcctInfoslist>();
        AccSplitBunchEntity.AcctInfoslist accInfoentity;

        if (merid1.getText().toString() != null && merid1.getText().toString().length() > 0) {
            accInfoentity = accSplitBunchEntity.new AcctInfoslist();
            accInfoentity.setMemberId(merid1.getText().toString());
            accInfoentity.setDivRate(divRate1.getText().toString());
            acctInfoslists.add(accInfoentity);
        }
        if (merid2.getText().toString() != null && merid2.getText().toString().length() > 0) {
            accInfoentity = accSplitBunchEntity.new AcctInfoslist();
            accInfoentity.setMemberId(merid2.getText().toString());
            accInfoentity.setDivRate(divRate2.getText().toString());
            acctInfoslists.add(accInfoentity);
        }
        if (merid3.getText().toString() != null && merid3.getText().toString().length() > 0) {
            accInfoentity = accSplitBunchEntity.new AcctInfoslist();
            accInfoentity.setMemberId(merid3.getText().toString());
            accInfoentity.setDivRate(divRate3.getText().toString());
            acctInfoslists.add(accInfoentity);
        }
        if (merid4.getText().toString() != null && merid4.getText().toString().length() > 0) {
            accInfoentity = accSplitBunchEntity.new AcctInfoslist();
            accInfoentity.setMemberId(merid4.getText().toString());
            accInfoentity.setDivRate(divRate4.getText().toString());
            acctInfoslists.add(accInfoentity);
        }
        accSplitBunchEntity.setAcctInfos(acctInfoslists);
        return accSplitBunchEntity;
    }

    public boolean isSplitBunchEntity() {
        boolean flag = false;
        if ((merid3.getText().toString() != null && merid3.getText().toString().length() > 0)
                || (merid1.getText().toString() != null && merid1.getText().toString().length() > 0)
                || (merid2.getText().toString() != null && merid2.getText().toString().length() > 0)
                || (merid4.getText().toString() != null && merid4.getText().toString().length() > 0)
                || (divmember.getText().toString() != null && divmember.getText().toString().length() > 0)
                || (divnum.getText().toString() != null && divnum.getText().toString().length() > 0)) {
            flag = true;
        }
        return flag;
    }


    public String getJson() {
        JSONObject jsonObject = null;
        try {
            AcctInfosEntity acctInfosEntity1 = new AcctInfosEntity();
            AcctInfosEntity acctInfosEntity2 = new AcctInfosEntity();
            AcctInfosEntity acctInfosEntity3 = new AcctInfosEntity();
            AcctInfosEntity acctInfosEntity4 = new AcctInfosEntity();
            acctInfosEntity1.setMemberId(merid1.getText().toString());
            acctInfosEntity1.setDivRate(divRate1.getText().toString());
            acctInfosEntity2.setMemberId(merid2.getText().toString());
            acctInfosEntity2.setDivRate(divRate2.getText().toString());
            acctInfosEntity3.setMemberId(merid3.getText().toString());
            acctInfosEntity3.setDivRate(divRate3.getText().toString());
            acctInfosEntity4.setMemberId(merid4.getText().toString());
            acctInfosEntity4.setDivRate(divRate4.getText().toString());
            List<AcctInfosEntity> list = new ArrayList<AcctInfosEntity>();
            if (merid1.getText().toString() != null && merid1.getText().toString().length() > 0) {
                list.add(acctInfosEntity1);
            }
            if (merid2.getText().toString() != null && merid2.getText().toString().length() > 0) {
                list.add(acctInfosEntity2);
            }
            if (merid3.getText().toString() != null && merid3.getText().toString().length() > 0) {
                list.add(acctInfosEntity3);
            }
            if (merid4.getText().toString() != null && merid4.getText().toString().length() > 0) {
                list.add(acctInfosEntity4);
            }
            JSONArray jsonArray = new JSONArray();
            JSONObject tmpObj = null;
            int count = list.size();
            for (int i = 0; i < count; i++) {
                tmpObj = new JSONObject();
                tmpObj.put("memberId", list.get(i).getMemberId());
                tmpObj.put("divRate", list.get(i).getDivRate());
                jsonArray.put(tmpObj);
                tmpObj = null;
            }
            Timber.d("---=" + jsonArray.toString());
            jsonObject = new JSONObject();
            jsonObject.put("acctInfos", jsonArray.toString());
            jsonObject.put("divCusCount", divnum.getText().toString());
            jsonObject.put("feeMemberId", divmember.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (divnum.getText().toString() == null
                && divmember.getText().toString() == null
                && merid1.getText().toString() == "商户号1"
                && divRate1.getText().toString() == "金额（分）"
                && merid2.getText().toString() == "商户号2"
                && divRate2.getText().toString() == "金额（分）"
                && merid3.getText().toString() == "商户号3"
                && divRate3.getText().toString() == "金额（分）"
                && merid4.getText().toString() == "商户号4"
                && divRate4.getText().toString() == "金额（分）") {
            return null;
        } else {
            return jsonObject.toString();
        }

    }

    public String getMerOrdNo() {
        String traceNo = (new Random().nextInt(999999)) + "";
        String date = (String) DateFormat.format("yyyyMMddHHmmss", Calendar.getInstance(Locale.CHINA));
        return date + traceNo;
    }
}