package com.mq.zhuangchefaka;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;

import com.mq.mylibrary.CardData;
import com.mq.mylibrary.base.BaseConstant;
import com.mq.mylibrary.base.BaseNfcActivity;
import com.mq.mylibrary.db.car.CarDao;
import com.mq.mylibrary.db.car.CarEntity;
import com.mq.mylibrary.db.grain_type.GrainTypeDao;
import com.mq.mylibrary.db.grain_type.GrainTypeEntity;
import com.mq.mylibrary.db.load_info.LoadInfoDao;
import com.mq.mylibrary.db.load_info.LoadInfoEntity;
import com.mq.mylibrary.db.team_group.TeamGroupDao;
import com.mq.mylibrary.db.team_group.TeamGroupEntity;
import com.mq.mylibrary.popupwindow.SpinnerOption;
import com.mq.mylibrary.popupwindow.adapter.SelAdapter;
import com.mq.mylibrary.tool.ActivityTool;
import com.mq.mylibrary.tool.DateTool;
import com.mq.mylibrary.tool.ETTool;
import com.mq.mylibrary.tool.LogTool;
import com.mq.mylibrary.tool.MusicTool;
import com.mq.mylibrary.tool.SPTool;
import com.mq.mylibrary.tool.StringTool;
import com.mq.mylibrary.tool.ToastTool;
import com.mq.zhuangchefaka.db.ZhuangCheDao;
import com.mq.zhuangchefaka.db.ZhuangCheEntity;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 创建人 mQ
 * 创建时间 2019/8/15 0015 19:51
 * 文件名称 ZhuangCheFaKaActivity
 * 说明:  火车入库-汽车装车
 **/
public class ZhuangCheFaKaActivity extends BaseNfcActivity {

    @BindView(R.id.tv_inbound_code)
    TextView mTvInboundCode;
    @BindView(R.id.tv_train_code)
    TextView mTvTrainCode;
    @BindView(R.id.tv_customer)
    TextView mTvCustomer;
    @BindView(R.id.tv_gain)
    TextView mTvGain;
    @BindView(R.id.tv_platform)
    TextView mTvPlatform;
    @BindView(R.id.tv_position)
    TextView mTvPosition;
    @BindView(R.id.tv_car)
    TextView mTvCar;
    @BindView(R.id.et_load_count)
    EditText mEtLoadCount;
    @BindView(R.id.tv_work_team)
    AutoCompleteTextView mTvWorkTeam;
    @BindView(R.id.tv_work_group)
    AutoCompleteTextView mTvWorkGroup;
    @BindView(R.id.et_entd)
    EditText mEtEntd;
    @BindView(R.id.tv_load_time)
    TextView mTvLoadTime;

    private List<SpinnerOption> mInboundList = new ArrayList<>();
    private List<SpinnerOption> mTrainList = new ArrayList<>();
    private List<SpinnerOption> mCarList = new ArrayList<>();
    private List<String> mTeamList = new ArrayList<>();
    private List<String> mGroupList = new ArrayList<>();

    private String mGrainId;

    private boolean saving;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuang_che_fa_ka);
        ButterKnife.bind(this);

        String currenTime = DateTool.formatDate(DateTool.getCurrenTimeStamp(), DateTool.FULL_DATE);
        mTvLoadTime.setText(currenTime);
        //显示登录人名称
        String keeper = (String) SPTool.get(BaseConstant.REAL_NAME, "");
        mEtEntd.setText(keeper);

        getTeamList();
        setAutoTextView(mTvWorkTeam, mTeamList);
        getGroupList();
        setAutoTextView(mTvWorkGroup, mGroupList);
    }

    private void getInboundCodeList() {
        if (mInboundList.size() > 0)
            return;
        mInboundList.clear();
        List<LoadInfoEntity> list = LoadInfoDao.get().getInboundCodeList(App.getDBHelper());
        if (list == null)
            return;
        for (LoadInfoEntity entity : list) {
            mInboundList.add(new SpinnerOption(entity.inbound_code, entity));
        }

    }

    private void getTrainCodeList() {
        mTrainList.clear();
        List<LoadInfoEntity> list = LoadInfoDao.get()
                .getTrainCodeList(App.getDBHelper(), ETTool.getData(mTvInboundCode));
        if (list == null)
            return;
        for (LoadInfoEntity entity : list) {
            mTrainList.add(new SpinnerOption(entity.train_code, entity));
        }
    }

    private void getCarList() {
        if (mCarList.size() > 0)
            return;
        mCarList.clear();
        List<CarEntity> list = CarDao.get().getList(App.getDBHelper());
        if (list == null)
            return;
        for (CarEntity entity : list) {
            mCarList.add(new SpinnerOption(entity.car_number));
        }
    }

    @SuppressLint("StaticFieldLeak")
    @OnClick({R.id.bar_back, R.id.bar_record, R.id.tv_inbound_code, R.id.tv_train_code,
            R.id.tv_car, R.id.tv_work_team, R.id.tv_work_group, R.id.tv_load_time, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bar_back:
                onBackPressed();
                break;
            case R.id.bar_record:
                //记录/补卡
                ActivityTool.startActivity(getContext(), LogActivity.class);
                break;
            case R.id.tv_inbound_code:
                //入站单号
                getInboundCodeList();
                showListPopupwindow(mTvInboundCode, mInboundList, mSelectListener);
                break;
            case R.id.tv_train_code:
                //火车皮号
                if (StringTool.isEmpty(ETTool.getData(mTvInboundCode))) {
                    ToastTool.showLong("请选择入站单号");
                    mTvInboundCode.setError("请选择入站单号");
                    return;
                }
                showListPopupwindow(mTvTrainCode, mTrainList, mSelectListener);
                break;
            case R.id.tv_car:
                //车辆编号
                getCarList();
                showListPopupwindow(mTvCar, mCarList, mSelectListener);
                break;
            case R.id.tv_work_team:
                //作业队
//                getTeamList();
//                showListPopupwindow(mTvWorkTeam, mTeamList, mSelectListener);
                mTvWorkTeam.showDropDown();
                break;
            case R.id.tv_work_group:
                //作业组
//                if (StringTool.isEmpty(ETTool.getData(mTvWorkTeam))) {
//                    ToastTool.showLong("请选择作业队");
//                    mTvWorkTeam.setError("请选择作业队");
//                    return;
//                }
//                showListPopupwindow(mTvWorkGroup, mGroupList, mSelectListener);\
                mTvWorkGroup.showDropDown();
                break;
            case R.id.tv_load_time:
                //装车时间
                showDateTimeDialog(mTvLoadTime, ETTool.getData(mTvLoadTime));
                break;
            case R.id.btn_save:
                if (StringTool.isEmpty(ETTool.getData(mTvInboundCode))) {
                    ToastTool.showLong("请选择入站单号");
                    mTvInboundCode.setError("请选择入站单号");
                    return;
                }
                if (StringTool.isEmpty(ETTool.getData(mTvTrainCode))) {
                    ToastTool.showLong("请选择关联火车皮号");
                    mTvTrainCode.setError("请选择关联火车皮号");
                    return;
                }
                if (StringTool.isEmpty(ETTool.getData(mTvCar))) {
                    ToastTool.showLong("请选择车辆编号");
                    mTvCar.setError("请选择车辆编号");
                    return;
                }
//                if (StringTool.isEmpty(ETTool.getData(mTvWorkTeam))) {
//                    ToastTool.showLong("请选择作业队");
//                    mTvWorkTeam.setError("请选择作业队");
//                    return;
//                }
//                if (StringTool.isEmpty(ETTool.getData(mTvWorkGroup))) {
//                    ToastTool.showLong("请选择作业组");
//                    mTvWorkGroup.setError("请选择作业组");
//                    return;
//                }
                if (StringTool.isEmpty(ETTool.getData(mEtEntd))) {
                    ToastTool.showLong("请输入登记人");
                    mEtEntd.setError("请输入登记人");
                    return;
                }

                if (saving) {
                    return;
                }
                saving = true;
                showPd();
                new AsyncTask<Void, Void, CardData>() {
                    @Override
                    protected CardData doInBackground(Void... voids) {
                        return save();
                    }

                    @Override
                    protected void onPostExecute(CardData cardData) {
                        super.onPostExecute(cardData);
                        if (cardData.state.equals("0")) {
                            ToastTool.showLong("保存数据及写卡成功！");
                            MusicTool.load(getContext());
                            new AlertDialog.Builder(getContext())
                                    .setMessage("保存数据及写卡成功！")
                                    .setPositiveButton("完成", null)
                                    .create().show();
                        } else {
                            ToastTool.showLong(cardData.msg);
                        }
                        saving = false;
                        cancelPd();
                    }
                }.execute();
                break;
        }
    }

    private void getTeamList() {
        if (mTeamList.size() > 0)
            return;
        mTeamList.clear();
        List<TeamGroupEntity> list = TeamGroupDao.get().getTeamList(App.getDBHelper());
        if (list == null)
            return;
        for (TeamGroupEntity entity : list) {
            mTeamList.add(entity.work_team);
        }
    }

    private void getGroupList() {
        mGroupList.clear();
        List<TeamGroupEntity> list = TeamGroupDao.get()
                .getGroupList(App.getDBHelper());
        if (list != null) {
            for (TeamGroupEntity entity : list) {
                mGroupList.add(entity.work_group);
            }
        }
    }

    SelAdapter.SelectListener mSelectListener = new SelAdapter.SelectListener() {
        @Override
        public void onSelectListener(View view, Set<SpinnerOption> selectList) {
            getSelPopupwindow(view, selectList);
            switch (view.getId()) {
                case R.id.tv_inbound_code:
                    getTrainCodeList();
                    mTvTrainCode.setText("");
                    mTvCustomer.setText("");
                    mTvGain.setText("");
                    mTvPlatform.setText("");
                    mTvPosition.setText("");
                    break;
                case R.id.tv_train_code:
                    SpinnerOption option = selectList.iterator().next();
                    LoadInfoEntity value = (LoadInfoEntity) option.value;
                    mTvCustomer.setText(value.customer);
                    GrainTypeEntity grain = GrainTypeDao.get().getGrain(App.getDBHelper(), value.grain_id);
                    mGrainId = grain.grain_id;
                    mTvGain.setText(grain.grain_name);
                    mTvPlatform.setText(value.platform_name);
                    mTvPosition.setText(value.position_name);
                    break;
                case R.id.tv_work_team:
                    //选择作业队 把作业组旧选择置空
                    getGroupList();
                    mTvWorkGroup.setText("");
                    break;
            }
        }
    };

    private CardData save() {
        CardData cardData = new CardData();
        cardData.state = "4";
        cardData.msg = "保存或写卡失败";

        LogTool.i("装车发卡---开始写卡保存");
        ZhuangCheEntity mEntity = new ZhuangCheEntity();
        mEntity.inbound_code = (ETTool.getData(mTvInboundCode));
        mEntity.train_code = (ETTool.getData(mTvTrainCode));
        mEntity.customer = (ETTool.getData(mTvCustomer));
        mEntity.grain_id = (mGrainId);
        mEntity.platform_name = (ETTool.getData(mTvPlatform));
        mEntity.position_name = (ETTool.getData(mTvPosition));
        mEntity.car = (ETTool.getData(mTvCar));
        mEntity.finish_count = (ETTool.getData(mEtLoadCount));
        mEntity.work_team = (ETTool.getData(mTvWorkTeam));
        mEntity.work_group = (ETTool.getData(mTvWorkGroup));
        mEntity.entd = (ETTool.getData(mEtEntd));
        mEntity.load_time = (ETTool.getData(mTvLoadTime));
        mEntity.grain = (ETTool.getData(mTvGain));

        String cardInfo = mEntity.getWriteData();
        LogTool.i("装车发卡---写卡：" + cardInfo);
        try {
            //写卡
            String s = writeTag(cardInfo);
            if (!s.equals("")) {
                cardData.msg = s;
                if (!App.isSkipCard)//跳过卡片时不返回错误信息
                    return cardData;
            }
            //保存数据
            LogTool.i("装车发卡---写入数据库");
            long id = ZhuangCheDao.get().insert(App.getDBHelper(), mEntity);
            if (id > 0) {
                cardData.state = "0";
                cardData.msg = "写卡成功";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return cardData;
    }
}
