package com.tofly.ghrq_route.module.trouble.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSpinner;

import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.module.trouble.TroubleTool;
import com.tofly.ghrq_route.module.trouble.controller.TroubleCallBack;
import com.tofly.ghrq_route.module.trouble.domain.MyTroubleEvent;
import com.tofly.ghrq_route.module.trouble.domain.TroubleBean;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.DepartmentBean;
import com.tofly.ghrq_route.module.user.domain.DepartmentUserBean;
import com.tofly.ghrq_route.common.ui.adapter.SingleUserListAdapter;

import org.greenrobot.eventbus.EventBus;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnItemSelected;

public class UiTroubleUndertakerVerify extends BaseUi {
    @BindView(R.id.spinner_trouble_depart)
    AppCompatSpinner spinnerDepart;
    @BindView(R.id.spinner_trouble_user)
    AppCompatSpinner spinnerUser;
    @BindView(R.id.edit_verify_note)
    EditText editVerifyNote;

    private List<DepartmentBean> mDepartmentList;

    private List<DepartmentUserBean> mUserList;

    private SingleUserListAdapter userListAdapter;

    private int indexDepartment = -1;

    private int indexUser = -1;

    private TroubleBean mTroubleBean;

    private TroubleTool troubleTool;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_trouble_undertaker_verify);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    private void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mTroubleBean = (TroubleBean) bundle.getSerializable(TroubleBean.TROUBLE_BEAN_KEY);
        }
    }

    private void initData() {
       troubleTool = TroubleTool.getInstance();

        getDepartments();
    }

    private void initListener() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_commit) {
            hideSoftKeyboard();
            if (isValid()) {
                uploadTroubleAlert();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @OnItemSelected({R.id.spinner_trouble_depart, R.id.spinner_trouble_user})
    public void onItemSelected(AdapterView<?> parent, int position) {
        switch (parent.getId()) {
            case R.id.spinner_trouble_depart:
                indexDepartment = position;
                indexUser = -1;
                if (mDepartmentList != null) {
                    DepartmentBean departmentBean = mDepartmentList.get(position);
                    getDepartmentUsers(departmentBean.getId());
                }
                break;
            case R.id.spinner_trouble_user:
                indexUser = position;
                userListAdapter.setSelection(position);
                break;
        }
    }

    private void getDepartments() {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartments(this, false, new UserCallBack(){
            @Override
            public void onGetDepartmentList(boolean isSuccess, int errorCode, String errMsg, List<DepartmentBean> departmentList) {
                super.onGetDepartmentList(isSuccess, errorCode, errMsg, departmentList);
                if (isSuccess) {
                    mDepartmentList = departmentList;
                    setDepartmentAdapter();
                    spinnerDepart.setSelection(0);
                }
            }
        });
    }

    private void setDepartmentAdapter(){
        List<String> departNameList = new ArrayList<>();
        for (DepartmentBean departmentBean : mDepartmentList) {
            departNameList.add(departmentBean.getName());
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, departNameList){
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerDepart.setAdapter(adapterDevType);
    }

    private void getDepartmentUsers(String departId) {
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartmentUsers(this, departId, new UserCallBack(){
            @Override
            public void onGetDepartmentUserList(boolean isSuccess, int errorCode, String errMsg,
                                                List<DepartmentUserBean> userList) {
                super.onGetDepartmentUserList(isSuccess, errorCode, errMsg, userList);
                if (isSuccess) {
                    mUserList = userList;
                    setUserAdapter();
                }
            }
        });
    }

    private void setUserAdapter(){
        //适配器
        userListAdapter = new SingleUserListAdapter(this, mUserList);
        spinnerUser.setAdapter(userListAdapter);
    }

    private boolean isValid() {
        if (mDepartmentList == null || mDepartmentList.isEmpty() || indexDepartment == -1) {
            toast(R.string.trouble_report_empty_depart);
            return false;
        }
        if (mUserList == null || mUserList.isEmpty() || indexUser == -1) {
            toast(R.string.trouble_report_empty_assigner);
            return false;
        }

        if (editVerifyNote.getText().toString().isEmpty()) {
            editVerifyNote.requestFocus();
            toast(R.string.trouble_undertaker_verify_note_hint);
            return false;
        }

        return true;
    }

    private void collectData() {
        /*审核详情*/
        String notes = editVerifyNote.getText().toString();
        mTroubleBean.setUndertakerCheckNotes(notes);

        DepartmentUserBean userBean = mUserList.get(indexUser);
        mTroubleBean.setUndertakerHandleUserId(userBean.getId());
        mTroubleBean.setUndertakerHandleUserName(userBean.getUsername());
    }

    private void uploadTroubleAlert() {
        String title = "上传数据";
        String content = "是否上传数据?";
        showAlertWithConfirmCancelButton(title, content, true, (dialogInterface, i) -> uploadTroubleData());
    }

    private void uploadTroubleData() {
        collectData();
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        troubleTool.undertakerVerifyTroubleNoSave(this, mTroubleBean, new TroubleCallBack() {
            @Override
            public void onSetData(boolean isSuccess, int errorCode, String errMsg) {
                super.onSetData(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    EventBus.getDefault().post(new MyTroubleEvent(MyTroubleEvent.TROUBLE_UPLOADED));
                    showUploadFinishedDialog();
                }
            }
        });
    }

    private void showUploadFinishedDialog() {
        int title = R.string.trouble_undertaker_verify_title;
        int msg = R.string.upload_ok;
        showAlertWithConfirmButton(title, msg, false, (dialogInterface, i) -> this.finish());
    }
}
