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.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 = "";

    @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);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //支付提示
        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);
        }

    }

    boolean isSend = false;

    @Override
    public void initData() {
        super.initData();
        //检查网络
        handler.postDelayed(netRun, 1000);
        handler.postDelayed(etRunnable, 250);
        et_payCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    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();
            }
            handler.postDelayed(this, 60 * 1000);
        }
    };

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

    @Override
    protected void onResume() {
        super.onResume();
        updateCanTeenName();
        getServerDate();
        initPayInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
        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) {
        switch (view.getId()) {
            case R.id.tv_set:
                new PopWindowMainSet(mContext, new PopWindowMainSet.CallBackPosition() {
                    @Override
                    public void selectIndex(int i) {
                        if (i == 0) {
                            DialogMainSetUtils.showRSTSetDialog(mContext, "饭堂窗口设置", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    updateCanTeenName();
                                    initPayInfo();
                                }
                            }, null, true);
                        } else if (i == 1) {
                            DialogMainSetUtils.showSetAmtDialog(mContext, "消费金额设置", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    initPayInfo();
                                }
                            }, null, true);
                        } else if (i == 2) {
                            DialogMainSetUtils.showChangePwdDialog(mContext, "修改管理员密码", null, null, true);
                        }
                    }
                }).showAtBottom(tv_set);
                break;
            case R.id.tv_table:
                new PopWindowMainReport(mContext, new PopWindowMainReport.CallBackPosition() {
                    @Override
                    public void selectIndex(final int index) {
                        if (index == 0) {
                            DialogMainSetUtils.showReportLocalDialog(mContext, "本机消费记录查询", null, true);
                        } else if (index == 1) {
                            DialogMainSetUtils.showReportRecordDialog(mContext, "消费记录查询", null, true);
                        } else if (index == 2) {
                            DialogUtil.showInputDialog(mContext, null, "请输入管理员密码", "请输入管理员密码", "确定", "取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    DialogMainSetUtils.showReportSumDialog(mContext, "每月消费汇总查询", null, true);
                                }
                            }, null, true);
                        }
                    }
                }).showAtBottom(tv_table);
                break;
            case R.id.tv_close:
                dialog = 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();
                break;
            case R.id.btn_pay:
                String code = et_payCode.getText().toString();
                if (!TextUtils.isEmpty(code) && !payCode.equals(code)) {
                    doPay(code);
                }
                break;
        }
    }

    Dialog dialog = null;

    // 初始化定时器
    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;
                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:
                    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;


            }
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.e("ggg", "onTouchEvent");
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.e("ggg", "dispatchTouchEvent");
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.e("ggg", "onKeyUp");
        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");
                    startTimer();
                    initPayInfo();
                }
            }

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

            }
        });
    }

    /**
     * PayCode：用户微信支付码
     * Mac：终端的mac地址,格式是使用 “:” 分隔
     * DeviceNo：设备编号,可自己设定格式 ,微信支付时用到
     *
     * @param payCode
     */
    //线路处理
    private void doPay(String payCode) {
        et_payCode.setText(null);
        et_payCode.requestFocus();
        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().Status == 200) {
                        soundPool.play(soundSucess, 1, 1, 0, 0, 1);
                        tv_pay_status.setText("支付成功");
                        tv_pay_status.setTextColor(getResources().getColor(R.color.green));
                        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);
                    } 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");
        String startDate = date + " " + start;
        String endDate = date + " " + end;
        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;
    }

}
