package com.ifavine.pay.ui.activity;

import android.app.Dialog;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ifavine.pay.R;
import com.ifavine.pay.api.APIWrapper;
import com.ifavine.pay.ui.base.BaseActivity;
import com.ifavine.pay.utils.BaseUtil;
import com.ifavine.pay.utils.DialogMainSetUtils;
import com.ifavine.pay.utils.DialogUtil;
import com.ifavine.pay.utils.SPUtil;
import com.ifavine.pay.utils.TLog;
import com.ifavine.pay.view.PopWindowMainReport;
import com.ifavine.pay.view.PopWindowMainSet;
import com.ifavine.pay.view.datepicker.DateUtil;
import com.ifavine.pay.vo.CanteenWindow;
import com.ifavine.pay.vo.CommonListResponse;
import com.ifavine.pay.vo.CommonResponse;
import com.ifavine.pay.vo.WindowCostAmount;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Administrator
 */


public class MainActivity extends BaseActivity {
    @BindView(R.id.tv_date)
    TextView tv_date;

    @BindView(R.id.tv_set)
    Button tv_set;
    @BindView(R.id.tv_net)
    TextView tv_net;
    @BindView(R.id.tv_table)
    Button tv_table;
    @BindView(R.id.et_payCode)
    EditText et_payCode;

    @BindView(R.id.tv_EmpNo)
    TextView tv_EmpNo;
    @BindView(R.id.tv_EmpName)
    TextView tv_EmpName;
    @BindView(R.id.tv_EmpDept)
    TextView tv_EmpDept;
    @BindView(R.id.tv_EmpDuty)
    TextView tv_EmpDuty;
    @BindView(R.id.tv_Cost)
    TextView tv_Cost;
    @BindView(R.id.tv_SubCost)
    TextView tv_SubCost;

    @BindView(R.id.tv_Consumption)
    TextView tv_Consumption;
    @BindView(R.id.tv_IsConsumed)
    TextView tv_IsConsumed;
    @BindView(R.id.tv_TradeNo)
    TextView tv_TradeNo;

    @BindView(R.id.tv_WindowName)
    TextView tv_WindowName;

    @BindView(R.id.tv_CanteenName)
    TextView tv_CanteenName;
    @BindView(R.id.tv_pay_status)
    TextView tv_pay_status;


    @BindView(R.id.t_AllowanceAmount)
    TextView t_AllowanceAmount;
    @BindView(R.id.t_DinnerAmount)
    TextView t_DinnerAmount;
    @BindView(R.id.t_DinnerType)
    TextView t_DinnerType;
    @BindView(R.id.tv_self)
    TextView tv_self;
    @BindView(R.id.btn_pay)
    Button btn_pay;


    private int soundSucess;
    private int soundFail;
    private SoundPool soundPool;
    private String payCode = "";

    private PopWindowMainSet popWindowMainSet;
    private PopWindowMainReport popWindowMainReport;
    private static int Current_Count_PopWindow = 0;
    public static int Current_Count_DialogInput = 0;
    private Dialog dialogInput = null;
    public static int Current_Count_DialogWindow = 0;
    private Dialog dialogWindow = null;

    private static boolean isStart = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //无title
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);


        //支付提示
        soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 100);
        soundSucess = soundPool.load(mContext, R.raw.success, 1);//加载资源，得到soundId
        soundFail = soundPool.load(mContext, R.raw.fail, 1);//加载资源，得到soundId
        dateTime = 0;
        //获取窗口信息
        GetCanteenWindows();

        //获取支付信息
        GetWindowCostAmount();
        //第一次使用设置窗口
        String WindowName = SPUtil.getInstance().readString("WindowName");
        if (TextUtils.isEmpty(WindowName)) {
            DialogUtil.showOkDialog(mContext, null, "设置信息", "请设置饭堂窗口和消费金额", "确定", null);
        }

    }


    @Override
    public void initData() {
        super.initData();
    }

    private Runnable netRun = new Runnable() {
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    pingNet("121.33.220.19");
                }
            }).start();
            initPayInfo();
            et_payCode.requestFocus();
            if (dateTime == 0) {
                getServerDate();
            }
            Current_Count++;
            if (Current_Count >= MAX_Mi) {
                setSCREEN_OFF_TIMEOUT();
            }
            handler.postDelayed(this, 60 * 1000);
        }
    };

    private static String lastCode;
    private static String code;
    private Runnable etRunnable = new Runnable() {
        @Override
        public void run() {
            code = et_payCode.getText().toString();
            if (!TextUtils.isEmpty(code)) {
                if (code.equals(lastCode)) {
                    doPay(code);
                }
                lastCode = code;
            }
            handler.postDelayed(this, 300);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        updateCanTeenName();
        getServerDate();
        initPayInfo();
        //检查网络
        Current_Count = 0;
        startTimer();
        if (!isStart) {
            handler.postDelayed(netRun, 1000);
            handler.postDelayed(etRunnable, 250);
        }
        isStart = true;
        Log.e("love", "onResume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        isStart = false;
        stopTimer();
        handler.removeCallbacks(netRun);
        handler.removeCallbacks(etRunnable);
        Log.e("love", "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
        isStart = false;
        handler.removeCallbacks(netRun);
        handler.removeCallbacks(etRunnable);
    }

    private boolean pingNet(String address) {
        try {
            Process process = Runtime.getRuntime().exec("ping -c 3 -w 100 " + address);
            InputStreamReader r = new InputStreamReader(process.getInputStream());
            LineNumberReader returnData = new LineNumberReader(r);
            String returnMsg = "";
            String line = "";
            while ((line = returnData.readLine()) != null) {
                System.out.println(line);
                returnMsg += line;
            }
            if (TextUtils.isEmpty(returnMsg)) {
                System.out.println("与 " + address + " 连接不畅通.");
                handler.sendEmptyMessage(2);
                return false;
            } else {
                //0 received, 100% packet loss
                if (returnMsg.indexOf("0 received") == 1 || returnMsg.indexOf("100% packet loss") == 1) {
                    System.out.println("与 " + address + " 连接不畅通.");
                    handler.sendEmptyMessage(2);
                    return false;
                } else {
                    System.out.println("与 " + address + " 连接畅通.");
                    handler.sendEmptyMessage(3);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @OnClick({R.id.tv_set, R.id.tv_table, R.id.tv_close, R.id.tv_reflesh, R.id.btn_pay})
    public void onClick(View view) {
        Current_Count = 0;
        switch (view.getId()) {
            case R.id.tv_set:
                Current_Count_PopWindow = 0;
                popWindowMainSet = new PopWindowMainSet(mContext, new PopWindowMainSet.CallBackPosition() {
                    @Override
                    public void selectIndex(int i) {
                        if (i == 0) {
                            Current_Count_DialogInput = 0;
                            dialogInput = DialogMainSetUtils.showRSTSetDialog(mContext, "饭堂窗口设置", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    updateCanTeenName();
                                    initPayInfo();
                                }
                            }, null, true);
                        } else if (i == 1) {
                            Current_Count_DialogWindow = 0;
                            dialogWindow = DialogMainSetUtils.showSetAmtDialog(mContext, "消费金额设置", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    initPayInfo();
                                }
                            }, null, true);
                        } else if (i == 2) {
                            Current_Count_DialogInput = 0;
                            dialogInput = DialogMainSetUtils.showChangePwdDialog(mContext, "修改管理员密码", null, null, true);
                        }
                    }
                });
                popWindowMainSet.showAtBottom(tv_set);
                break;
            case R.id.tv_table:
                Current_Count_PopWindow = 0;
                popWindowMainReport = new PopWindowMainReport(mContext, new PopWindowMainReport.CallBackPosition() {
                    @Override
                    public void selectIndex(final int index) {
                        if (index == 0) {
                            Current_Count_DialogWindow = 0;
                            dialogWindow = DialogMainSetUtils.showReportLocalDialog(mContext, "本机消费记录查询", null, true);
                        } else if (index == 1) {
                            Current_Count_DialogWindow = 0;
                            dialogWindow = DialogMainSetUtils.showReportRecordDialog(mContext, "消费记录查询", null, true);
                        } else if (index == 2) {
                            Current_Count_DialogInput = 0;
                            dialogInput = DialogUtil.showInputDialog(mContext, null, "请输入管理员密码", "请输入管理员密码", "确定", "取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Current_Count_DialogWindow = 0;
                                    dialogWindow = DialogMainSetUtils.showReportSumDialog(mContext, "每月消费汇总查询", null, true);
                                }
                            }, null, true);
                        }
                    }
                });
                popWindowMainReport.showAtBottom(tv_table);
                break;
            case R.id.tv_close:
                Current_Count_DialogInput = 0;
                dialogInput = DialogUtil.showConfirmDialog(mContext, null, "系统提示", "确认关闭应用?", "确定", "取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        System.exit(0);
                    }
                }, null, true);
                break;
            case R.id.tv_reflesh:
                getServerDate();
                GetCanteenWindows();
                GetWindowCostAmount();
                break;
            case R.id.btn_pay:
                String code = et_payCode.getText().toString();
                if (!TextUtils.isEmpty(code) && !payCode.equals(code)) {
                    doPay(code);
                }
                break;
        }
    }


    // 初始化定时器
    private long dateTime;
    private Timer timer;

    private void startTimer() {
        if (timer != null) {
            return;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                dateTime += 1000;
                Current_Count_PopWindow++;
                if (Current_Count_PopWindow > 10) {
                    Current_Count_PopWindow = 0;
                    handler.sendEmptyMessage(4);
                }
                Current_Count_DialogInput++;
                if (Current_Count_DialogInput > 10) {
                    Current_Count_DialogInput = 0;
                    handler.sendEmptyMessage(5);
                }
                Current_Count_DialogWindow++;
                if (Current_Count_DialogWindow > 20) {
                    Current_Count_DialogWindow = 0;
                    handler.sendEmptyMessage(6);
                }
                handler.sendEmptyMessage(1);
            }
        }, 1000, 1000);
    }

    // 停止定时器
    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            // 一定设置为null，否则定时器不会被回收
            timer = null;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (dateTime != 0) {
                        tv_date.setText(BaseUtil.getDateFormat(dateTime, "yyyy-MM-dd HH:mm:ss"));
                    }
                    break;
                case 2:
                    tv_net.setText("网络错误!");
                    tv_net.setTextColor(getResources().getColor(R.color.red));
                    break;
                case 3:
                    tv_net.setText("网络畅通");
                    tv_net.setTextColor(getResources().getColor(R.color.green));
                    break;
                case 4:
                    if (popWindowMainSet != null && popWindowMainSet.isShowing()) {
                        popWindowMainSet.dismiss();
                    }
                    if (popWindowMainReport != null && popWindowMainReport.isShowing()) {
                        popWindowMainReport.dismiss();
                    }
                    break;
                case 5:
                    if (dialogInput != null && dialogInput.isShowing()) {
                        dialogInput.dismiss();
                    }
                    break;
                case 6:
                    DialogUtil.dismissTipDialog();
                    if (dialogWindow != null && dialogWindow.isShowing()) {
                        dialogWindow.dismiss();
                    }
                    break;


            }
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.e("love", "onTouchEvent");
        Current_Count = 0;
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.e("love", "dispatchTouchEvent");
        Current_Count = 0;
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.e("love", "onKeyUp");
        Current_Count = 0;
        return super.onKeyUp(keyCode, event);
    }

    public void updateCanTeenName() {
        String CanTeenCode = SPUtil.getInstance().readString("CanTeenCode");
        String WindowName = SPUtil.getInstance().readString("WindowName");
        String CanTeenName = SPUtil.getInstance().readString("CanTeenName");
        tv_CanteenName.setText(CanTeenName);
        tv_WindowName.setText(WindowName);
    }


    //线路处理
    private void getServerDate() {
        Call<CommonResponse<String>> call =
                APIWrapper.getInstance().getServerDate();
        call.enqueue(new Callback<CommonResponse<String>>() {
            @Override
            public void onResponse(Call<CommonResponse<String>> call,
                                   Response<CommonResponse<String>> response) {
                if (response.isSuccessful()) {
                    if (response.body() == null) {
                        return;
                    }
                    if (response.body().Status != 200) {
                        return;
                    }
                    String data = response.body().ModelJson;
                    TLog.log("aaa", data);
                    dateTime = BaseUtil.getDateFormat(data, "yyyy/MM/dd hh:mm:ss");
                    initPayInfo();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse<String>> call, Throwable t) {

            }
        });
    }

    /**
     * PayCode：用户微信支付码
     * Mac：终端的mac地址,格式是使用 “:” 分隔
     * DeviceNo：设备编号,可自己设定格式 ,微信支付时用到
     *
     * @param payCode
     */
    //线路处理
    private void doPay(String payCode) {
        Current_Count = 0;
        et_payCode.setText(null);
        et_payCode.requestFocus();
        tv_EmpNo.setText(null);
        tv_EmpName.setText(null);
        tv_EmpDuty.setText(null);
        tv_EmpDept.setText(null);
        tv_SubCost.setText(null);
        tv_Consumption.setText(null);
        tv_Cost.setText(null);
        tv_IsConsumed.setText(null);
        tv_TradeNo.setText(null);
        tv_pay_status.setText("支付中...");
        tv_pay_status.setTextColor(getResources().getColor(R.color.font_black_20));

        String Mac = SPUtil.getInstance().readString("Mac");
        String DeviceNo = SPUtil.getInstance().readString("DeviceNo");
        Call<CommonResponse<String>> call =
                APIWrapper.getInstance().SubmitPaying(payCode, Mac, DeviceNo);
        call.enqueue(new Callback<CommonResponse<String>>() {
            @Override
            public void onResponse(Call<CommonResponse<String>> call,
                                   Response<CommonResponse<String>> response) {
                if (response.isSuccessful()) {
                    if (response.body() == null) {
                        return;
                    }
                    if (response.body() != null) {
                        tv_EmpNo.setText(response.body().EmpNo);
                        tv_EmpName.setText(response.body().EmpName);
                        tv_EmpDuty.setText(response.body().EmpDuty);
                        tv_EmpDept.setText(response.body().EmpDept);
                        tv_SubCost.setText(response.body().SubCost);
                        tv_Consumption.setText(response.body().Consumption);
                        tv_Cost.setText(response.body().Cost);
                        tv_IsConsumed.setText(response.body().IsConsumed);
                        tv_TradeNo.setText(response.body().TradeNo);
                    }
                    if (response.body().Status == 200) {
                        soundPool.play(soundSucess, 1, 1, 0, 0, 1);
                        tv_pay_status.setText("支付成功");
                        tv_pay_status.setTextColor(getResources().getColor(R.color.green));
                    } else {
                        soundPool.play(soundFail, 1, 1, 0, 0, 1);
                        tv_pay_status.setText(response.body().Message);
                        tv_pay_status.setTextColor(getResources().getColor(R.color.red));
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse<String>> call, Throwable t) {
                soundPool.play(soundFail, 1, 1, 0, 0, 1);
                tv_pay_status.setText("支付失败");
                tv_pay_status.setTextColor(getResources().getColor(R.color.red));
            }
        });
    }

    Gson gson = new Gson();

    //线路处理
    private void GetCanteenWindows() {
        String Mac = SPUtil.getInstance().readString("Mac");
        Call<CommonListResponse<CanteenWindow>> call =
                APIWrapper.getInstance().GetCanteenWindows(Mac);
        call.enqueue(new Callback<CommonListResponse<CanteenWindow>>() {
            @Override
            public void onResponse(Call<CommonListResponse<CanteenWindow>> call,
                                   Response<CommonListResponse<CanteenWindow>> response) {
                if (response.isSuccessful()) {
                    if (response.body() == null) {
                        return;
                    }
                    if (response.body().Status != 200) {
                        return;
                    }
                    List<CanteenWindow> data = response.body().ModelJson;
                    TLog.log("aaa", response.body().toString());
                    String jsonApp = gson.toJson(data);
                    SPUtil.getInstance().writeString("CanteenWindows", jsonApp);
                }
            }

            @Override
            public void onFailure(Call<CommonListResponse<CanteenWindow>> call, Throwable t) {

            }
        });
    }


    private void GetWindowCostAmount() {
        String Mac = SPUtil.getInstance().readString("Mac");
        Call<CommonListResponse<WindowCostAmount>> call =
                APIWrapper.getInstance().GetWindowCostAmount(Mac);
        call.enqueue(new Callback<CommonListResponse<WindowCostAmount>>() {
            @Override
            public void onResponse(Call<CommonListResponse<WindowCostAmount>> call,
                                   Response<CommonListResponse<WindowCostAmount>> response) {
                if (response.isSuccessful()) {
                    if (response.body() == null) {
                        return;
                    }
                    if (response.body().Status != 200) {
                        return;
                    }
                    List<WindowCostAmount> data = response.body().ModelJson;
                    TLog.log("aaa", response.body().toString());
                    String jsonApp = gson.toJson(data);
                    SPUtil.getInstance().writeString("WindowCostAmounts", jsonApp);
                    initPayInfo();
                }
            }

            @Override
            public void onFailure(Call<CommonListResponse<WindowCostAmount>> call, Throwable t) {

            }
        });
    }

    private void initPayInfo() {
        if (dateTime == 0) {
            return;
        }
        String data = SPUtil.getInstance().readString("WindowCostAmounts");
        if (TextUtils.isEmpty(data)) {
            return;
        }
        final List<WindowCostAmount> DATA = gson.fromJson(data, new TypeToken<List<WindowCostAmount>>() {
        }.getType());
        for (int i = 0; i < 4; i++) {
            if (getTimeCompare(DATA.get(i).StartTime, DATA.get(i).EndTime)) {
                if ("1".equals(DATA.get(i).DinnerType)) {
                    t_DinnerType.setText("早餐");
                } else if ("2".equals(DATA.get(i).DinnerType)) {
                    t_DinnerType.setText("午餐");
                } else if ("3".equals(DATA.get(i).DinnerType)) {
                    t_DinnerType.setText("晚餐");
                } else if ("4".equals(DATA.get(i).DinnerType)) {
                    t_DinnerType.setText("夜宵");
                }
                t_AllowanceAmount.setText(DATA.get(i).AllowanceAmount + "");
                t_DinnerAmount.setText(DATA.get(i).DinnerAmount + "");
                tv_self.setText((DATA.get(i).DinnerAmount - DATA.get(i).AllowanceAmount) + "");
                return;
            }
            if (i == 3) {
                t_DinnerType.setText("夜宵");
                t_AllowanceAmount.setText(DATA.get(i).AllowanceAmount + "");
                t_DinnerAmount.setText(DATA.get(i).DinnerAmount + "");
                tv_self.setText((DATA.get(i).DinnerAmount - DATA.get(i).AllowanceAmount) + "");
            }
        }
    }


    private boolean getTimeCompare(String start, String end) {
        String date = DateUtil.formatDate(dateTime, "yyyy-MM-dd");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startDate = date + " " + start + ":00";
        String endDate = date + " " + end + ":59";
        try {
            Date s = df.parse(startDate);
            Date e = df.parse(endDate);
            if (s.getTime() < dateTime && dateTime < e.getTime()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private final static int MAX_Mi = 10;
    private int Current_Count = 0;

    /**
     * 设置锁屏 60分钟没有消费操作锁屏
     */
    private void setSCREEN_OFF_TIMEOUT() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        // Settings.System.putInt(getContentResolver(), android.provider.Settings.System.SCREEN_OFF_TIMEOUT, 10 * 1000);
    }

    //窗口计时处理
}
