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 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.BuildTool;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageCallback;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageController;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManagerBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildProjectTypeBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildTypeBean;
import com.tofly.ghrq_route.module.buildManage.domain.DepartmentBean;
import com.tofly.ghrq_route.module.buildManage.domain.UserListBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.user.domain.MessageUserBean;

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

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

/**
 * Created by Amu on 2017/4/11.
 */

public class UiBuildFoundFirst extends BaseUi {

    @BindView(R.id.edit_build_name)
    EditText editBuildName;
    @BindView(R.id.text_build_type)
    TextView textBuildType;
    @BindView(R.id.edit_build_company)
    EditText editBuildCompany;
    @BindView(R.id.edit_scene_charge)
    TextView editSceneCharge;
    @BindView(R.id.edit_scene_charge_phone)
    EditText editSceneChargePhone;
    @BindView(R.id.edit_manage_company)
    EditText editManageCompany;
    @BindView(R.id.edit_manage_charger)
    EditText editManageCharger;
    @BindView(R.id.edit_build_fzr)
    EditText editBuildFzr;
    @BindView(R.id.edit_description)
    EditText editDescription;

    private String mBuildType = null;
    private int mJhr = -1;
    private BuildTool buildTool;
    private List<BuildProjectTypeBean> mBuildProjectTypeList;
    private BuildManageBean mBuildManage;
    private OptionsPickerView pickerView;
    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 DBDaoHelper dbDaoHelper;
    private String department;
    private List<BuildTypeBean> buildTypeBeans = new ArrayList<>();
    private BuildManageController buildManageController;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ui_build_found_first);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    @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 initView() {

    }

    private void initData() {
        dbDaoHelper = DBDaoHelper.getInstance();
        buildTool = BuildTool.getInstance();
        getBuildType();
        getLocalUserList();
    }

    private void getBuildType() {
        if (buildManageController == null) {
            buildManageController = new BuildManageController(this);
        }
        buildManageController.getBuildType(new BuildManageCallback() {
            @Override
            public void onGetBuildTypeList(boolean isSuccess, int errorCode, String errMsg, List<BuildTypeBean> data) {
                super.onGetBuildTypeList(isSuccess, errorCode, errMsg, data);
                if (isSuccess) {
                    buildTypeBeans = data;
                }
            }
        });
    }

    private void getLocalUserList() {
        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(UiBuildFoundFirst.this, (OnOptionsSelectListener) (options1, options2, options3, v) -> {
                mJhr = list2.get(options1).get(options2);
                editSceneCharge.setText(list1.get(options1).get(options2));
                department = list01.get(options1);
            })
                    .setSelectOptions(0, 0)
                    .isRestoreItem(true)
                    .isDialog(true)
                    .build();
            pickerView.setPicker(list0, list1);
        }
    }

    private void initListener() {

    }

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

    //    private void getBuildProjectTypeList() {
//        buildTool.getBuildProjectTypeList(this, new BuildManageCallback() {
//            @Override
//            public void onGetBuildProjectTypeList(boolean isSuccess, int errorCode, String errMsg, List<BuildProjectTypeBean> buildProjectTypeList, int total) {
//                super.onGetBuildProjectTypeList(isSuccess, errorCode, errMsg, buildProjectTypeList, total);
//                if (isSuccess) {
//                    mBuildProjectTypeList = buildProjectTypeList;
//                    if (mBuildProjectTypeList != null) {
//                        int position = 0;
//                        BuildProjectTypeBean buildType = mBuildProjectTypeList.get(position);
//                        if (buildType != null) {
//                            mBuildType = position;
//                            textBuildType.setText(buildType.getName());
//                        }
//                    }
//                }
//            }
//        });
//    }
//
    //    private void showBuildTypePopupWindow() {
//        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
//        List<String> buildTypeList = new ArrayList<>();
//        if (mBuildProjectTypeList != null) {
//            for (BuildProjectTypeBean buildProjectTypeBean : mBuildProjectTypeList) {
//                buildTypeList.add(buildProjectTypeBean.getName());
//            }
//        }
//        listPopupWindow.setAdapter(new ArrayAdapter<>(this, R.layout.popup_content_item, buildTypeList));
//        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                mBuildType = position;
//                listPopupWindow.dismiss();
//                if (mBuildProjectTypeList != null) {
//                    BuildProjectTypeBean buildType = mBuildProjectTypeList.get(position);
//                    if (buildType != null) {
//                        textBuildType.setText(buildType.getName());
//                    }
//                }
//            }
//        });
//        listPopupWindow.setAnchorView(textBuildType);
//        listPopupWindow.setVerticalOffset(5);
//        listPopupWindow.setModal(true);
//        listPopupWindow.show();
//    }
    private void showBuildTypePopupWindow() {
        if (buildTypeBeans != null && buildTypeBeans.size() > 0) {
            final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
            List<String> buildTypeList = new ArrayList<>();
            List<String> buildTypeId = new ArrayList<>();
            for (BuildTypeBean buildTypeBean : buildTypeBeans) {
                buildTypeList.add(buildTypeBean.getName());
                buildTypeId.add(buildTypeBean.getId());
            }

            listPopupWindow.setAdapter(new ArrayAdapter<>(this, R.layout.popup_content_item, buildTypeList));
            listPopupWindow.setOnItemClickListener((parent, view, position, id) -> {
                mBuildType = buildTypeId.get(position);
                listPopupWindow.dismiss();
                textBuildType.setText(buildTypeList.get(position));
            });
            listPopupWindow.setAnchorView(textBuildType);
            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() {
        boolean isDeviceTypeValid = false;

        if (TextUtils.isEmpty(editBuildName.getText())) {
            toast("工地名称不能为空");
            return false;
        }

        if (TextUtils.isEmpty(textBuildType.getText())) {
            String strWarn = getString(R.string.build_found_type_empty_err);
            toast(strWarn);
            return false;
        }

//        String buildCompany = editBuildCompany.getText().toString();
//        if (buildCompany.isEmpty()) {
//            toast("施工单位不能为空");
//            editBuildCompany.requestFocus();
//            return false;
//        }


/*        String sceneCharge = editSceneCharge.getText().toString();
        if (sceneCharge.isEmpty()) {
            toast("责任班长不能为空");
            editSceneCharge.requestFocus();
            return false;
        }*/

//        if (TextUtils.isEmpty(editBuildFzr.getText())) {
//            toast("负责人不能为空");
//            editBuildFzr.requestFocus();
//            return false;
//        }

        String mobile = editSceneChargePhone.getText().toString();
        boolean isMobileValid = false;
        String strWarn = "负责人电话不能为空";
        if (!mobile.isEmpty()) {
            if (CheckUtil.isPhoneNum(mobile)) {
                isMobileValid = true;
            } else {
                strWarn = getString(R.string.write_right_phone_number);
                toast(strWarn);
                editSceneChargePhone.requestFocus();
                return false;
            }
        }

//        if (!isMobileValid) {
//            toast(strWarn);
//            editSceneChargePhone.requestFocus();
//            return false;
//        }
        collectData();
        return true;
    }

    private void collectData() {
        mBuildManage = new BuildManageBean();
        String build_id = UUID.randomUUID().toString();
        mBuildManage.setId(build_id);
        /*工地监护名称*/
        String buildName = editBuildName.getText().toString();
        if (!buildName.isEmpty()) {
            mBuildManage.setSiteName(buildName);
        }
        /*工程建设类别*/
        if (!TextUtils.isEmpty(mBuildType)) {
            mBuildManage.setSiteType(mBuildType);
        }
        if (!TextUtils.isEmpty(textBuildType.getText())) {
            mBuildManage.setSiteTypeName(textBuildType.getText().toString());
        }
        /*施工单位名称*/
        String buildCompany = editBuildCompany.getText().toString();
        if (!buildCompany.isEmpty()) {
            mBuildManage.setConstructionUnit(buildCompany);
        }
        /*处置班班长id*/
        if (mJhr != -1) {
            mBuildManage.setDispatchUserId(String.valueOf(mJhr));
        }
        if (!TextUtils.isEmpty(editSceneCharge.getText())) {
            mBuildManage.setDispatchUserName(editSceneCharge.getText().toString());
        }
        /*工地负责人姓名*/
        if (!TextUtils.isEmpty(editBuildFzr.getText())) {
            mBuildManage.setPersonInCharge(editBuildFzr.getText().toString());
        }
        /*施工负责人电话*/
        String charegePhone = editSceneChargePhone.getText().toString();
        if (!charegePhone.isEmpty()) {
            mBuildManage.setPersonInChargePhone(charegePhone);
        }
        /*主管人姓名*/
        String charegeUsername = editManageCharger.getText().toString();
        if (!charegeUsername.isEmpty()) {
            mBuildManage.setManager(charegeUsername);
        }
        /*主管单位名字*/
        String chargeCompany = editManageCompany.getText().toString();
        if (!chargeCompany.isEmpty()) {
            mBuildManage.setManageUnit(chargeCompany);
        }
        if (!TextUtils.isEmpty(editDescription.getText())) {
            mBuildManage.setDescription(editDescription.getText().toString());
        }
        if (!TextUtils.isEmpty(department)) {
            mBuildManage.setDepartment(department);
        }
    }

    @OnClick({R.id.text_build_type, R.id.edit_scene_charge})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_build_type:
                showBuildTypePopupWindow();
                break;
            case R.id.edit_scene_charge:
                if (dataList.size() > 0) {
                    pickerView.show();
                } else {
                    toast("暂无数据");
                }
                break;
        }
    }

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

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

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