package hf.lskj.com.carstockcount.fragment;


import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import hf.lskj.com.carstockcount.MyApplication;
import hf.lskj.com.carstockcount.R;
import hf.lskj.com.carstockcount.adapter.VinAdapter;
import hf.lskj.com.carstockcount.db.CarInfo;
import hf.lskj.com.carstockcount.db.CarInfoDao;
import hf.lskj.com.carstockcount.db.Record;
import hf.lskj.com.carstockcount.db.RecordDao;
import hf.lskj.com.carstockcount.event.BindEvent;
import hf.lskj.com.carstockcount.utils.KeyBoardUtils;
import hf.lskj.com.carstockcount.utils.LogUtils;
import hf.lskj.com.carstockcount.utils.ToastUtils;
import hf.lskj.com.carstockcount.utils.UHF.Sound;
import hf.lskj.com.carstockcount.utils.UHF.UHFClient;
import hf.lskj.com.carstockcount.utils.UHF.UHFUtils;
import uhf.api.CommandType;
import uhf.api.Query_epc;
import uhf.api.ShareData;


public class BindFragment extends BaseFragment implements OnKeyDownInterface {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.tv_vin_title)
    TextView tvVinTitle;
    @Bind(R.id.tv_vin)
    AppCompatAutoCompleteTextView tvVin;
    @Bind(R.id.tv_rfid_title)
    TextView tvRfidTitle;
    @Bind(R.id.tv_rfid)
    TextView tvRfid;
    @Bind(R.id.bt_bind)
    Button btBind;
    @Bind(R.id.bt_unbind)
    Button btUnbind;
    private String mParam2;
    private CarInfoDao mCarInfoDao;
    private String mVin;
    private RecordDao mRecordDao;
    private Sound mSound;
    private ArrayAdapter<String> carsAdapter;
    private List<String> vinList = new ArrayList<>();
    private CarInfo mSelectedCar;

    public BindFragment() {
    }

    public static BindFragment newInstance(String vin, String param2) {
        BindFragment fragment = new BindFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, vin);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void setCarInfo(CarInfo carInfo) {
        setVin(carInfo.getVin());
    }

    public void setVin(String vin) {
        mVin = vin;
        tvVin.setText(mVin);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mVin = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mCarInfoDao = MyApplication.getInstances().getDaoSession().getCarInfoDao();
        mRecordDao = MyApplication.getInstances().getDaoSession().getRecordDao();
        mSound = new Sound(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_bind, container, false);
        ButterKnife.bind(this, rootView);
        if (!TextUtils.isEmpty(mVin)) {
            tvVin.setText(mVin);
        }
        List<CarInfo> cars = mCarInfoDao.queryBuilder().whereOr(CarInfoDao.Properties.Rfid.isNull(), CarInfoDao.Properties.Rfid.eq("")).list();

        vinList.clear();
        for (CarInfo car : cars) {
            vinList.add(car.getVin());
        }
        carsAdapter = new VinAdapter(getActivity(), android.R.layout.simple_dropdown_item_1line, vinList);
        tvVin.setAdapter(carsAdapter);
        tvVin.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mVin = carsAdapter.getItem(i);
                KeyBoardUtils.closeKeybord(getActivity());
            }
        });
        btBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //在扫描前,对vin码进行校验
                if (beforeQueryTags()) {
                    queryTags(true);
                }
            }
        });
        btUnbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                queryTags(false);
            }
        });

        tvVin.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    tvVin.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                } else {
                    tvVin.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.search_clear), null);

                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvVin.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //可以获得上下左右四个drawable，右侧排第二。图标没有设置则为空。
                Drawable rightIcon = tvVin.getCompoundDrawables()[2];
                if (rightIcon != null && event.getAction() == MotionEvent.ACTION_UP) {
                    //检查点击的位置是否是右侧的删除图标
                    //注意，使用getRwwX()是获取相对屏幕的位置，getX()可能获取相对父组件的位置
                    int leftEdgeOfRightDrawable = tvVin.getRight() - tvVin.getPaddingRight()
                            - rightIcon.getBounds().width();
                    if (event.getRawX() >= leftEdgeOfRightDrawable) {
                        tvVin.setText("");
                    }
                }
                return false;
            }
        });
        return rootView;
    }

    private boolean beforeQueryTags() {
        if (!tvVin.getText().toString().equals(mVin)) {
            if (tvVin.getText().length() > 0) {
                LogUtils.i("车辆VIN码不正确,mVin=" + mVin);
                Toast.makeText(getActivity(), "车辆VIN码不正确,请重新选择", Toast.LENGTH_SHORT).show();
                return false;
            }
            mVin = "";
        }
        if (TextUtils.isEmpty(mVin)) {
            Toast.makeText(getActivity(), "请先选择车辆VIN码", Toast.LENGTH_SHORT).show();
            return false;
        }
        mSelectedCar = mCarInfoDao.load(mVin);
        if (mSelectedCar != null) {
            if (!TextUtils.isEmpty(mSelectedCar.getRfid())) {
                ToastUtils.showShort("绑定失败:车辆已绑定,标签ID:" + mSelectedCar.getRfid());
                return false;
            }
        } else {
            Log.w("BindFragment", "根据vin" + mVin + "无法获得carInfo记录");
            ToastUtils.showShort("vin码有误,请重新选择!");
            return false;
        }
        return true;
    }

    private void queryTags(boolean isBind) {

        Query_epc mQuery_epc = new Query_epc();
        UHFClient info = UHFClient.getInstance();
        if (info != null) {

            Boolean ret = UHFClient.mUHF.command(CommandType.SINGLE_QUERY_TAGS_EPC, mQuery_epc);
            if (ret) {
                String str_tmp = ShareData.CharToString(mQuery_epc.epc.epc, mQuery_epc.epc.epc.length);
                str_tmp = str_tmp.replace(" ", "");
                LogUtils.i(str_tmp);
                if ("060D0A000000000000000000".equals(str_tmp) || "0D0A00000000000000000000".equals(str_tmp)) {
                    //不知道为什么 没有标签也能读出这个数据
                    mSound.callAlarm(false, 0);
                    return;
                } else if ("".equals(str_tmp)) {
                    mSound.callAlarm(false, 0);
                    ToastUtils.showShort("请对准标签扫描");
                    return;
                }
                tvRfid.setText(str_tmp);
                if (isBind) {
                    bind(str_tmp);
                } else {
                    unBind(str_tmp);
                }
                mSound.callAlarm(true, 0);
            } else {
                mSound.callAlarm(false, 0);
                ToastUtils.showShort("没有扫描到标签");
            }
        } else {
            LogUtils.i("info is null");
        }
    }

    private void bind(String rfid) {
        List<CarInfo> dbEntity = mCarInfoDao.queryBuilder().where(CarInfoDao.Properties.Rfid.eq(rfid)).list();
        if (dbEntity.size() > 0) {
            for (CarInfo carInfo : dbEntity) {
                if (mVin.equals(carInfo.getVin())) {
                    ToastUtils.showShort("绑定成功");
                    return;
                }
            }
            ToastUtils.showShort("绑定失败,此标签已绑定其他车辆:" + dbEntity.get(0).getVin());
            return;
        }
        mSelectedCar.setRfid(rfid);
        mSelectedCar.setStockCountTime(System.currentTimeMillis() + "");
        mSelectedCar.setStockCountType(Record.TYPE_BANGDING);
        if (mCarInfoDao.insertOrReplace(mSelectedCar) > 0) {
            Record record = new Record();
            record.setRfid(tvRfid.getText().toString());
            record.setVin(mVin);
            record.setCreateTime(System.currentTimeMillis() + "");
            record.setOperatorId(MyApplication.currentUser.getLoginId());
            record.setStoreId(mSelectedCar.getStoreId());
            record.setStatus(mSelectedCar.getStatus());
            record.setColor(mSelectedCar.getColor());
            record.setCarType(mSelectedCar.getType());
            record.setType(Record.TYPE_BANGDING);
            if (mRecordDao.insert(record) > 0) {
                vinList.remove(mVin);
                carsAdapter.notifyDataSetChanged();
                ToastUtils.showShort("绑定成功");
                EventBus.getDefault().post(new BindEvent(record.getRfid()));
            } else {
                Toast.makeText(getActivity(), "绑定失败!", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getActivity(), "绑定失败!", Toast.LENGTH_SHORT).show();
        }
    }

    private void unBind(final String rfid) {
        final CarInfo carInfo = mCarInfoDao.queryBuilder().where(CarInfoDao.Properties.Rfid.eq(rfid)).unique();
        if (carInfo == null) {
            ToastUtils.showShort("此标签尚未绑定");
        } else {
            tvVin.setText(carInfo.getVin());
            new AlertDialog.Builder(getActivity())
                    .setTitle("确定解绑吗?")
                    .setMessage("VIN码:\n" + carInfo.getVin() + "\n标签ID:\n" + rfid)
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Record record = new Record();
                            record.setRfid(carInfo.getRfid());
                            record.setVin(carInfo.getVin());
                            record.setStatus(carInfo.getStatus());
                            record.setCreateTime(System.currentTimeMillis() + "");
                            record.setOperatorId(MyApplication.currentUser.getLoginId());
                            record.setStoreId(carInfo.getStoreId());
                            record.setColor(carInfo.getColor());
                            record.setCarType(carInfo.getType());
                            record.setType(Record.TYPE_JIEBANG);
                            MyApplication.getInstances().getDb().beginTransaction();
                            if (mRecordDao.insertOrReplace(record) > 0) {
                                carInfo.setRfid("");
                                carInfo.setStockCountType(Record.TYPE_JIEBANG);
                                carInfo.setStockCountTime(System.currentTimeMillis() + "");
                                if (mCarInfoDao.insertOrReplace(carInfo) > 0) {
                                    ToastUtils.showShort("解绑成功");
                                    MyApplication.getInstances().getDb().setTransactionSuccessful();
                                } else {
                                    ToastUtils.showShort("解绑失败!");
                                }
                            } else {
                                ToastUtils.showShort("解绑失败!");
                            }
                            MyApplication.getInstances().getDb().endTransaction();
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void lazyLoad() {
        if (!isVisible) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                UHFUtils uhfUtils = new UHFUtils(getActivity());
                uhfUtils.handleSetPower(6);
            }
        }).run();
    }

    @Override
    public void onKeyDown(int keyCode, KeyEvent event) {
        btBind.callOnClick();
    }
}
