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

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

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.BuildFileAdapte;
import com.tofly.ghrq_route.common.ui.adapter.BuildappendAdapter;
import com.tofly.ghrq_route.module.buildManage.BuildExaminesBean;
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.BuildFileBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBeans;
import com.tofly.ghrq_route.module.buildManage.domain.VoiceBeans;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.NoListView;
import com.tofly.ghrq_route.common.util.file.FileUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

/**
 * @author YCHK
 * 工地工单审核
 */
public class UiBuildExamine 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_build_fzr)
    TextView editBuildFzr;
    @BindView(R.id.edit_scene_charge_phone)
    TextView editSceneChargePhone;
    @BindView(R.id.edit_scene_charge)
    TextView editSceneCharge;
    @BindView(R.id.edit_manage_company)
    TextView editManageCompany;
    @BindView(R.id.edit_manage_charger)
    TextView editManageCharger;
    @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.ll_add)
    LinearLayout llAdd;
    @BindView(R.id.ll_process)
    LinearLayout llProcess;
    @BindView(R.id.tv_examine)
    TextView tvExamine;
    @BindView(R.id.tv_examine_time)
    TextView tvExamineTime;
    @BindView(R.id.tv_examine_description)
    EditText tvExamineDescription;
    @BindView(R.id.tv_document_name)
    NoListView tvDocumentName;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.text_build_address)
    TextView textBuildAddress;
    @BindView(R.id.tv_description)
    TextView tvDescription;
    @BindView(R.id.tv_dispatch_note)
    TextView tvDispatchNote;
    @BindView(R.id.ll_examine_add)
    LinearLayout llExamineAdd;

    private BuildManageBeans data;
    private BuildManageController controller = null;
    private int examineIdea = -1;
    private String userId;
    private boolean isSelect = false, isSelect1 = false;
    private BuildappendAdapter adapter;
    private List<VoiceBeans> fileBeanList;
    private List<buildFilesInfo> appendList;
    private BuildFileAdapte buildFileAdapte;
    private List<BuildFileBean> buildFileBeanList = new ArrayList<>();
    private BuildExaminesBean examinesBean;

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

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

    @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 void getData(String id) {
        if (controller == null) {
            controller = new BuildManageController(this);
        }

        controller.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 boolean isValid() {
        if (examineIdea == -1) {
            toast("请选择审核意见");
            return false;
        } else if (TextUtils.isEmpty(tvExamine.getText())) {
            toast("审核人不能为空");
            return false;
        } else if (TextUtils.isEmpty(tvExamineTime.getText())) {
            toast("审核时间不能为空");
            return false;
        } else {
            if (!TextUtils.isEmpty(data.getId())) {
                examinesBean.setWorkOrderId(data.getId());
            }
            examinesBean.setAuditor(userId);
            examinesBean.setAuditmind(String.valueOf(examineIdea));
            examinesBean.setAuditDescription(tvExamineDescription.getText().toString());
            examinesBean.setAuditTime(tvExamineTime.getText().toString());
            return true;
        }
    }

    private void initView() {
        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (!TextUtils.isEmpty(userBean.getRealName())) {
            tvExamine.setText(userBean.getRealName());
            userId = userBean.getUserid();
        }
        Date date = new Date();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        tvExamineTime.setText(simpleDateFormat.format(date));
        if (data != null) {
            examinesBean = new BuildExaminesBean();
            /*工地监护名称*/
            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.getDispatchDate())) {
                tvDispatchTime.setText(data.getDispatchDate());
            }
            if (!TextUtils.isEmpty(data.getConstructionPersonName())) {
                tvDispatch.setText(data.getConstructionPersonName());
            }
            if (!TextUtils.isEmpty(data.getConstructionAddress())) {
                textBuildAddress.setText(data.getConstructionAddress());
            }
            if (!TextUtils.isEmpty(data.getDescription())) {
                tvDescription.setText(data.getDescription());
            }
            if (!TextUtils.isEmpty(data.getNote())) {
                tvDispatchNote.setText(data.getNote());
            }
            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<>();
                loadAppendtionList(fileBeanList, isSelect);
                if (fileBeanList.size() > 2) {
                    tvDetail.setVisibility(View.VISIBLE);
                }
                if (appendList.size() > 0) {
                    llAppend.setVisibility(View.VISIBLE);
                }
                adapter = new BuildappendAdapter(this, appendList);
                listAppendix.setAdapter(adapter);
            }
            if (data.getProcessManages() != null && data.getProcessManages().size() > 0) {
                llProcess.setVisibility(View.VISIBLE);
                if (data.getProcessManages().size() > 2) {
                    tvMore.setVisibility(View.VISIBLE);
                }
                loadProcessList(data.getProcessManages(), isSelect1);
            }
            if (data.getAuditList() != null && data.getAuditList().size() > 0) {
                for (BuildExaminesBean buildExamineBean : data.getAuditList()) {
                    View view = getExamineView(buildExamineBean);
                    llExamineAdd.addView(view);
                }
            }
            buildFileAdapte = new BuildFileAdapte(this, buildFileBeanList);
            tvDocumentName.setAdapter(buildFileAdapte);
        }
    }

    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.setName(fileBeans.get(i).getFileName());
                }
                appendList.add(info1);
            }
        }
    }

    private void loadProcessList(List<BuildManageBeans.ProcssManageBean> processManageBeans, boolean isSelect1) {
        llAdd.removeAllViews();
        for (int i = 0; i < processManageBeans.size(); i++) {
            if (isSelect1) {
                View view = getProcessView(processManageBeans.get(i));
                llAdd.addView(view);
            } else {
                if (i <= 1) {
                    View view = getProcessView(processManageBeans.get(i));
                    llAdd.addView(view);
                }
            }
        }
    }

    private View getProcessView(BuildManageBeans.ProcssManageBean buildProcessManageBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_build_process, null);
        TextView tv_process_describe = view.findViewById(R.id.tv_process_describe);
        TextView tv_process_date = view.findViewById(R.id.tv_process_date);
        LinearLayout ll_append1 = view.findViewById(R.id.ll_append1);
        NoListView list_process = view.findViewById(R.id.list_process);
        if (!TextUtils.isEmpty(buildProcessManageBean.getDescription())) {
            tv_process_describe.setText(buildProcessManageBean.getDescription());
        }
        if (!TextUtils.isEmpty(buildProcessManageBean.getManageDate())) {
            tv_process_date.setText(buildProcessManageBean.getManageDate());
        }
        if (buildProcessManageBean.getProcessVoice() != null && buildProcessManageBean.getProcessVoice().size() > 0) {
            buildProcessManageBean.getProcessFiles().addAll(buildProcessManageBean.getProcessVoice());
        }
        if (buildProcessManageBean.getProcessFiles() != null && buildProcessManageBean.getProcessFiles().size() > 0) {
            List<buildFilesInfo> appendList1 = new ArrayList<>();
            ll_append1.setVisibility(View.VISIBLE);
            for (VoiceBeans fileBean : buildProcessManageBean.getProcessFiles()) {
                buildFilesInfo info = new buildFilesInfo();
                if (!TextUtils.isEmpty(fileBean.getFileName())) {
                    info.setId(data.getId() + "-" + fileBean.getFileName());
                    info.setName(fileBean.getFileName());

                }
                if (!TextUtils.isEmpty(fileBean.getPath())) {
                    info.setPath(fileBean.getPath());
                }
                appendList1.add(info);
            }
            BuildappendAdapter adapter1 = new BuildappendAdapter(this, appendList1);
            list_process.setAdapter(adapter1);
        }
        return view;
    }

    private View getExamineView(BuildExaminesBean buildExamineBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_build_examine, null);
        TextView tv_examine = view.findViewById(R.id.tv_examine);
        TextView tv_examine_time = view.findViewById(R.id.tv_examine_time);
        TextView tv_examine_idea = view.findViewById(R.id.tv_examine_idea);
        TextView tv_examine_description = view.findViewById(R.id.tv_examine_description);
        LinearLayout ll_description = view.findViewById(R.id.ll_description);
        LinearLayout ll_append2 = view.findViewById(R.id.ll_append2);
        NoListView list_examine = view.findViewById(R.id.list_examine);
        if (!TextUtils.isEmpty(buildExamineBean.getAuditorName())) {
            tv_examine.setText(buildExamineBean.getAuditorName());
        }
        if (!TextUtils.isEmpty(buildExamineBean.getAuditTime())) {
            tv_examine_time.setText(buildExamineBean.getAuditTime());
        }
        if (!TextUtils.isEmpty(buildExamineBean.getAuditMindName())) {
            tv_examine_idea.setText(buildExamineBean.getAuditMindName());
        }
        if (!TextUtils.isEmpty(buildExamineBean.getAuditDescription())) {
            ll_description.setVisibility(View.VISIBLE);
            tv_examine_description.setText(buildExamineBean.getAuditDescription());
        }
        if (buildExamineBean.getAuditEndFiles() != null && buildExamineBean.getAuditEndFiles().size() > 0) {
            List<buildFilesInfo> appendList2 = new ArrayList<>();
            ll_append2.setVisibility(View.VISIBLE);
            for (VoiceBeans fileBean : buildExamineBean.getAuditEndFiles()) {
                buildFilesInfo info = new buildFilesInfo();
                if (!TextUtils.isEmpty(fileBean.getFileName())) {
                    info.setId(data.getId() + "-" + fileBean.getFileName());
                    info.setName(fileBean.getFileName());
                }
                if (!TextUtils.isEmpty(fileBean.getPath())) {
                    info.setPath(fileBean.getPath());
                }
                appendList2.add(info);
            }
            BuildappendAdapter adapter2 = new BuildappendAdapter(this, appendList2);
            list_examine.setAdapter(adapter2);
        }
        return view;
    }

    private void gotoUiBuildFoundNext() {
        if (controller == null) {
            controller = new BuildManageController(this);
        }
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        controller.getBuildExamine(examinesBean, buildFileBeanList, 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 void onDestroy() {
        super.onDestroy();
        BaseApp.cancelAllRequest(getClass().getName());
    }

    @OnClick({R.id.rb_sure, R.id.rb_no, R.id.build_found_document, R.id.tv_more, R.id.tv_detail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_sure:
                examineIdea = 0;
                break;
            case R.id.rb_no:
                examineIdea = 1;
                break;
            case R.id.build_found_document:
                showFileChooser();
                break;
            case R.id.tv_detail:
                isSelect = !isSelect;
                if (isSelect) {
                    tvDetail.setText("更少");
                } else {
                    tvDetail.setText("更多");
                }
                loadAppendtionList(fileBeanList, isSelect);
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_more:
                isSelect1 = !isSelect1;
                if (isSelect1) {
                    tvMore.setText("更少");
                } else {
                    tvMore.setText("更多");
                }
                loadProcessList(data.getProcessManages(), isSelect1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == -1) {
            Uri uri = data.getData();
            assert uri != null;
            String filePath = FileUtil.getPath(this, uri);
            assert filePath != null;
            File file = new File(filePath);
            BuildFileBean fileBean = new BuildFileBean();
            fileBean.setFileName(file.getName());
            fileBean.setFilePath(file.getPath());
            buildFileBeanList.add(fileBean);
            buildFileAdapte.notifyDataSetChanged();
        }
    }

    /**
     * 打开文件夹
     */
    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "文件路径"), 1);
        } catch (ActivityNotFoundException ex) {
            ex.printStackTrace();
        }
    }

}

