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


import android.app.DatePickerDialog;
import android.app.Dialog;
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.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.module.buildManage.buildFilesInfo;
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.BuildManageBeans;
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.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.user.domain.MessageUserBean;
import com.tofly.ghrq_route.common.util.NoListView;

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 UiBuildDispatch extends BaseUi {

    @BindView(R.id.edit_build_name)
    TextView editBuildName;
    @BindView(R.id.text_build_type)
    TextView textBuildType;
    @BindView(R.id.edit_build_company)
    TextView editBuildCompany;
    @BindView(R.id.edit_scene_charge)
    TextView editSceneCharge;
    @BindView(R.id.edit_scene_charge_phone)
    TextView editSceneChargePhone;
    @BindView(R.id.edit_manage_company)
    TextView editManageCompany;
    @BindView(R.id.edit_manage_charger)
    TextView editManageCharger;
    @BindView(R.id.edit_build_fzr)
    TextView editBuildFzr;
    @BindView(R.id.tv_dispatch)
    TextView tvDispatch;
    @BindView(R.id.tv_dispatch_time)
    TextView tvDispatchTime;
    @BindView(R.id.list_appendix)
    NoListView listAppendix;
    @BindView(R.id.ll_append)
    LinearLayout llAppend;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.text_build_address)
    TextView textBuildAddress;
    @BindView(R.id.tv_dispatch_note)
    EditText tvDispatchNote;
    @BindView(R.id.tv_description)
    TextView tvDescription;

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

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

    @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(tvDispatchNote.getText())) {
            toast("备注不能为空");
            return false;
        } else {
            data.setDispatchDate(tvDispatchTime.getText().toString());
            data.setConstructionPerson(String.valueOf(mPGR));
            data.setNote(tvDispatchNote.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})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_dispatch:
                if (dataList.size() > 0) {
                    pickerView.show();
                } else {
                    toast("暂时数据");
                }
                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;
        }
    }

    private void initView() {
        if (data != null) {
            /*工地监护名称*/
            if (!TextUtils.isEmpty(data.getSiteName())) {
                editBuildName.setText(data.getSiteName());
            }
            /*工程建设类别*/
            if (!TextUtils.isEmpty(data.getSiteTypeName())) {
                textBuildType.setText(data.getSiteTypeName());
            }
            /*施工单位名称*/
            if (!TextUtils.isEmpty(data.getConstructionUnit())) {
                editBuildCompany.setText(data.getConstructionUnit());
            }

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

            /*施工负责人*/
            if (!TextUtils.isEmpty(data.getPersonInCharge())) {
                editBuildFzr.setText(data.getPersonInCharge());
            }
            /*施工负责人电话*/
            if (!TextUtils.isEmpty(data.getPersonInChargePhone())) {
                editSceneChargePhone.setText(data.getPersonInChargePhone());
            }
            /*主管人姓名*/
            if (!TextUtils.isEmpty(data.getManager())) {
                editManageCharger.setText(data.getManager());
            }
            /*主管单位名字*/
            if (!TextUtils.isEmpty(data.getManageUnit())) {
                editManageCompany.setText(data.getManageUnit());
            }
            if (!TextUtils.isEmpty(data.getConstructionAddress())) {
                textBuildAddress.setText(data.getConstructionAddress());
            }
            if (!TextUtils.isEmpty(data.getDescription())) {
                tvDescription.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);
            if (data.getVoice() != null && data.getVoice().size() > 0) {
                data.getFiles().addAll(data.getVoice());
            }
            if (data.getFiles() != null && data.getFiles().size() > 0) {
                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) {
                    buildFilesInfo info = new buildFilesInfo();
                    if (!TextUtils.isEmpty(fileBeans.get(i).getPath())) {
                        info.setPath(fileBeans.get(i).getPath());
                    }
                    if (!TextUtils.isEmpty(fileBeans.get(i).getFileName())) {
                        info.setId(data.getId() + "-" + i);
                        info.setName(fileBeans.get(i).getFileName());
                    }
                    appendList.add(info);
                }
            } else {
                buildFilesInfo info1 = new buildFilesInfo();
                if (!TextUtils.isEmpty(fileBeans.get(i).getPath())) {
                    info1.setPath(fileBeans.get(i).getPath());
                }
                if (!TextUtils.isEmpty(fileBeans.get(i).getFileName())) {
                    info1.setId(data.getId() + "-" + i);
                    info1.setPath(fileBeans.get(i).getFileName());
                }
                appendList.add(info1);
            }
        }
    }

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

    private void getData(String id) {
        if (buildManageController == null) {
            buildManageController = new BuildManageController(this);
        }

        buildManageController.getBuildDetail(id, new BuildManageCallback() {
            @Override
            public void onBuildDataDetail(boolean isSuccess, int errorCode, String errMsg, BuildManageBeans buildManageList, int total) {
                super.onBuildDataDetail(isSuccess, errorCode, errMsg, buildManageList, total);
                if (isSuccess) {
                    data = buildManageList;
                    initView();
                }
            }
        });
    }

    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(UiBuildDispatch.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 (buildManageController == null) {
            buildManageController = new BuildManageController(this);
        }
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        buildManageController.getBuildDispatch(data, new BuildManageCallback() {
            @Override
            public void onUpdateBuildLog(boolean isSuccess, int errorCode, String errMsg) {
                super.onUpdateBuildLog(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).append(" 00:00:00"));
        }
    };

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

}
