package com.tofly.ghrq_route.common.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.mgq.base.utils.check.CheckUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManagerBean;
import com.tofly.ghrq_route.module.buildManage.domain.DepartmentBean;
import com.tofly.ghrq_route.module.buildManage.domain.UserListBean;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.user.domain.MessageUserBean;

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

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

/**
 * @author YCHK
 * 抢维修新建
 */
public class UiRepairFoundFirst extends BaseUi {

    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.tv_job_type)
    TextView tvJobType;
    @BindView(R.id.et_job_source)
    EditText etJobSource;
    @BindView(R.id.et_contacts)
    EditText etContacts;
    @BindView(R.id.et_contacts_phone)
    EditText etContactsPhone;
    @BindView(R.id.et_job_detail)
    EditText etJobDetail;
    @BindView(R.id.tv_qwx_team)
    TextView tvQwxTeam;
    @BindView(R.id.et_rush_code)
    EditText etRushCode;

    private int mBuildType = -1;
    private RushRepairBean mBuildJobBean;
    private DBDaoHelper dbDaoHelper;
    private List<String> list0 = new ArrayList<>();
    private List<String> list01 = new ArrayList<>();
    private List<List<String>> list1 = new ArrayList<>();
    private List<List<Integer>> list2 = new ArrayList<>();
    private List<BuildManagerBean> dataList = new ArrayList<>();
    private OptionsPickerView pickerView;
    private int mBz = -1;
    private String department;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_repair_found_first);
        ButterKnife.bind(this);
        getLocalUserList();
    }

    private void getLocalUserList() {
        dbDaoHelper = DBDaoHelper.getInstance();
        List<DepartmentBean> departmentBeans = dbDaoHelper.getDepartment();
        List<UserListBean> userListBeans = dbDaoHelper.getUserListBean();
        if (departmentBeans != null && departmentBeans.size() > 0) {
            for (DepartmentBean departmentBean : departmentBeans) {
                BuildManagerBean buildManagerBean = new BuildManagerBean();
                if (!TextUtils.isEmpty(departmentBean.getId())) {
                    buildManagerBean.setId(departmentBean.getId());
                }
                if (!TextUtils.isEmpty(departmentBean.getName())) {
                    buildManagerBean.setName(departmentBean.getName());
                }
                if (userListBeans != null && userListBeans.size() > 0) {
                    List<MessageUserBean> messageUserBeanList = new ArrayList<>();
                    for (UserListBean userListBean : userListBeans) {
                        if (userListBean.getDepartmentId().equals(departmentBean.getId())) {
                            MessageUserBean messageUserBean = new MessageUserBean();
                            if (!TextUtils.isEmpty(userListBean.getId())) {
                                messageUserBean.setId(Integer.parseInt(userListBean.getId()));
                            }
                            if (!TextUtils.isEmpty(userListBean.getRealName())) {
                                messageUserBean.setRealName(userListBean.getRealName());
                            }
                            messageUserBeanList.add(messageUserBean);
                        }
                    }
                    buildManagerBean.setUsers(messageUserBeanList);
                }
                dataList.add(buildManagerBean);
            }
        }
        InitPickView(dataList);
    }

    private void InitPickView(List<BuildManagerBean> dataList) {
        if (dataList != null && dataList.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                List<String> lists = new ArrayList<>();
                List<Integer> lists1 = new ArrayList<>();
                list0.add(dataList.get(i).getName());
                list01.add(dataList.get(i).getId());
                for (MessageUserBean data : dataList.get(i).getUsers()) {
                    lists.add(data.getRealName());
                    lists1.add(data.getId());
                }
                list1.add(lists);
                list2.add(lists1);
            }
            pickerView = new OptionsPickerBuilder(UiRepairFoundFirst.this, (OnOptionsSelectListener) (options1, options2, options3, v) -> {
                mBz = list2.get(options1).get(options2);
                tvQwxTeam.setText(list1.get(options1).get(options2));
                department = list01.get(options1);
            })
                    .setSelectOptions(0, 0)
                    .isRestoreItem(true)
                    .isDialog(true)
                    .build();
            pickerView.setPicker(list0, list1);
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_next) {
            if (isValid()) {
                gotoUiBuildFoundNext();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void gotoUiBuildFoundNext() {
        Bundle bundle = new Bundle();
        bundle.putSerializable("rush_repair", mBuildJobBean);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClass(this, UiRepairFound.class);
        startActivityForResult(intent, 0x002);
    }

    private void showBuildTypePopupWindow() {
        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        String[] typeList = new String[]{"内部工单", "外部转接"};
        List<String> buildTypeList = new ArrayList<>(Arrays.asList(typeList));
        listPopupWindow.setAdapter(new ArrayAdapter<>(this, R.layout.popup_content_item, buildTypeList));
        listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
            mBuildType = position;
            listPopupWindow.dismiss();
            tvJobType.setText(buildTypeList.get(position));
        });
        listPopupWindow.setAnchorView(tvJobType);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x002 && resultCode == 0x001) {
            setResult(0x001);
            finish();
        }
    }

    private boolean isValid() {
        if (mBuildType == -1) {
            toast("工单类型不能为空");
            tvJobType.requestFocus();
            return false;
        }

        String sceneCharge = etJobSource.getText().toString();
        if (sceneCharge.isEmpty()) {
            toast("工单来源不能为空");
            etJobSource.requestFocus();
            return false;
        }
        if (!TextUtils.isEmpty(etContactsPhone.getText())) {
            if (!CheckUtil.isPhoneNum(etContactsPhone.getText().toString())) {
                String strWarn = getString(R.string.write_right_phone_number);
                toast(strWarn);
                etContactsPhone.requestFocus();
                return false;
            }
        }
        if (TextUtils.isEmpty(etRushCode.getText())) {
            toast("工单编号不能为空");
            etRushCode.requestFocus();
            return false;
        }
        if (TextUtils.isEmpty(tvQwxTeam.getText())) {
            toast("抢维修班班长不能为空");
            return false;
        }
        collectData();
        return true;
    }

    private void collectData() {
        mBuildJobBean = new RushRepairBean();
        String uuid = UUID.randomUUID().toString();
        mBuildJobBean.setId(uuid);
        if (!TextUtils.isEmpty(etRushCode.getText())) {
            mBuildJobBean.setWorkOrderId(etRushCode.getText().toString());
        }
        /*工单类型*/
        if (mBuildType != -1) {
            mBuildJobBean.setWorkOrderType("" + mBuildType);
        }
        if (!TextUtils.isEmpty(tvJobType.getText())) {
            mBuildJobBean.setWorkOrderTypeName(tvJobType.getText().toString());
        }
        if (!TextUtils.isEmpty(etJobSource.getText())) {
            mBuildJobBean.setWorkOrderSource(etJobSource.getText().toString());
        }

        if (!TextUtils.isEmpty(etContactsPhone.getText())) {
            if (CheckUtil.isPhoneNum(etContactsPhone.getText().toString())) {
                mBuildJobBean.setContactPhone(etContactsPhone.getText().toString());
            }
        }

        if (mBz != -1) {
            mBuildJobBean.setDispatchUserId("" + mBz);
        }

        if (!TextUtils.isEmpty(tvQwxTeam.getText())) {
            mBuildJobBean.setDispatchUserName(tvQwxTeam.getText().toString());
        }

        if (!TextUtils.isEmpty(etContacts.getText())) {
            mBuildJobBean.setContact(etContacts.getText().toString());
        }

        if (!TextUtils.isEmpty(etJobDetail.getText())) {
            mBuildJobBean.setDescription(etJobDetail.getText().toString());
        }

        if (!TextUtils.isEmpty(department)) {
            mBuildJobBean.setDepartment(department);
        }
    }

    @OnClick({R.id.tv_job_type, R.id.tv_qwx_team})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_job_type:
                showBuildTypePopupWindow();
                break;
            case R.id.tv_qwx_team:
                if (dataList.size() > 0) {
                    pickerView.show();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApp.cancelAllRequest(getClass().getName());
    }
}
