package com.mq.zhongzhuanzhuangche;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
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.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.zhongzhuanzhuangche.db.ZhongZhuanZhuangCheDao;
import com.mq.zhongzhuanzhuangche.db.ZhongZhuanZhuangCheEntity;

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

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

/**
 * 创建人 mQ
 * 创建时间 2019/8/22 0022 10:12
 * 文件名称 ZhuangCheActivity
 * 说明:  到站中转-汽车装车
 **/
public class ZhuangCheActivity extends BaseNfcActivity {

    @BindView(R.id.tv_pick_up_goods_count)
    TextView mTvPickUpGoodsCount;
    @BindView(R.id.tv_measure_type)
    TextView mTvMeasureType;
    @BindView(R.id.tv_finish_count)
    EditText mTvFinishCount;
    @BindView(R.id.et_single_weight)
    EditText mEtSingleWeight;
    @BindView(R.id.tv_finish_weight)
    TextView mTvFinishWeight;
    @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_start_time)
    TextView mTvStartTime;
    @BindView(R.id.tv_end_time)
    TextView mTvEndTime;
    @BindView(R.id.layout_single_weight)
    LinearLayout mLayoutSingleWeight;
    @BindView(R.id.layout_finish_weight)
    LinearLayout mLayoutFinishWeight;

    private ZhongZhuanZhuangCheEntity mEntity;

    private List<String> mTeamList = new ArrayList<>();
    private List<String> mGroupList = new ArrayList<>();
    private boolean saving;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuang_che);
        ButterKnife.bind(this);
        //取出读卡数据
        mEntity = (ZhongZhuanZhuangCheEntity) getIntent().getSerializableExtra("bean");
        //显示登录人名称
        String keeper = (String) SPTool.get(BaseConstant.REAL_NAME, "");
        mEtEntd.setText(keeper);
        //显示当前为作业时间
        String currenTime = DateTool.formatDate(DateTool.getCurrenTimeStamp(), DateTool.FULL_DATE);
        mTvStartTime.setText(currenTime);
        mTvEndTime.setText(currenTime);

        String measure_type = mEntity.measure_type;
        if (StringTool.notEmpty(measure_type) && measure_type.equals("称重")) {
            mLayoutSingleWeight.setVisibility(View.GONE);
            mLayoutFinishWeight.setVisibility(View.GONE);
        }
        ETTool.setData(mTvPickUpGoodsCount, mEntity.pick_up_goods_count);
        ETTool.setData(mTvMeasureType, mEntity.measure_type);
        mTvFinishCount.addTextChangedListener(mTextWatcher);
        mEtSingleWeight.addTextChangedListener(mTextWatcher);

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

    @SuppressLint("StaticFieldLeak")
    @OnClick({R.id.bar_back, R.id.bar_record, R.id.tv_work_team, R.id.tv_work_group,
            R.id.tv_start_time, R.id.tv_end_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_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_start_time:
                //开始时间
                showDateTimeDialog(mTvStartTime, ETTool.getData(mTvStartTime));
                break;
            case R.id.tv_end_time:
                //结束时间
                showDateTimeDialog(mTvEndTime, ETTool.getData(mTvEndTime));
                break;
            case R.id.btn_save:
//                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())
                                    .setCancelable(false)
                                    .setMessage("保存数据及写卡成功！")
                                    .setPositiveButton("完成", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    }).create().show();
                        } else {
                            ToastTool.showLong(cardData.msg);
                        }
                        saving = false;
                        cancelPd();
                    }
                }.execute();
                break;
        }
    }

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

        LogTool.i("汽车装车---开始写卡保存");
        mEntity.finish_count = (ETTool.getData(mTvFinishCount));
        mEntity.single_weight = (ETTool.getData(mEtSingleWeight));
        mEntity.finish_weight = (ETTool.getData(mTvFinishWeight));
        mEntity.work_team = (ETTool.getData(mTvWorkTeam));
        mEntity.work_group = (ETTool.getData(mTvWorkGroup));
        mEntity.entd = (ETTool.getData(mEtEntd));
        mEntity.start_time = (ETTool.getData(mTvStartTime));
        mEntity.end_time = (ETTool.getData(mTvEndTime));

        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 = ZhongZhuanZhuangCheDao.get().insert(App.getDBHelper(), mEntity);
            if (id > 0) {
                cardData.state = "0";
                cardData.msg = "写卡成功";
            }

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

    public SelAdapter.SelectListener mSelectListener = new SelAdapter.SelectListener() {
        @Override
        public void onSelectListener(View view, Set<SpinnerOption> selectList) {
            getSelPopupwindow(view, selectList);
            SpinnerOption option = selectList.iterator().next();
            switch (view.getId()) {
                case R.id.tv_work_team:
                    //选择作业队 把作业组旧选择置空
                    getGroupList();
                    mTvWorkGroup.setText("");
                    break;
            }
        }
    };

    private void getTeamList() {
        if (mTeamList.size() > 0)
            return;
        mTeamList.clear();
        List<TeamGroupEntity> list = TeamGroupDao.get().getTeamList(App.getDBHelper());
        if (list != null) {
            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);
            }
        }
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                double single = Double.valueOf(ETTool.getData(mEtSingleWeight));
                double finishCount = Double.valueOf(ETTool.getData(mTvFinishCount));
                mTvFinishWeight.setText((single * finishCount) + "");
            } catch (Exception e) {
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

}
