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.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

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

import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.file.FileUtil;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.mgq.base.utils.string.StringUtil;
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.AuditFileBean;
import com.tofly.ghrq_route.module.trouble.domain.AuditSchemeBean;
import com.tofly.ghrq_route.module.trouble.domain.MyTroubleEvent;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
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 com.tofly.ghrq_route.common.ui.dialog.MultiUserSelectDailog;
import com.tofly.ghrq_route.common.util.file.FileViewUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;

import org.greenrobot.eventbus.EventBus;

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

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

public class UiTroubleUnderSectaryVerifyAssign extends BaseUi {
    @BindView(R.id.spinner_trouble_verify_state)
    AppCompatSpinner spinnerVerifyState;
    @BindView(R.id.radio_group_verify)
    RadioGroup radioGroupVerify;
    @BindView(R.id.text_assign_title)
    TextView textAssignTitle;
    @BindView(R.id.spinner_trouble_depart)
    AppCompatSpinner spinnerDepart;
    @BindView(R.id.spinner_trouble_user)
    AppCompatSpinner spinnerUser;
    @BindView(R.id.layout_assigner_module)
    LinearLayout layoutAssignerModule;
    @BindView(R.id.layout_undersectary_verify)
    LinearLayout layoutUndersectaryVerify;
    @BindView(R.id.text_handle_title)
    TextView textHandleTitle;
    @BindView(R.id.layout_make_scheme)
    LinearLayout layoutSchemeModule;
    @BindView(R.id.layout_user_coprocessor)
    LinearLayout layoutCoprocessor;
    @BindView(R.id.text_user_coprocessor)
    TextView textCoprocessor;
    @BindView(R.id.edit_verify_note)
    EditText editVerifyNote;
    @BindArray(R.array.trouble_undersectary_verify_states)
    String[] verifyStates;
    @BindView(R.id.layout_rectify_file)
    LinearLayout layoutRectifyFile;
    @BindView(R.id.layout_protect_notice_file)
    LinearLayout layoutProtectNoticeFile;
    @BindView(R.id.layout_rectify_notice_file)
    LinearLayout layoutRectifyNoticeFile;
    @BindView(R.id.layout_rectify_final_file)
    LinearLayout layoutRectifyFinalFile;
    @BindView(R.id.edit_handle_note)
    EditText editHandleNote;
    @BindArray(R.array.trouble_scheme_files)
    String[] schemeFiles;

    private FrameLayout rectifyLayout;

    private ImageView btnRectify;

    private TroubleAudioBean rectifyFile;

    private FrameLayout protectNoticeLayout;

    private ImageView btnProtectNotice;

    private TroubleAudioBean protectNoticeFile;

    private FrameLayout rectifyNoticeLayout;

    private ImageView btnRectifyNotice;

    private TroubleAudioBean rectifyNoticeFile;

    private FrameLayout rectifyFinalLayout;

    private ImageView btnRectifyFinal;

    private TroubleAudioBean rectifyFinalFile;

    private List<DepartmentBean> mDepartmentList;

    private List<DepartmentUserBean> mUserList;

    private SingleUserListAdapter userListAdapter;

    private List<DepartmentUserBean> mCoprocessorList;

    private MultiUserSelectDailog userSelectDailog;

    private AuditSchemeBean auditSchemeBean;

    private int mVerifyState = 0;

    private int indexDepartment = -1;

    private int indexUser = -1;

    private TroubleBean mTroubleBean;

    private TroubleTool troubleTool;

    private PermissionHelper permissionHelper;

    private PhotoHelper photoHelper;

    private FileViewUtil fileViewUtil;

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

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

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

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

        TextView textFileType = layoutRectifyFile.findViewById(R.id.text_file_type);
        rectifyLayout = layoutRectifyFile.findViewById(R.id.layout_file);
        btnRectify = layoutRectifyFile.findViewById(R.id.btn_add_file);
        textFileType.setText(schemeFiles[0]);

        textFileType = layoutProtectNoticeFile.findViewById(R.id.text_file_type);
        protectNoticeLayout = layoutProtectNoticeFile.findViewById(R.id.layout_file);
        btnProtectNotice = layoutProtectNoticeFile.findViewById(R.id.btn_add_file);
        textFileType.setText(schemeFiles[1]);

        textFileType = layoutRectifyNoticeFile.findViewById(R.id.text_file_type);
        rectifyNoticeLayout = layoutRectifyNoticeFile.findViewById(R.id.layout_file);
        btnRectifyNotice = layoutRectifyNoticeFile.findViewById(R.id.btn_add_file);
        textFileType.setText(schemeFiles[2]);

        textFileType = layoutRectifyFinalFile.findViewById(R.id.text_file_type);
        rectifyFinalLayout = layoutRectifyFinalFile.findViewById(R.id.layout_file);
        btnRectifyFinal = layoutRectifyFinalFile.findViewById(R.id.btn_add_file);
        textFileType.setText(schemeFiles[3]);
    }

    private void initData() {
        permissionHelper = new PermissionHelper(this);
        photoHelper = new PhotoHelper(this, permissionHelper);
        fileViewUtil = new FileViewUtil(this);
        troubleTool = TroubleTool.getInstance();

        setVerifyStateAdapter();
        spinnerVerifyState.setSelection(0);

        textCoprocessor.setText("请选择协同处理人员");
    }

    private void initListener() {
        btnRectify.setOnClickListener(view -> photoHelper.requestDocumentFile((success, errStr, document) -> {
            if (success && document != null) {
                rectifyFile = document;
                View rootView = fileViewUtil.getDocumentView(document, (view1, document1) -> {
                    rectifyFile = null;
                    rectifyLayout.removeAllViews();
                    rectifyLayout.addView(btnRectify);
                });
                if (rootView != null) {
                    rectifyLayout.removeAllViews();
                    rectifyLayout.addView(rootView);
                }
            }
        }));

        btnProtectNotice.setOnClickListener(view -> photoHelper.requestDocumentFile((success, errStr, document) -> {
            if (success && document != null) {
                protectNoticeFile = document;
                View rootView = fileViewUtil.getDocumentView(document, (view1, document1) -> {
                    protectNoticeFile = null;
                    protectNoticeLayout.removeAllViews();
                    protectNoticeLayout.addView(btnProtectNotice);
                });
                if (rootView != null) {
                    protectNoticeLayout.removeAllViews();
                    protectNoticeLayout.addView(rootView);
                }
            }
        }));

        btnRectifyNotice.setOnClickListener(view -> photoHelper.requestDocumentFile((success, errStr, document) -> {
            if (success && document != null) {
                rectifyNoticeFile = document;
                View rootView = fileViewUtil.getDocumentView(document, (view1, document1) -> {
                    rectifyNoticeFile = null;
                    rectifyNoticeLayout.removeAllViews();
                    rectifyNoticeLayout.addView(btnRectifyNotice);
                });
                if (rootView != null) {
                    rectifyNoticeLayout.removeAllViews();
                    rectifyNoticeLayout.addView(rootView);
                }
            }
        }));

        btnRectifyFinal.setOnClickListener(view -> photoHelper.requestDocumentFile((success, errStr, document) -> {
            if (success && document != null) {
                rectifyFinalFile = document;
                View rootView = fileViewUtil.getDocumentView(document, (view1, document1) -> {
                    rectifyFinalFile = null;
                    rectifyFinalLayout.removeAllViews();
                    rectifyFinalLayout.addView(btnRectifyFinal);
                });
                if (rootView != null) {
                    rectifyFinalLayout.removeAllViews();
                    rectifyFinalLayout.addView(rootView);
                }
            }
        }));
    }

    @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_verify_state, 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_verify_state:
                mVerifyState = position;
                onSetVerifyState();
                break;
            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 setVerifyStateAdapter() {
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<String>(this,
                R.layout.my_simple_spinner_item, verifyStates) {
        };
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        //加载适配器
        spinnerVerifyState.setAdapter(adapterDevType);
    }

    private void onSetVerifyState() {
        layoutSchemeModule.setVisibility(View.GONE);
        layoutAssignerModule.setVisibility(View.GONE);
        layoutUndersectaryVerify.setVisibility(View.GONE);
        textHandleTitle.setVisibility(View.GONE);
        switch (mVerifyState) {
            case 0:  //继续处理
                layoutUndersectaryVerify.setVisibility(View.VISIBLE);
                layoutSchemeModule.setVisibility(View.VISIBLE);
                layoutAssignerModule.setVisibility(View.VISIBLE);
                textHandleTitle.setVisibility(View.VISIBLE);
                textAssignTitle.setText(R.string.trouble_duty_assign_main_handler);
                getDepartmentUsers();
                break;
            case 1:   //转入其他班组
                layoutAssignerModule.setVisibility(View.VISIBLE);
                textAssignTitle.setText(R.string.trouble_undersectary_verify_duty_user);
                getDepartmentUsers();
                break;
            case 2:   //转入副部长处理
            case 3:   //存量隐患
                break;
        }
    }

    private void getDepartmentUsers() {
        layoutAssignerModule.setVisibility(View.VISIBLE);
        if (mDepartmentList == null || mDepartmentList.isEmpty()) {
            getDepartments();
        }
    }

    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() {
        //适配器
        /*ArrayAdapter<DepartmentUserBean> adpterDangerType = new ArrayAdapter<DepartmentUserBean>(this,
                R.layout.my_simple_spinner_item, mUserList) {

            @Override
            @SuppressLint({"InflateParams", "ViewHolder"})
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View rootView = getLayoutInflater().inflate(R.layout.my_simple_spinner_item, null);
                TextView textView = rootView.findViewById(R.id.text1);
                DepartmentUserBean userBean = getItem(position);
                if (userBean != null) {
                    textView.setText(userBean.getUsername());
                }
                return rootView;
            }

            @Override
            @SuppressLint("InflateParams")
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View rootView = getLayoutInflater().inflate(R.layout.listview_user_item_1, null);
                CircleImageView imageUserIcon = rootView.findViewById(R.id.image_user_icon);
                TextView textName = rootView.findViewById(R.id.text_user_name);
                TextView textRealName = rootView.findViewById(R.id.text_real_name);
                CheckedTextView checkedText = rootView.findViewById(R.id.check_text);

                DepartmentUserBean userBean = getItem(position);
                if (userBean != null) {
                    textName.setText(userBean.getUsername());
                    textRealName.setText(userBean.getRealName());
                    String avatar = userBean.getAvatar();
                    if (avatar != null && !avatar.isEmpty()) {
                        String faceurl = NetRequestURL.newApi_dyrq.getFormattedPicture(avatar);
                        ImageLoader imageLoader = ImageLoader.getInstance();
                        imageLoader.displayImage(faceurl, imageUserIcon);
                    }
                }

                checkedText.setChecked(position == indexUser);
                return rootView;
            }

        };
        adpterDangerType.setDropDownViewResource(R.layout.listview_user_item_1);
        spinnerUser.setAdapter(adpterDangerType);*/
        userListAdapter = new SingleUserListAdapter(this, mUserList);
        spinnerUser.setAdapter(userListAdapter);
    }

    @OnClick({R.id.layout_user_coprocessor})
    void onClicked(View view) {
        if (view.getId() == R.id.layout_user_coprocessor) {
            showMultiUserSelectDialog();
        }
    }

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

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (photoHelper != null) {
            photoHelper.handleActivityResult(requestCode, resultCode, data);
        }
    }

    private boolean isValid() {
        if (mVerifyState == 0) {
            if (mUserList == null || mUserList.isEmpty() || indexUser == -1) {
                toast(R.string.trouble_duty_empty_main_handler);
                return false;
            }
        }else if (mVerifyState == 1){
            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_undersectary_verify_note_hint);
            return false;
        }

        return true;
    }

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

        if (mVerifyState == 0) { //继续处理
            auditSchemeBean = new AuditSchemeBean();
            /*整改方案描述*/
            auditSchemeBean.setDutyPlanNote(notes);

            /*工单处理负责人*/
            DepartmentUserBean userBean = mUserList.get(indexUser);
            auditSchemeBean.setHandleUserId(userBean.getId());
            auditSchemeBean.setHandleUserName(userBean.getUsername());

            int checkedId = radioGroupVerify.getCheckedRadioButtonId();
            mTroubleBean.setFlag(checkedId == R.id.rb_yes ? 0 : 1);

            /*协同处理人员*/
            if (mCoprocessorList != null && !mCoprocessorList.isEmpty()) {
                List<String> coprocessorNames = new ArrayList<>();
                List<String> coprocessorIds = new ArrayList<>();
                for (DepartmentUserBean departmentUserBean : mCoprocessorList) {
                    coprocessorIds.add(departmentUserBean.getId());
                    coprocessorNames.add(departmentUserBean.getUsername());
                }
                String names = StringUtil.listToString(coprocessorNames, ',');
                auditSchemeBean.setCoprocessorName(names);
                String ids = StringUtil.listToString(coprocessorIds, ',');
                auditSchemeBean.setCoprocessor(ids);
            }

            /*整改方案说明*/
            String handle_note = editHandleNote.getText().toString();
            auditSchemeBean.setDutyPlanNote(handle_note);

            /*整改方案*/
            if (rectifyFile != null && rectifyFile.getPath() != null) {
                String filePath = rectifyFile.getPath();
                if (FileUtil.isFileExist(filePath)) {
                    String fileName = FileUtil.getFileName(filePath);
                    AuditFileBean fileBean = new AuditFileBean();
                    fileBean.setPath(filePath);
                    fileBean.setFileName(fileName);/**/
                    auditSchemeBean.setRectifyFile(Collections.singletonList(fileBean));
                }
            }

            /*管道保护通知书*/
            if (protectNoticeFile != null && protectNoticeFile.getPath() != null) {
                String filePath = protectNoticeFile.getPath();
                if (FileUtil.isFileExist(filePath)) {
                    String fileName = FileUtil.getFileName(filePath);
                    AuditFileBean fileBean = new AuditFileBean();
                    fileBean.setPath(filePath);
                    fileBean.setFileName(fileName);
                    auditSchemeBean.setProtectNoticeFile(Collections.singletonList(fileBean));
                }
            }

            /*隐患整改通知书*/
            if (rectifyNoticeFile != null && rectifyNoticeFile.getPath() != null) {
                String filePath = rectifyNoticeFile.getPath();
                if (FileUtil.isFileExist(filePath)) {
                    String fileName = FileUtil.getFileName(filePath);
                    AuditFileBean fileBean = new AuditFileBean();
                    fileBean.setPath(filePath);
                    fileBean.setFileName(fileName);
                    auditSchemeBean.setRectifyNoticeFile(Collections.singletonList(fileBean));
                }
            }

            /*整改工程决算书*/
            if (rectifyFinalFile != null && rectifyFinalFile.getPath() != null) {
                String filePath = rectifyFinalFile.getPath();
                if (FileUtil.isFileExist(filePath)) {
                    String fileName = FileUtil.getFileName(filePath);
                    AuditFileBean fileBean = new AuditFileBean();
                    fileBean.setPath(filePath);
                    fileBean.setFileName(fileName);
                    auditSchemeBean.setRectifyFinalFile(Collections.singletonList(fileBean));
                }
            }
        }else if (mVerifyState == 1) {  //转其它班组
            DepartmentUserBean userBean = mUserList.get(indexUser);
            mTroubleBean.setMaintainerUserId(userBean.getId());
            mTroubleBean.setMaintainerUserName(userBean.getUsername());
        }

        mTroubleBean.setState(mVerifyState);
        mTroubleBean.setStateName(verifyStates[mVerifyState]);
    }

    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.underSectaryVerifyAssignTroubleNoSave(this, mTroubleBean, auditSchemeBean, 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() {
        String title = getTitle().toString();
        String msg = getString(R.string.upload_ok);
        showAlertWithConfirmButton(title, msg, false, (dialogInterface, i) -> this.finish());
    }
}
