package com.itant.joycity.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.andexert.expandablelayout.library.ExpandableLayout;
import com.bumptech.glide.Glide;
import com.itant.joycity.R;
import com.itant.joycity.adapter.QQKefuAdapter;
import com.itant.joycity.adapter.UserInfoAdapter;
import com.itant.joycity.adapter.WechatKefuAdapter;
import com.itant.joycity.api.JoyUrl;
import com.itant.joycity.bean.Kefu;
import com.itant.joycity.bean.UserInfo;
import com.itant.joycity.bean.WechatKefu;
import com.itant.joycity.tool.StringTool;
import com.itant.joycity.tool.ToastTool;
import com.itant.joycity.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jason on 2016/10/6.
 */
public class FourthFragment extends BaseFragment implements View.OnClickListener {
    public String myJpgPath = Environment.getExternalStorageDirectory() + "/JinSha/";

    private String weiXinUrl;
    private String zhiFuBaoUrl;

    private ExpandableLayout el_wechat;// 微信支付
    private ImageView iv_er_wei_ma_wechat;// 微信的二维码

    private ExpandableLayout el_alipay;// 支付宝支付
    private ImageView iv_er_wei_ma_alipay;// 支付宝的二维码

    private ExpandableLayout el_bank;// 银行支付
    private List<UserInfo> userInfos;// 用户信息
    private UserInfoAdapter userInfoAdapter;

    private ExpandableLayout el_kefu;// 客服
    private List<Kefu> qqKefus;// qq客服
    private QQKefuAdapter qqKefuAdapter;

    private List<WechatKefu> wechatKefus;// 微信客服
    private WechatKefuAdapter wechatKefuAdapter;

    private EditText et_account;// 账号
    private EditText et_money;// 金额
    private RadioGroup rg_payment;//支付方式
    private int payment = 1;// 微信1 支付宝2 银行3


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fourth, null);


        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("充值通道");

        el_wechat = (ExpandableLayout) view.findViewById(R.id.el_wechat);
        LinearLayout ll_wechat = (LinearLayout) el_wechat.findViewById(R.id.ll_wechat);
        ll_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!el_wechat.isOpened()) {
                    getWeiXinUrl();
                    el_wechat.show();
                } else {
                    el_wechat.hide();
                }
            }
        });
        iv_er_wei_ma_wechat = (ImageView) el_wechat.findViewById(R.id.iv_er_wei_ma_wechat);
        iv_er_wei_ma_wechat.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        Bitmap tmpBitmap = null;
                        if (!TextUtils.isEmpty(weiXinUrl)) {
                            try {
                                InputStream is = new URL(weiXinUrl).openStream();
                                tmpBitmap = BitmapFactory.decodeStream(is);
                                String picName = "微信"+System.currentTimeMillis()+".png";
                                saveMyBitmap(picName, tmpBitmap);
                                is.close();

                                insertIntoAlbum(picName);
                                handler.sendEmptyMessage(1);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            handler.sendEmptyMessage(3);
                        }

                    }
                }).start();
                return true;
            }
        });

        el_alipay = (ExpandableLayout) view.findViewById(R.id.el_alipay);
        LinearLayout ll_alipay = (LinearLayout) el_alipay.findViewById(R.id.ll_alipay);
        ll_alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!el_alipay.isOpened()) {
                    getZhiFuBaoUrl();
                    el_alipay.show();
                } else {
                    el_alipay.hide();
                }
            }
        });
        iv_er_wei_ma_alipay = (ImageView) el_alipay.findViewById(R.id.iv_er_wei_ma_alipay);
        iv_er_wei_ma_alipay.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        Bitmap tmpBitmap = null;
                        if (!TextUtils.isEmpty(zhiFuBaoUrl)) {
                            try {
                                InputStream is = new URL(zhiFuBaoUrl).openStream();
                                tmpBitmap = BitmapFactory.decodeStream(is);

                                String picName = "支付宝"+System.currentTimeMillis()+".png";
                                saveMyBitmap(picName, tmpBitmap);
                                is.close();

                                insertIntoAlbum(picName);
                                handler.sendEmptyMessage(2);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            handler.sendEmptyMessage(3);
                        }

                    }
                }).start();

                return true;
            }
        });

        el_bank = (ExpandableLayout) view.findViewById(R.id.el_bank);

        LinearLayout ll_bank = (LinearLayout) el_bank.findViewById(R.id.ll_bank);
        ll_bank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!el_bank.isOpened()) {
                    getUserInfos();
                    el_bank.show();
                } else {
                    el_bank.hide();
                }
            }
        });

        ListView lv_bank = (ListView) el_bank.findViewById(R.id.lv_bank);
        userInfos = new ArrayList<>();
        userInfoAdapter = new UserInfoAdapter(getActivity(), userInfos);
        lv_bank.setAdapter(userInfoAdapter);

        el_kefu = (ExpandableLayout) view.findViewById(R.id.el_kefu);

        LinearLayout ll_kefu = (LinearLayout) el_kefu.findViewById(R.id.ll_kefu);
        ll_kefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!el_kefu.isOpened()) {
                    getKefuInfos();
                    el_kefu.show();
                } else {
                    el_kefu.hide();
                }
            }
        });

        // QQ
        MyListView lv_qq = (MyListView) el_kefu.findViewById(R.id.lv_qq);
        qqKefus = new ArrayList<>();
        qqKefuAdapter = new QQKefuAdapter(getActivity(), qqKefus);
        lv_qq.setAdapter(qqKefuAdapter);
        // 微信
        MyListView lv_wechat = (MyListView) el_kefu.findViewById(R.id.lv_weixin);
        wechatKefus = new ArrayList<>();
        wechatKefuAdapter = new WechatKefuAdapter(getActivity(), wechatKefus);
        lv_wechat.setAdapter(wechatKefuAdapter);

        rg_payment = (RadioGroup) view.findViewById(R.id.rg_payment);
        rg_payment.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_wechat:
                        payment = 1;
                        break;
                    case R.id.rb_alipay:
                        payment = 2;
                        break;
                    case R.id.rb_bank:
                        payment = 3;
                        break;
                    default:
                        break;
                }
            }
        });

        et_account = (EditText) view.findViewById(R.id.et_account);
        et_money = (EditText) view.findViewById(R.id.et_money);

        Button btn_submit = (Button) view.findViewById(R.id.btn_submit);
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击提交
                submitPayment();
            }
        });

        getWeiXinUrl();
        getZhiFuBaoUrl();
        getUserInfos();
        getKefuInfos();
        return view;
    }

    private void insertIntoAlbum(String picName) {
        // 插入到相册
        try {
            MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),
                    myJpgPath, picName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        // 通知相册更新
        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(myJpgPath+picName))));
    }

    /**
     * 提交成功清空表单
     */
    private void resetPayment() {
        et_account.setText("");
        et_money.setText("");
    }

    /**
     * 提交支付信息
     */
    private void submitPayment() {
        String account = et_account.getText().toString();
        String money = et_money.getText().toString();
        if (TextUtils.isEmpty(account)) {
            ToastTool.showShort(getActivity(), "会员账号不能为空");
            return;
        }

        if (TextUtils.isEmpty(money)) {
            ToastTool.showShort(getActivity(), "转账金额不能为空");
            return;
        }

        RequestParams params = new RequestParams(JoyUrl.URL_SUBMIT);
        params.addQueryStringParameter("account", account);
        params.addQueryStringParameter("money", money);
        params.addQueryStringParameter("payment", String.valueOf(payment));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null) {
                            String success = jsonObject.getString("Submit");
                            if (TextUtils.equals(success, "1")) {
                                ToastTool.showShort(getActivity(), "提交成功");
                                resetPayment();
                            } else {
                                ToastTool.showShort(getActivity(), "提交失败");
                            }
                        }
                    } catch (Exception e) {
                        ToastTool.showShort(getActivity(), "提交失败");
                        e.printStackTrace();
                    }
                } else {
                    ToastTool.showShort(getActivity(), "提交失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                ToastTool.showShort(getActivity(), "提交失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                ToastTool.showShort(getActivity(), "提交取消");
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取银行信息
     */
    private void getUserInfos() {
        RequestParams params = new RequestParams(JoyUrl.URL_USER_INFO);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null) {
                            JSONArray jsonArray = jsonObject.getJSONArray("BankCard");
                            if (jsonArray != null) {
                                List<UserInfo> userBankInfos = StringTool.stringToList(jsonArray.toString(), UserInfo.class);
                                if (userBankInfos != null) {
                                    if (userInfos != null && userInfos.size() > 0) {
                                        userInfos.clear();
                                    }
                                    userInfos.addAll(userBankInfos);
                                    userInfoAdapter.notifyDataSetChanged();
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastTool.showShort(getActivity(), "获取数据失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取客服信息
     */
    private void getKefuInfos() {
        RequestParams params = new RequestParams(JoyUrl.URL_KEFU);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null) {
                            JSONArray jsonArray = jsonObject.getJSONArray("CustomerService");
                            if (jsonArray != null && jsonArray.length() >= 2) {
                                // QQ
                                JSONObject qqObj = jsonArray.getJSONObject(0);
                                if (qqObj != null) {
                                    String qqString = qqObj.get("QQ").toString();
                                    if (!TextUtils.isEmpty(qqString)) {
                                        List<Kefu> qqKefuList = StringTool.stringToList(qqString, Kefu.class);
                                        if (qqKefuList != null) {
                                            if (qqKefus != null && qqKefus.size() > 0) {
                                                qqKefus.clear();
                                            }
                                            qqKefus.addAll(qqKefuList);
                                            qqKefuAdapter.notifyDataSetChanged();
                                        }
                                    }
                                }

                                // 微信
                                JSONObject wechatObj = jsonArray.getJSONObject(1);
                                if (wechatObj != null) {
                                    String wechatString = wechatObj.get("微信").toString();
                                    if (!TextUtils.isEmpty(wechatString)) {
                                        List<WechatKefu> wechatKefuList = StringTool.stringToList(wechatString, WechatKefu.class);
                                        if (wechatKefuList != null) {
                                            if (wechatKefus != null && wechatKefus.size() > 0) {
                                                wechatKefus.clear();
                                            }
                                            wechatKefus.addAll(wechatKefuList);
                                            wechatKefuAdapter.notifyDataSetChanged();
                                        }
                                    }
                                }

                            } else {

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastTool.showShort(getActivity(), "获取数据失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取微信链接
     */
    private void getWeiXinUrl() {
        RequestParams params = new RequestParams(JoyUrl.URL_WEI_XIN);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject obj = StringTool.getUsefulObjectFromArray(jsonObject, "WeiXin");
                    if (obj != null) {
                        try {
                            weiXinUrl = obj.getString("Url").trim();
                            Glide.with(getActivity())
                                    .load(weiXinUrl)
                                    .into(iv_er_wei_ma_wechat);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取支付宝链接
     */
    private void getZhiFuBaoUrl() {
        RequestParams params = new RequestParams(JoyUrl.URL_ZHI_FU_BAO);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!TextUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject obj = StringTool.getUsefulObjectFromArray(jsonObject, "ZhiFuBao");
                        if (obj != null) {
                            try {
                                zhiFuBaoUrl = obj.getString("Url").trim();

                                Glide.with(getActivity())
                                        .load(zhiFuBaoUrl)
                                        .into(iv_er_wei_ma_alipay);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastTool.showShort(getActivity(), "获取数据失败");
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                //Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                //Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {


            default:
                break;
        }
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                ToastTool.showShort(getActivity(), "微信二维码已保存到sdcard/JinSha文件夹下");
            }

            if (msg.what == 2) {
                ToastTool.showShort(getActivity(), "支付宝二维码已保存到sdcard/JinSha文件夹下");
            }

            if (msg.what == 3) {
                ToastTool.showShort(getActivity(), "请等待图片加载完成");
            }
        }
    };

    /**
     * 保存图片到SD卡
     */
    public void saveMyBitmap(String fileName, Bitmap mBitmap) throws IOException {
        File tmp = new File(myJpgPath);
        if (!tmp.exists()) {
            tmp.mkdir();
        }
        File f = new File(myJpgPath+fileName);
        f.createNewFile();
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
