package com.mq.zhicang.shanxi;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
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.Switch;
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.sotre.StoreDao;
import com.mq.mylibrary.db.sotre.StoreEntity;
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.zhicang.App;
import com.mq.zhicang.LogActivity;
import com.mq.zhicang.R;
import com.mq.zhicang.db.ZhiCangDao;
import com.mq.zhicang.db.ZhiCangEntity;

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

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

/**
 * 填写值仓信息-山西
 * 创建人: mQ
 * 时间: 2021/1/4 9:57
 */
public class WriteShanxiActivity extends BaseNfcActivity {

    @BindView(R.id.tv_real_house)
    TextView mTvRealHouse;
    @BindView(R.id.tv_real_position)
    TextView mTvRealPosition;
    @BindView(R.id.tv_pack_type)
    TextView mTvPackType;
    @BindView(R.id.et_finish_count)
    EditText mEtFinishCount;
    @BindView(R.id.et_deduct_water)
    EditText mEtDeductWater;
    @BindView(R.id.et_deduct_sundries)
    EditText mEtDeductSundries;
    @BindView(R.id.et_deduct_other)
    EditText mEtDeductOther;
    @BindView(R.id.et_deduct_pack)
    EditText mEtDeductPack;
    @BindView(R.id.et_deduct_percent)
    EditText mEtDeductPercent;
    @BindView(R.id.tv_work_team)
    AutoCompleteTextView mTvWorkTeam;
    @BindView(R.id.tv_work_group)
    AutoCompleteTextView mTvWorkGroup;
    @BindView(R.id.et_keeper)
    EditText mEtKeeper;
    @BindView(R.id.et_remark)
    EditText mEtRemark;
    @BindView(R.id.switch_sfhz)
    Switch mSwitchSfhz;

    private ZhiCangEntity mEntity;

    private List<SpinnerOption> houseList;
    private List<SpinnerOption> positionList = new ArrayList<>();
    private List<String> mTeamList = new ArrayList<>();
    private List<String> mGroupList = new ArrayList<>();

    private List<SpinnerOption> packList = Arrays.asList(
            new SpinnerOption("散装"),
            new SpinnerOption("袋装"),
            new SpinnerOption("集装箱"),
            new SpinnerOption("混合")
    );

    private String mSelHouseId;
    private String mSelPositionId;
    private boolean saving;

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

        //取出读卡数据
        mEntity = (ZhiCangEntity) getIntent().getSerializableExtra("bean");
        //显示登录人名称
        String keeper = (String) SPTool.get(BaseConstant.REAL_NAME, "");
        mEtKeeper.setText(keeper);
        //显示当前为作业时间
        String currenTime = DateTool.formatDate(DateTool.getCurrenTimeStamp(), DateTool.FULL_DATE);
        mEntity.start_time = currenTime;
        mEntity.end_time = currenTime;

        //将拟仓房选为实际仓房
        getHouseList();
        for (SpinnerOption house : houseList) {
            if (house.name.equals(mEntity.plan_house)) {
                mTvRealHouse.setText(house.name);
                mSelHouseId = (String) house.value;
                break;
            }
        }

        //将拟货位选为实际货位
        LogTool.i("选择的仓房：" + mTvRealHouse.getText().toString());
        getPositionList();
        for (SpinnerOption position : positionList) {
            if (position.name.equals(mEntity.plan_position)) {
                mTvRealPosition.setText(position.name);
                mSelPositionId = (String) position.value;
                break;
            }
        }

        getTeamList();
        setAutoTextView(mTvWorkTeam, mTeamList);

        getGroupList();
        setAutoTextView(mTvWorkGroup, mGroupList);


    }

    @SuppressLint("StaticFieldLeak")
    @OnClick({R.id.bar_back, R.id.bar_record, R.id.tv_real_house, R.id.tv_real_position,
            R.id.tv_pack_type, R.id.tv_work_team, R.id.tv_work_group, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bar_back:
                finish();
                break;
            case R.id.bar_record:
                //记录 补卡
                ActivityTool.startActivity(getContext(), LogActivity.class);
                break;
            case R.id.tv_real_house:
                //选择仓房
                showListPopupwindow(mTvRealHouse, houseList, mSelectListener);
                break;
            case R.id.tv_real_position:
                //选择货位
                String house = ETTool.getData(mTvRealHouse);
                if (StringTool.isEmpty(house)) {
                    mTvRealHouse.setError("请选择仓房");
                    ToastTool.showLong("请先选择仓房");
                    return;
                }
                showListPopupwindow(mTvRealPosition, positionList, mSelectListener);
                break;
            case R.id.tv_pack_type:
                //包装方式
                showListPopupwindow(mTvPackType, packList, 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.btn_save:
                if (mSelHouseId == null) {
                    ToastTool.showLong("请选择实际仓房");
                    mTvRealHouse.setError("请选择实际仓房");
                    return;
                }
                if (mSelPositionId == null) {
                    ToastTool.showLong("请选择实际货位");
                    mTvRealPosition.setError("请选择实际货位");
                    return;
                }
                String packType = ETTool.getData(mTvPackType);
                if (StringTool.isEmpty(packType)) {
                    ToastTool.showLong("请选择包装方式");
                    mTvPackType.setError("请选择包装方式");
                    return;
                }
//                String team = ETTool.getData(mTvWorkTeam);
//                if (StringTool.isEmpty(team)) {
//                    ToastTool.showLong("请选择作业队");
//                    mTvWorkTeam.setError("请选择作业队");
//                    return;
//                }
//                String group = ETTool.getData(mTvWorkGroup);
//                if (StringTool.isEmpty(group)) {
//                    ToastTool.showLong("请选择作业组");
//                    mTvWorkGroup.setError("请选择作业组");
//                    return;
//                }
                String keeper = ETTool.getData(mEtKeeper);
                if (StringTool.isEmpty(keeper)) {
                    ToastTool.showLong("请填写保管员名称");
                    mEtKeeper.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;
//            case R.id.btn_clear:
//                break;
        }
    }

    private void getHouseList() {
        if (houseList == null) {
            houseList = new ArrayList<>();
            List<StoreEntity> list = StoreDao.get().getStoreList(App.getDBHelper());
            for (StoreEntity store : list) {
                houseList.add(new SpinnerOption(store.getStore_name(), store.getStore_id()));
            }
        }
    }

    private void getPositionList() {
        positionList.clear();
        String data = ETTool.getData(mTvRealHouse);
        if (StringTool.isEmpty(data))
            return;
        List<StoreEntity> list = StoreDao.get().getPositionList(App.getDBHelper(), data);
        for (StoreEntity position : list) {
            positionList.add(new SpinnerOption(position.getPosition_name(), position.getPosition_id()));
        }
    }

    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() {
        if (mGroupList.size() > 0)
            return;
        mGroupList.clear();
        List<TeamGroupEntity> list = TeamGroupDao.get()
                .getGroupList(App.getDBHelper());
        if (list != null) {
            for (TeamGroupEntity entity : list) {
                mGroupList.add(entity.work_group);
            }
        }
    }

    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_real_house:
                    //选择仓房 把货位旧选择置空
                    mTvRealPosition.setText("");
                    mSelHouseId = (String) option.value;
                    mSelPositionId = null;
                    getPositionList();
                    break;
                case R.id.tv_real_position:
                    //选择货位
                    mSelPositionId = (String) option.value;
                    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("值仓---开始写卡保存");
        mEntity.real_house = (ETTool.getData(mTvRealHouse));
        mEntity.real_position = (ETTool.getData(mTvRealPosition));
        mEntity.deduct_water = (ETTool.getData(mEtDeductWater));
        mEntity.deduct_sundries = (ETTool.getData(mEtDeductSundries));
        mEntity.deduct_other = (ETTool.getData(mEtDeductOther));
        mEntity.deduct_pack = (ETTool.getData(mEtDeductPack));
        mEntity.deduct_percent = (ETTool.getData(mEtDeductPercent));
        mEntity.remark = (ETTool.getData(mEtRemark));
        mEntity.keeper = (ETTool.getData(mEtKeeper));
        mEntity.pack_type = (ETTool.getData(mTvPackType));
        mEntity.finish_count = (ETTool.getData(mEtFinishCount));
        mEntity.work_team = (ETTool.getData(mTvWorkTeam));
        mEntity.work_group = (ETTool.getData(mTvWorkGroup));
        mEntity.real_house_id = (mSelHouseId);
        mEntity.real_position_id = (mSelPositionId);
        mEntity.back_impurity = mSwitchSfhz.isChecked() ? "1" : "0";


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

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


}
