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

import android.app.DatePickerDialog;
import android.app.Dialog;
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.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
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.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.adapter.BuildappendAdapter;
import com.tofly.ghrq_route.common.ui.view.UserListView;
import com.tofly.ghrq_route.module.buildManage.buildFilesInfo;
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.buildManage.domain.VoiceBeans;
import com.tofly.ghrq_route.module.rushrepair.controller.RushRepairCallback;
import com.tofly.ghrq_route.module.rushrepair.controller.RushRepairController;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairBeanList;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.user.domain.MessageUserBean;
import com.tofly.ghrq_route.common.util.EventBusUtil;
import com.tofly.ghrq_route.common.util.NoListView;

import org.greenrobot.eventbus.Subscribe;

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

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

/**
 * @author YCHK
 * 抢维修派工
 */
public class UiRepairDispatch extends BaseUi {

    @BindView(R.id.tv_repair_code)
    TextView tvRepairCode;
    @BindView(R.id.tv_repair_type)
    TextView tvRepairType;
    @BindView(R.id.tv_repair_source)
    TextView tvRepairSource;
    @BindView(R.id.tv_contact)
    TextView tvContact;
    @BindView(R.id.tv_contact_phone)
    TextView tvContactPhone;
    @BindView(R.id.edit_scene_charge)
    TextView editSceneCharge;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.list_appendix)
    NoListView listAppendix;
    @BindView(R.id.ll_append)
    LinearLayout llAppend;
    @BindView(R.id.tv_dispatch)
    TextView tvDispatch;
    @BindView(R.id.tv_dispatch_time)
    TextView tvDispatchTime;
    @BindView(R.id.layout_recver_area)
    LinearLayout layoutRecverArea;
    @BindView(R.id.tv_note)
    EditText tvNote;
    @BindView(R.id.tv_rush_note)
    TextView tvRushNote;

    private int mPGR = -1;
    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 RushRepairController rushRepairController;
    private int mYear, mMonth, mDay;
    private TextView date;
    final int DATE_DIALOG = 1;
    private BuildappendAdapter adapter;
    private List<buildFilesInfo> appendList;
    private List<VoiceBeans> fileBeanList = new ArrayList<>();
    private DBDaoHelper dbDaoHelper;
    private boolean isSelect = false;
    private List<BuildManagerBean> dataList = new ArrayList<>();
    private List<MessageUserBean> mRecverList = null;
    private String department;
    private RushRepairBeanList data = null;

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

    @Subscribe
    public void onMessageEvent(UiMessageUserSelect.MessageUserSelectEvent event) {
        if (event.message.equals(UiMessageUserSelect.MESSAGE_USER_SELECTED)) {
            List<MessageUserBean> userBeanList = event.userList;
            if (userBeanList != null) {
                mRecverList = userBeanList;
                UserListView userListView = new UserListView(this, mRecverList);
                View rootView = userListView.getViewWithNoTitle();
                if (rootView != null) {
                    layoutRecverArea.removeAllViews();
                    layoutRecverArea.addView(rootView);
                }
            }
        }
    }

    private String getSendUsers() {
        String userIds = "";
        List<String> users = new ArrayList<>();
        if (mRecverList != null) {
            for (MessageUserBean userBean : mRecverList) {
                if (userBean != null && userBean.getId() != 0) {
                    users.add(String.valueOf(userBean.getId()));
                }
            }
        }
        if (users.size() > 0) {
            userIds = StringUtil.listToString(users, ',');
        }
        return userIds;
    }

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

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

    private boolean isValid() {
        if (TextUtils.isEmpty(tvDispatchTime.getText())) {
            toast("派工时间不能为空");
            return false;
        } else if (TextUtils.isEmpty(tvDispatch.getText())) {
            toast("工地监护人不能为空");
            return false;
        } else if (TextUtils.isEmpty(tvNote.getText())) {
            toast("派工备注不能为空");
            return false;
        } else {
            data.setDispatchDate(tvDispatchTime.getText().toString());
            data.setRushRepairResponsible(String.valueOf(mPGR));
            String userIds = getSendUsers();
            if (!TextUtils.isEmpty(userIds)) {
                data.setRushRepairPersons(userIds);
            }
            if (!TextUtils.isEmpty(tvNote.getText())) {
                data.setIntroduction(tvNote.getText().toString());
            }
            if (!TextUtils.isEmpty(department)) {
                data.setDepartment(department);
            }
            return true;
        }
    }

    @OnClick({R.id.tv_dispatch, R.id.tv_dispatch_time, R.id.tv_detail, R.id.image_add_recver})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_dispatch:
                pickerView.show();
                break;
            case R.id.tv_dispatch_time:
                date = tvDispatchTime;
                showDialog(DATE_DIALOG);
                break;
            case R.id.tv_detail:
                isSelect = !isSelect;
                if (isSelect) {
                    tvDetail.setText("更少");
                } else {
                    tvDetail.setText("更多");
                }
                loadAppendtionList(fileBeanList, isSelect);
                adapter.notifyDataSetChanged();
                break;
            case R.id.image_add_recver:
                hideSoftKeyboard();
                Intent intent=new Intent(this,UiMessageUserSelect.class);
                startActivity(intent);
                break;
        }
    }

    private void initView() {
        if (data != null) {
            /*工单编号*/
            if (!TextUtils.isEmpty(data.getWorkOrderId())) {
                tvRepairCode.setText(data.getWorkOrderId());
            }
            /*工单类型*/
            if (!TextUtils.isEmpty(data.getWorkOrderTypeName())) {
                tvRepairType.setText(data.getWorkOrderTypeName());
            }
            /*工单来源*/
            if (!TextUtils.isEmpty(data.getWorkOrderSource())) {
                tvRepairSource.setText(data.getWorkOrderSource());
            }

            /*抢修班班长姓名*/
            if (!TextUtils.isEmpty(data.getDispatchUserName())) {
                editSceneCharge.setText(data.getDispatchUserName());
            }

            /*联系人*/
            if (!TextUtils.isEmpty(data.getContact())) {
                tvContact.setText(data.getContact());
            }

            /*联系人电话*/
            if (!TextUtils.isEmpty(data.getContactPhone())) {
                tvContactPhone.setText(data.getContactPhone());
            }
            /*地址*/
            if (!TextUtils.isEmpty(data.getAddress())) {
                tvAddress.setText(data.getAddress());
            }
            if (!TextUtils.isEmpty(data.getDescription())) {
                tvRushNote.setText(data.getDescription());
            }
            final Calendar calendar = Calendar.getInstance();
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
            dbDaoHelper = DBDaoHelper.getInstance();
            if (data.getVoice() != null && data.getVoice().size() > 0) {
                data.getFiles().addAll(data.getVoice());
            }
            fileBeanList = data.getFiles();
            if (fileBeanList != null && fileBeanList.size() > 0) {
                appendList = new ArrayList<>();
                llAppend.setVisibility(View.VISIBLE);
                loadAppendtionList(fileBeanList, isSelect);
                if (fileBeanList.size() > 2) {
                    tvDetail.setVisibility(View.VISIBLE);
                }
                adapter = new BuildappendAdapter(this, appendList);
                listAppendix.setAdapter(adapter);
            }
        }
    }

    private void loadAppendtionList(List<VoiceBeans> fileBeans, boolean type) {
        appendList.clear();
        for (int i = 0; i < fileBeans.size(); i++) {
            if (!type) {
                if (i <= 1) {
                    if (!TextUtils.isEmpty(fileBeans.get(i).getPath())) {
                        buildFilesInfo info = new buildFilesInfo();
                        info.setId(data.getId() + i);
                        info.setPath(fileBeans.get(i).getPath());
                        info.setName(fileBeans.get(i).getFileName());
                        appendList.add(info);
                    }
                }
            } else {
                if (!TextUtils.isEmpty(fileBeans.get(i).getPath())) {
                    buildFilesInfo info = new buildFilesInfo();
                    info.setId(data.getId() + i);
                    info.setPath(fileBeans.get(i).getPath());
                    info.setName(fileBeans.get(i).getFileName());
                    appendList.add(info);
                }
            }
        }
    }

    private void initData() {
        getLocalUserList();
        String id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            getData(id);
        }
    }

    private void getData(String id) {
        RushRepairController rushRepairController = new RushRepairController(this);
        rushRepairController.getDataDetail(id, new RushRepairCallback() {
            @Override
            public void onRepairDetail(boolean isSuccess, int errorCode, String errMsg, RushRepairBeanList buildManage, int total) {
                super.onRepairDetail(isSuccess, errorCode, errMsg, buildManage, total);
                if (isSuccess) {
                    data = buildManage;
                    initView();
                }
            }
        });
    }

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


    private void gotoUiBuildFoundNext() {
        if (rushRepairController == null) {
            rushRepairController = new RushRepairController(this);
        }
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        rushRepairController.getBuildDispatch(data, new RushRepairCallback() {
            @Override
            public void onRushBack(boolean isSuccess, int errorCode, String errMsg) {
                super.onRushBack(isSuccess, errorCode, errMsg);
                ProgressManager.getInstance().cancelProgress();
                if (isSuccess) {
                    toast("派工成功");
                    setResult(0x001);
                    finish();
                } else {
                    errMsg = BaseApp.formatErrorMessage(errorCode, errMsg);
                    toast(errMsg);
                }
            }
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        if (id == DATE_DIALOG) {
            return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear + 1;
            mDay = dayOfMonth;
            String month, day;
            if (mMonth < 9) {
                month = "0" + mMonth;
            } else {
                month = "" + mMonth;
            }
            if (mDay < 10) {
                day = "0" + mDay;
            } else {
                day = "" + mDay;
            }
            date.setText(new StringBuffer().append(mYear).append("-").append(month).append("-").append(day));
        }
    };


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

}
