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.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.BaseMapActivity;
import com.tofly.ghrq_route.common.ui.adapter.BuildappendAdapter;
import com.tofly.ghrq_route.common.util.ArcgisUtils.SizeMarkerSymbol;
import com.tofly.ghrq_route.common.util.NoListView;
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.BuildManageFileBean;
import com.tofly.ghrq_route.module.rushrepair.RushRepairTool;
import com.tofly.ghrq_route.module.rushrepair.controller.RushRepairCallback;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairBean;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairExamineBean;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairFileBean;
import com.tofly.ghrq_route.module.rushrepair.domain.RushRepairProcessBean;
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.latte_core.base.IPresenter;

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

import butterknife.BindView;

/**
 * @author YCHK
 * 抢维修历史详情
 */
public class UiRushRepairHistoryDetail extends BaseMapActivity {
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.tv_current_address)
    TextView tvCurrentAddress;
    @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_rush_note)
    TextView tvRushNote;
    @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_part)
    TextView tvPart;
    @BindView(R.id.tv_dispatch_time)
    TextView tvDispatchTime;
    @BindView(R.id.tv_note)
    TextView tvNote;
    @BindView(R.id.ll_dispatch)
    LinearLayout llDispatch;
    @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;

    private RushRepairBean data;
    private BuildappendAdapter adapter, adapter1, adapter2;
    private DBDaoHelper dbDaoHelper;
    private List<buildFilesInfo> appendList, appendList1, appendList2;
    private List<TroublePictureBean> photos;
    private List<TroubleAudioBean> audioBeans;
    private List<BuildFileBean> buildFileBeans;
    private ArrayList<String> photoId, audioId, fileId;
    private RushRepairProcessBean rushRepairProcessBean;
    private String id;
    private int type;
    private MarkerSymbol buildMarker;
    private double x = 0.0, y = 0.0;

    @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 = (RushRepairBean) getIntent().getSerializableExtra("rushRepair");
        photoId = getIntent().getStringArrayListExtra("photoId");
        audioId = getIntent().getStringArrayListExtra("audioId");
        fileId = getIntent().getStringArrayListExtra("fileId");
        id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            rushRepairProcessBean = dbDaoHelper.getRushRepairProcess(id);
        }
        if (rushRepairProcessBean != null) {
            type = 4;
        } else {
            type = 3;
        }

        photos = new ArrayList<>();
        audioBeans = new ArrayList<>();
        buildFileBeans = new ArrayList<>();
        if (photoId != null && photoId.size() > 0) {
            for (String s : photoId) {
                photos.add(dbDaoHelper.getTroublePicture(s));
            }
        }
        if (audioId != null && audioId.size() > 0) {
            for (String s : audioId) {
                audioBeans.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() {

    }

    /**
     * 添加已知经纬度的图标
     */
    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.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.getDispatchDate())) {
                tvDispatchTime.setText(data.getDispatchDate());
            }
            //监护人
            if (!TextUtils.isEmpty(data.getResponsibleName())) {
                tvDispatch.setText(data.getResponsibleName());
            }
            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());
            }
            if (rushRepairProcessBean != null) {
                llDispatch.setVisibility(View.VISIBLE);
            }
            appendList = new ArrayList<>();
            if (rushRepairProcessBean == null) {
                llAppend.setVisibility(View.VISIBLE);
                loadAppendtionList(appendList, photos, audioBeans, buildFileBeans);
                adapter = new BuildappendAdapter(this, appendList);
                listAppendix.setAdapter(adapter);
            } else {
                llDispatch.setVisibility(View.VISIBLE);
                List<RushRepairFileBean> fileBeanList = dbDaoHelper.getRushRepairFile(data.getId());
                if (fileBeanList != null && fileBeanList.size() > 0) {
                    for (RushRepairFileBean 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, photos, audioBeans, buildFileBeans);
                llProcess.setVisibility(View.VISIBLE);
                View view1 = getProcessView(rushRepairProcessBean);
                llAdd.addView(view1);

                List<RushRepairExamineBean> examineBeans = dbDaoHelper.getRushExamine(data.getId());
                if (examineBeans != null && examineBeans.size() > 0) {
                    llExamine.setVisibility(View.VISIBLE);
                    for (RushRepairExamineBean repairExamineBean : examineBeans) {
                        View view = getExamineView(repairExamineBean);
                        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.getFilePath());
            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);
        RushRepairTool buildTool = RushRepairTool.getInstance();
        if (rushRepairProcessBean == null) {
            buildTool.addBuildJobManage(this, data, photos, audioBeans, buildFileBeans, true, new RushRepairCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        Toast.makeText(UiRushRepairHistoryDetail.this, "上传离线抢维修成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
        } else {
            buildTool.addRushManageProcess(this, rushRepairProcessBean, photos, audioBeans, buildFileBeans, true, new RushRepairCallback() {
                @Override
                public void onAddBuildManage(boolean isSuccess, int errorCode, String errMsg) {
                    super.onAddBuildManage(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess) {
                        Toast.makeText(UiRushRepairHistoryDetail.this, "上传离线工地过程管理成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }
            });
        }
    }

    private View getProcessView(RushRepairProcessBean 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(RushRepairExamineBean 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 void collectData() {
        if (mLastLocation != null) {
            if (type == 3) {
                data.setX(mLastLocation.getX());
                data.setY(mLastLocation.getY());
            }else {
                rushRepairProcessBean.setX(mLastLocation.getX());
                rushRepairProcessBean.setY(mLastLocation.getY());
            }
        }

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

    private boolean isValid() {
        collectData();

        boolean check = true;
        if (type == 3) {
            if (data.getAddress().isEmpty()) {
                if (!tvCurrentAddress.getText().toString().isEmpty()) {
                    data.setAddress(tvCurrentAddress.getText().toString());
                    data.setX(x);
                    data.setY(y);
                } else {
                    showToast("当前位置不能为空");
                    check = false;
                }
            }
        } else {
            if (rushRepairProcessBean.getX() == 0.0 || rushRepairProcessBean.getY() == 0.0) {
                if (!tvCurrentAddress.getText().toString().isEmpty()) {
                    rushRepairProcessBean.setX(x);
                    rushRepairProcessBean.setY(y);
                } else {
                    showToast("当前位置不能为空");
                    check = false;
                }
            }
        }
        return check;
    }

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

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

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

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

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

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

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

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

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

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