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

import android.annotation.SuppressLint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.MarkerSymbol;
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.BaseMapFileActivity;
import com.tofly.ghrq_route.common.ui.adapter.BuildappendAdapter;
import com.tofly.ghrq_route.common.ui.view.MyAudioRecordButton;
import com.tofly.ghrq_route.module.buildManage.BuildExamineBean;
import com.tofly.ghrq_route.module.buildManage.BuildTool;
import com.tofly.ghrq_route.module.buildManage.buildFilesInfo;
import com.tofly.ghrq_route.module.buildManage.controller.BuildManageCallback;
import com.tofly.ghrq_route.module.buildManage.domain.BuildFileBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildManageFileBean;
import com.tofly.ghrq_route.module.buildManage.domain.BuildProcessManageBean;
import com.tofly.ghrq_route.module.sqlite.DBDaoHelper;
import com.tofly.ghrq_route.module.trouble.domain.TroubleAudioBean;
import com.tofly.ghrq_route.module.trouble.domain.TroublePictureBean;
import com.tofly.ghrq_route.common.util.ArcgisUtils.SizeMarkerSymbol;
import com.tofly.ghrq_route.common.util.NoListView;
import com.tofly.latte_core.base.IPresenter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author YCHK
 * 工地未上报记录信息详情
 */
public class UiBuildHistoryDetailActivity extends BaseMapFileActivity {
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.tv_dqdz)
    TextView tvDqdz;
    @BindView(R.id.edit_build_name)
    TextView editBuildName;
    @BindView(R.id.text_build_type)
    TextView textBuildType;
    @BindView(R.id.text_build_address)
    TextView textBuildAddress;
    @BindView(R.id.tv_description)
    TextView tvDescription;
    @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.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_dispatch_note)
    TextView tvDispatchNote;
    @BindView(R.id.ll_add)
    LinearLayout llAdd;
    @BindView(R.id.ll_process)
    LinearLayout llProcess;
    @BindView(R.id.ll_examine_add)
    LinearLayout llExamineAdd;
    @BindView(R.id.ll_examine)
    LinearLayout llExamine;
    @BindView(R.id.ll_dispatch)
    LinearLayout llDispatch;

    private BuildManageBean data;
    private BuildappendAdapter adapter, adapter1, adapter2;
    private DBDaoHelper dbDaoHelper;
    private List<BuildFileBean> buildFileBeans;
    private ArrayList<String> photoId, audioId, fileId;
    private BuildProcessManageBean buildProcessManageBean;
    private List<buildFilesInfo> appendList, appendList1, appendList2;
    private String id;
    private int type;

    private MarkerSymbol buildMarker;

    @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);
    }

    @Override
    public void initView() {
        super.initView();

    }

    @Override
    public void initNet() {
        super.initNet();

        dbDaoHelper = DBDaoHelper.getInstance();
        data = (BuildManageBean) getIntent().getSerializableExtra("build_manage");
        photoId = getIntent().getStringArrayListExtra("photoId");
        audioId = getIntent().getStringArrayListExtra("audioId");
        fileId = getIntent().getStringArrayListExtra("fileId");
        id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            buildProcessManageBean = dbDaoHelper.getBuildProcess(id);
        }
        if (buildProcessManageBean != null) {
            type = 2;
        } else {
            type = 1;
        }

        buildFileBeans = new ArrayList<>();
        if (photoId != null && photoId.size() > 0) {
            for (String s : photoId) {
                mPicturesUpload.add(dbDaoHelper.getTroublePicture(s));
            }
        }
        if (audioId != null && audioId.size() > 0) {
            for (String s : audioId) {
                mAudiosRecords.add(dbDaoHelper.getTroubleAudio(s));
            }
        }
        if (fileId != null && fileId.size() > 0) {
            for (String s : fileId) {
                buildFileBeans.add(dbDaoHelper.getBuildFile(s, type));
            }
        }
        initNews();

        initListener();
    }

    @SuppressLint("ClickableViewAccessibility")
    public void initListener() {

    }

    @Override
    public void onBaseMapLoaded() {
        if (data != null) {
            initRenderSymbol();
        }
    }

    /**
     * 添加已知经纬度的图标
     */
    private void initRenderSymbol() {
        if (data.getX() != 0.0 && data.getX() != 0.0) {
            Drawable drawable = getResources().getDrawable(R.drawable.buildsite);
            buildMarker = SizeMarkerSymbol.sizeSymbol((BitmapDrawable) drawable, 18, 18);
            Graphic graphic = new Graphic(new Point(data.getX(), data.getY()), buildMarker);
            GraphicsOverlay graphicsOverlay = new GraphicsOverlay();
            graphicsOverlay.getGraphics().add(graphic);
            mapView.getGraphicsOverlays().add(graphicsOverlay);
        }
    }

    private void initNews() {
        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());
            }
            if (!TextUtils.isEmpty(data.getConstructionPersonName())) {
                tvDispatch.setText(data.getConstructionPersonName());
            }
            if (!TextUtils.isEmpty(data.getDispatchDate())) {
                tvDispatchTime.setText(data.getDispatchDate());
            }
            if (!TextUtils.isEmpty(data.getNote())) {
                tvDispatchNote.setText(data.getNote());
            }
            appendList = new ArrayList<>();
            if (buildProcessManageBean == null) {
                llAppend.setVisibility(View.VISIBLE);
                loadAppendtionList(appendList, mPicturesUpload, mAudiosRecords, buildFileBeans);
                adapter = new BuildappendAdapter(this, appendList);
                listAppendix.setAdapter(adapter);
            } else {
                llDispatch.setVisibility(View.VISIBLE);
                List<BuildManageFileBean> fileBeanList = dbDaoHelper.getBuildManageFile(data.getId());
                if (fileBeanList != null && fileBeanList.size() > 0) {
                    for (BuildManageFileBean fileBean : fileBeanList) {
                        buildFilesInfo info = new buildFilesInfo();
                        if (!TextUtils.isEmpty(fileBean.getVoicePath())) {
                            info.setId(data.getId() + "-" + fileBean.getId());
                            info.setPath(fileBean.getVoicePath());
                            info.setName(fileBean.getVoiceName());
                            appendList.add(info);
                        }
                        if (!TextUtils.isEmpty(fileBean.getFilePath())) {
                            buildFilesInfo info1 = new buildFilesInfo();
                            info1.setId(data.getId() + "-" + fileBean.getId());
                            info1.setPath(fileBean.getFilePath());
                            info1.setName(fileBean.getFileName());
                            appendList.add(info1);
                        }
                    }
                    if (appendList.size() > 0) {
                        llAppend.setVisibility(View.VISIBLE);
                    }
                    adapter = new BuildappendAdapter(this, appendList);
                    listAppendix.setAdapter(adapter);
                }

                appendList1 = new ArrayList<>();
                loadAppendtionList(appendList1, mPicturesUpload, mAudiosRecords, buildFileBeans);
                llProcess.setVisibility(View.VISIBLE);
                View view1 = getProcessView(buildProcessManageBean);
                llAdd.addView(view1);

                List<BuildExamineBean> examineBeans = dbDaoHelper.getBuildExamine(data.getId());
                if (examineBeans != null && examineBeans.size() > 0) {
                    llExamine.setVisibility(View.VISIBLE);
                    for (BuildExamineBean buildExamineBean : examineBeans) {
                        View view = getExamineView(buildExamineBean);
                        llExamineAdd.addView(view);
                    }
                }

            }
        }
    }

    private void loadAppendtionList(List<buildFilesInfo> appendLists, List<TroublePictureBean> photos, List<TroubleAudioBean> audioBeans, List<BuildFileBean> buildFileBeans) {
        for (TroublePictureBean pictureBean : photos) {
            buildFilesInfo info = new buildFilesInfo();
            info.setId(data.getId() + "-" + pictureBean.getId());
            info.setPath(pictureBean.getFilepath());
            File file = new File(pictureBean.getFilepath());
            if (file.exists())
                info.setName(file.getName());
            appendLists.add(info);
        }
        for (TroubleAudioBean audioBean : audioBeans) {
            buildFilesInfo info = new buildFilesInfo();
            info.setId(data.getId() + "-" + audioBean.getId());
            info.setPath(audioBean.getPath());
            File file = new File(audioBean.getPath());
            if (file.exists())
                info.setName(file.getName());
            appendLists.add(info);
        }
        for (BuildFileBean fileBean : buildFileBeans) {
            buildFilesInfo info = new buildFilesInfo();
            info.setId(data.getId() + "-" + fileBean.getId());
            info.setPath(fileBean.getFilePath());
            File file = new File(fileBean.getFileName());
            if (file.exists())
                info.setName(file.getName());
            appendLists.add(info);
        }
    }

    private void gotoUiBuildFoundNext() {
        String strUploading = getString(R.string.uploading_data);
        ProgressManager.getInstance().showProgress(this, null, strUploading, false);
        BuildTool buildTool = BuildTool.getInstance();
        if (buildProcessManageBean == null) {
            collectData();
            buildTool.addBuildManage(this, data, mPicturesUpload, mAudiosRecords, buildFileBeans, true, new BuildManageCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        Toast.makeText(UiBuildHistoryDetailActivity.this, "上传离线工地成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
        } else {
            buildTool.addBuildManageProcess(this, buildProcessManageBean, mPicturesUpload, mAudiosRecords, buildFileBeans, true, new BuildManageCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        Toast.makeText(UiBuildHistoryDetailActivity.this, "上传离线工地过程管理成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
        }
    }

    private View getProcessView(BuildProcessManageBean 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 llDate = view.findViewById(R.id.ll_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());
        } else {
            llDate.setVisibility(View.GONE);
        }
        ll_append1.setVisibility(View.VISIBLE);
        adapter1 = new BuildappendAdapter(this, appendList1);
        list_process.setAdapter(adapter1);
        return view;
    }

    private View getExamineView(BuildExamineBean 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_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())) {
            tv_examine_description.setText(buildExamineBean.getAuditDescription());
        }
        if (!TextUtils.isEmpty(buildExamineBean.getWorkOrderId()) && !TextUtils.isEmpty(buildExamineBean.getId())) {
            List<BuildManageFileBean> manageFileBeans = dbDaoHelper.getBuildManageFiles(buildExamineBean.getWorkOrderId(), buildExamineBean.getId());
            if (manageFileBeans != null && manageFileBeans.size() > 0) {
                appendList2 = new ArrayList<>();
                ll_append2.setVisibility(View.VISIBLE);
                for (BuildManageFileBean fileBean : manageFileBeans) {
                    buildFilesInfo info = new buildFilesInfo();
                    if (!TextUtils.isEmpty(fileBean.getAuditEndFilesPath())) {
                        info.setId(fileBean.getBuildId() + "-" + fileBean.getId());
                        info.setPath(fileBean.getAuditEndFilesPath());
                        info.setName(fileBean.getAuditEndFilesName());
                        appendList2.add(info);
                    }
                }
                adapter2 = new BuildappendAdapter(this, appendList2);
                list_examine.setAdapter(adapter2);
            }
        }

        return view;
    }

    private boolean isValid() {
        if (mLastLocation != null) {
            double lng = mLastLocation.getX();
            double lat = mLastLocation.getY();
            if (Double.isNaN(lng) && Double.isNaN(lat)) {
                showToast("当前位置不可用");
                return false;
            }
        }

        return true;
    }

    private void collectData() {
        if (mLastLocation != null) {
            data.setX(mLastLocation.getX());
            data.setY(mLastLocation.getY());
        }

        if (mAddress != null) {
            data.setConstructionAddress(mAddress);
        }
    }

    @Override
    protected IPresenter createPresenter() {
        return null;
    }

    @Override
    public int setLayout() {
        return R.layout.activity_build_history_detail;
    }

    @Override
    public boolean enableLoadMap() {
        return true;
    }

    @Override
    public boolean enableMoveMapListener() {
        return true;
    }

    @Override
    public boolean enableArcgisLocating() {
        return false;
    }

    @Override
    public boolean enableAmapLocationListener() {
        return true;
    }

    @Override
    public boolean enableMapMoveToLocation() {
        return true;
    }

    @Override
    public TextView getTextAddrView() {
        return tvDqdz;
    }

    @Override
    public Button getAddPhotoBtn() {
        return null;
    }

    @Override
    public LinearLayout getPhotoGallery() {
        return null;
    }

    @Override
    public MyAudioRecordButton getAudioRecordBtn() {
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        BaseApp.cancelAllRequest(getClass().getName());
    }
}
