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.buildFilesInfo;
import com.tofly.ghrq_route.module.buildManage.domain.BuildFileBean;
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.rushrepair.domain.RushRepairExamineList;
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 UiRepairExamine 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.tv_more)
    TextView tvMore;
    @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_part)
    TextView tvPart;
    @BindView(R.id.tv_rush_note)
    TextView tvRushNote;
    @BindView(R.id.tv_note)
    TextView tvNote;
    @BindView(R.id.ll_examine_add)
    LinearLayout llExamineAdd;

    private RushRepairBeanList data;
    private RushRepairController 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 RushRepairExamineList examinesBean;

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

    @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 (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));
        String id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            getData(id);
        }
    }

    private void initData() {
        if (data != null) {
            examinesBean = new RushRepairExamineList();
            /*工单编号*/
            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.getResponsibleName())) {
                tvDispatch.setText(data.getResponsibleName());
            }
            /*派发时间*/
            if (!TextUtils.isEmpty(data.getDispatchDate())) {
                tvDispatchTime.setText(data.getDispatchDate());
            }
            if (!TextUtils.isEmpty(data.getRushRepairPersonsName())) {
                tvPart.setText(data.getRushRepairPersonsName());
            }
            /*备注*/
            if (!TextUtils.isEmpty(data.getDescription())) {
                tvRushNote.setText(data.getDescription());
            }
            /* 派发备注*/
            if (!TextUtils.isEmpty(data.getIntroduction())) {
                tvNote.setText(data.getIntroduction());
            }
            appendList = new ArrayList<>();
            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 (RushRepairExamineList repairExamineList : data.getAuditList()) {
                    View view = getExamineView(repairExamineList);
                    llExamineAdd.addView(view);
                }
            }
        }
        buildFileAdapte = new BuildFileAdapte(this, buildFileBeanList);
        tvDocumentName.setAdapter(buildFileAdapte);
    }

    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;
                    initData();
                }
            }
        });
    }

    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 loadProcessList(List<RushRepairBeanList.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(RushRepairBeanList.ProcssManageBean procssManageBean) {
        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(procssManageBean.getDescription())) {
            tv_process_describe.setText(procssManageBean.getDescription());
        }
        if (!TextUtils.isEmpty(procssManageBean.getManageDate())) {
            tv_process_date.setText(procssManageBean.getManageDate());
        }
        if (procssManageBean.getProcessVoice() != null && procssManageBean.getProcessVoice().size() > 0) {
            procssManageBean.getProcessFiles().addAll(procssManageBean.getProcessVoice());
        }
        if (procssManageBean.getProcessFiles() != null && procssManageBean.getProcessFiles().size() > 0) {
            List<buildFilesInfo> appendList1 = new ArrayList<>();
            ll_append1.setVisibility(View.VISIBLE);
            for (VoiceBeans voiceBeans : procssManageBean.getProcessFiles()) {
                buildFilesInfo info = new buildFilesInfo();
                if (!TextUtils.isEmpty(voiceBeans.getPath())) {
                    info.setId(data.getId() + "-" + procssManageBean.getId());
                    info.setPath(voiceBeans.getPath());
                    info.setName(voiceBeans.getFileName());
                    appendList1.add(info);
                }
            }
            BuildappendAdapter adapter1 = new BuildappendAdapter(this, appendList1);
            list_process.setAdapter(adapter1);
        }

        return view;
    }

    private View getExamineView(RushRepairExamineList repairExamineList) {
        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(repairExamineList.getAuditorname())) {
            tv_examine.setText(repairExamineList.getAuditorname());
        }
        if (!TextUtils.isEmpty(repairExamineList.getAuditTime())) {
            tv_examine_time.setText(repairExamineList.getAuditTime());
        }
        if (!TextUtils.isEmpty(repairExamineList.getAuditmindname())) {
            tv_examine_idea.setText(repairExamineList.getAuditmindname());
        }
        if (!TextUtils.isEmpty(repairExamineList.getAuditDescription())) {
            ll_description.setVisibility(View.VISIBLE);
            tv_examine_description.setText(repairExamineList.getAuditDescription());
        }
        if (repairExamineList.getAuditEndFiles() != null && repairExamineList.getAuditEndFiles().size() > 0) {
            List<buildFilesInfo> appendList2 = new ArrayList<>();
            ll_append2.setVisibility(View.VISIBLE);
            for (VoiceBeans fileBean : repairExamineList.getAuditEndFiles()) {
                buildFilesInfo info = new buildFilesInfo();
                if (!TextUtils.isEmpty(fileBean.getPath())) {
                    info.setId(data.getId() + "-" + repairExamineList.getId());
                    info.setPath(fileBean.getPath());
                    info.setName(fileBean.getFileName());
                    appendList2.add(info);
                }
            }
            BuildappendAdapter adapter2 = new BuildappendAdapter(this, appendList2);
            list_examine.setAdapter(adapter2);
        }
        return view;
    }

    private void gotoUiBuildFoundNext() {
        if (controller == null) {
            controller = new RushRepairController(this);
        }
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        controller.getRushExamine(examinesBean, buildFileBeanList, 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 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();
        }
    }

}
