package com.tofly.ghrq_route.module.emergencyHandle.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatSpinner;

import com.mgq.base.utils.string.StringUtil;
import com.mgq.base.utils.toast.ToastUtil;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.module.emergencyHandle.domain.EmergencyHandleData;
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.dialog.MultiUserSelectDailog;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.common.util.SnackBarUtil;
import com.tofly.ghrq_route.common.util.SpinnerUtils;

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

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

/**
 * Created by Amu on 2017/2/21.
 */

public class EmergencyRepairAssignReportModuleLayout extends LinearLayout {
    @BindView(R.id.spinner_handle_depart)
    AppCompatSpinner spinnerHandleDepart;
    @BindView(R.id.spinner_handle_user)
    AppCompatSpinner spinnerHandleUser;
    @BindView(R.id.spinner_assist_depart)
    AppCompatSpinner spinnerAssistDepart;
    @BindView(R.id.text_user_coprocessor)
    TextView textAssistUser;
    @BindView(R.id.edit_note)
    EditText editNote;
    @BindView(R.id.btn_add_photo)
    Button btnAddPhoto;
    @BindView(R.id.photo_gallery)
    LinearLayout photoGallery;
    @BindView(R.id.btn_audio_record)
    MyAudioRecordButton btnAudioRecord;

    private Context mContext;

    private List<DepartmentBean> mDepartmentList;

    private List<DepartmentUserBean> mUserList;

    private int indexHandleDepart = -1;

    private int indexHandleUser = -1;

    private int indexAssistDepart = -1;

    private int indexAssistUser = -1;

    private String mAssistDepartId = null;

    private MultiUserSelectDailog userSelectDialog;

    private List<DepartmentUserBean> mCoprocessorList;

    public EmergencyRepairAssignReportModuleLayout(Context context) {
        this(context, null);
    }

    public EmergencyRepairAssignReportModuleLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EmergencyRepairAssignReportModuleLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;

        initView();
        initListener();
    }

    private void initView() {
        inflate(mContext, R.layout.layout_emergency_repair_assign_report_module, this);
        ButterKnife.bind(this);

        getDepartments();
    }

    private void initListener() {

    }

    @OnClick({ R.id.layout_user_coprocessor})
    void onClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_user_coprocessor:
                showMultiUserSelectDialog();
                break;
        }
    }

    @OnItemSelected({R.id.spinner_handle_depart, R.id.spinner_handle_user, R.id.spinner_assist_depart})
    public void onItemSelected(AdapterView<?> parent, int position){
        switch (parent.getId()) {
            case R.id.spinner_handle_depart:
                indexHandleDepart = position;
                DepartmentBean departmentBean = mDepartmentList.get(position);
                if (departmentBean != null) {
                    getDepartmentUsers(departmentBean.getId());
                }
                break;
            case R.id.spinner_handle_user:
                indexHandleUser = position;
                break;
            case R.id.spinner_assist_depart:
                indexAssistDepart = position;
                departmentBean = mDepartmentList.get(position);
                if (departmentBean != null) {
                    mAssistDepartId = departmentBean.getId();
                }
                textAssistUser.setText("请选择协助人员");
                if (userSelectDialog != null)
                    userSelectDialog.setDepartment(mAssistDepartId);
                break;
        }
    }

    private void showMultiUserSelectDialog() {
        if (userSelectDialog == null) {
            userSelectDialog = new MultiUserSelectDailog(mContext);
            userSelectDialog.setClicklistener(userBeans -> {
                mCoprocessorList = userBeans;
                List<String> coprocessorNames = new ArrayList<>();
                for (DepartmentUserBean departmentUserBean : mCoprocessorList) {
                    coprocessorNames.add(departmentUserBean.getRealName());
                }
                String names = StringUtil.listToString(coprocessorNames, ',');
                textAssistUser.setText(names);
            });
        }
        userSelectDialog.show();
    }

    private void getDepartments() {
        View parent = (View) getParent();
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartments(mContext, 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();
                }else {
                    SnackBarUtil.showSnackAlways(parent, "获取部门失败", "重试", view -> getDepartments());
                }
            }
        });
    }

    private void setDepartmentAdapter(){
        if (mDepartmentList != null) {
            List<String> typeNameList = new ArrayList<>();
            for (DepartmentBean departmentBean : mDepartmentList) {
                typeNameList.add(departmentBean.getName());
            }
            SpinnerUtils.setAdapter(mContext, spinnerHandleDepart, typeNameList);
            SpinnerUtils.setAdapter(mContext, spinnerAssistDepart, typeNameList);
        }
    }

    private void getDepartmentUsers(String departId) {
        View parent = (View) getParent();
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getDepartmentUsers(mContext, 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();
                }else {
                    SnackBarUtil.showSnackAlways(parent, "获取部门用户失败",
                            "重试", view -> getDepartmentUsers(departId));
                }
            }
        });
    }

    private void setUserAdapter(){
        List<String> levelNameList = new ArrayList<>();
        for (DepartmentUserBean userBean : mUserList) {
            levelNameList.add(userBean.getRealName());
        }
        SpinnerUtils.setAdapter(mContext, spinnerHandleUser, levelNameList);
    }

    public boolean isValid() {
        if (mUserList == null || mUserList.isEmpty() || indexHandleUser == -1) {
            ToastUtil.showToast(mContext, R.string.emergency_report_empty_handle_user);
            return false;
        }

        if (editNote.getText().toString().isEmpty()) {
            editNote.requestFocus();
            ToastUtil.showToast(mContext, mContext.getString(R.string.emergency_repair_assign_empty_note));
            return false;
        }

        return true;
    }

    public void collectData(EmergencyHandleData handleData) {
        /*处理人员*/
        DepartmentBean departBean = mDepartmentList.get(indexHandleDepart);
        handleData.setResponsibleDepartment(departBean.getId());
        DepartmentUserBean userBean = mUserList.get(indexHandleUser);
        handleData.setResponsibleUserId(userBean.getId());
        /*协同处理人员*/
        if (indexAssistDepart != -1 && mDepartmentList != null) {
            departBean = mDepartmentList.get(indexAssistDepart);
            handleData.setMdispatchingDepartment(departBean.getId());
            if (mCoprocessorList != null && mCoprocessorList.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < mCoprocessorList.size(); i++) {
                    DepartmentUserBean departmentUserBean = mCoprocessorList.get(i);
                    String userid = departmentUserBean.getId();
                    stringBuilder.append(userid);
                    if (i < mCoprocessorList.size() - 1) {
                        stringBuilder.append(",");
                    }
                }
                handleData.setMdispatchingUserId(stringBuilder.toString());
            }
        }

        String note = editNote.getText().toString();
        handleData.setMdispatchingNotes(note);
    }
}
