package com.casic.dcms.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.casic.dcms.R;
import com.casic.dcms.adapter.ImageRecycleViewAdapter;
import com.casic.dcms.base.BaseCaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.mvp.presenter.ShopCaseSubmitPresenterImpl;
import com.casic.dcms.mvp.presenter.UploadImagePresenterImpl;
import com.casic.dcms.mvp.view.ICaseSubmitCaseView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.FileUtils;
import com.casic.dcms.utils.GlideLoadEngine;
import com.casic.dcms.utils.ItemDecorationSpace;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

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

import butterknife.BindView;
import butterknife.OnClick;

public class ThreePackageUploadActivity extends BaseCaseActivity implements View.OnClickListener,
        IUploadFileView, ICaseSubmitCaseView {

    private Context context = ThreePackageUploadActivity.this;
    @BindView(R.id.shopView)
    TextView shopView;
    @BindView(R.id.communityView)
    EditText communityView;
    @BindView(R.id.longitudeView)
    TextView longitudeView;
    @BindView(R.id.latitudeView)
    TextView latitudeView;
    @BindView(R.id.shopKeeperView)
    EditText shopKeeperView;
    @BindView(R.id.phoneNumberView)
    EditText phoneNumberView;
    @BindView(R.id.caseLocationView)
    EditText caseLocationView;
    @BindView(R.id.caseDetailEditView)
    EditText caseDetailEditView;
    @BindView(R.id.selectedResultView)
    RecyclerView selectedResultView;
    @BindView(R.id.addImageView)
    ImageView addImageView;
    @BindView(R.id.submitButton)
    QMUIRoundButton submitButton;

    private UploadImagePresenterImpl uploadImagePresenter;
    private ShopCaseSubmitPresenterImpl shopCaseSubmitPresenter;
    private ImageRecycleViewAdapter imageAdapter;
    private QMUITipDialog submitDialog;
    private ArrayList<String> realPaths = new ArrayList<>();//真是图片路径
    private List<String> mediaList = new ArrayList<>();//上传到服务器的数据集
    private String gridId, shopID;

    @Override
    public int initLayoutView() {
        return R.layout.activity_package;
    }

    @Override
    protected String setTitleName() {
        return "三包上报";
    }

    @Override
    public void initData() {
        uploadImagePresenter = new UploadImagePresenterImpl(this);
        shopCaseSubmitPresenter = new ShopCaseSubmitPresenterImpl(this);
        submitDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("提交中，请稍后")
                .create();
        imageAdapter = new ImageRecycleViewAdapter(this);
        selectedResultView.setLayoutManager(new GridLayoutManager(this, 2));
        selectedResultView.addItemDecoration(new ItemDecorationSpace());
        selectedResultView.setAdapter(imageAdapter);
    }

    @Override
    public void initEvent() {
        submitButton.setChangeAlphaWhenPress(true);
    }

    @OnClick({R.id.shopLayout, R.id.addImageView, R.id.submitButton})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shopLayout:
                Intent intent = new Intent(this, ArcGISMapActivity.class);
                intent.putExtra("type", "三包上报");
                startActivityForResult(intent, Constant.REQUEST_MAP_CODE);
                break;
            case R.id.addImageView:
                new QMUIDialog.MenuDialogBuilder(this)
                        .addItem("相册中选取", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //选图
                                selectPicture();
                            }
                        })
                        .addItem("相机拍照", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //拍照
                                takePicture();
                            }
                        })
                        .setCanceledOnTouchOutside(false)
                        .create().show();
                break;
            case R.id.submitButton:
                submitCase();
                break;
        }
    }

    private void selectPicture() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideLoadEngine.createGlideEngine())
                .maxSelectNum(2)
                .isCompress(true)
                .compressQuality(80)
                .compressSavePath(FileUtils.getImageCompressPath())
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void takePicture() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .imageEngine(GlideLoadEngine.createGlideEngine())
                .maxSelectNum(1)
                .isCompress(true)
                .compressQuality(80)
                .compressSavePath(FileUtils.getImageCompressPath())
                .forResult(PictureConfig.REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        String mediaCompressPath = media.getCompressPath();
                        uploadImagePresenter.onReadyRetrofitRequest(new File(mediaCompressPath));
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
                    uploadImagePresenter.onReadyRetrofitRequest(new File(localMedia.getCompressPath()));
                    break;
                case Constant.REQUEST_MAP_CODE:
                    if (data == null) {
                        return;
                    }
                    double longitude = data.getDoubleExtra("longitude", 0);
                    double latitude = data.getDoubleExtra("latitude", 0);
                    gridId = data.getStringExtra("gridId");
                    String community = data.getStringExtra("community");
                    String shopName = data.getStringExtra("shopName");
                    shopID = data.getStringExtra("shopID");

                    longitudeView.setText(String.valueOf(longitude));
                    latitudeView.setText(String.valueOf(latitude));
                    communityView.setText(community);
                    shopView.setText(shopName);
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 案卷提交
     */
    private void submitCase() {
        String longitude = longitudeView.getText().toString();
        String latitude = latitudeView.getText().toString();
        if (longitude.equals("0") || latitude.equals("0") || TextUtils.isEmpty(longitude) || TextUtils.isEmpty(latitude)) {
            ToastHelper.showToast("经纬度异常，请重新选择位置", ToastHelper.WARING);
            return;
        }
        String shopKeeper = shopKeeperView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(shopKeeper)) {
            ToastHelper.showToast("店主名还未填写", ToastHelper.WARING);
            return;
        }
        String phoneNumber = phoneNumberView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastHelper.showToast("电话号码还未填写", ToastHelper.WARING);
            return;
        }
        if (StringHelper.isPhoneNumber(phoneNumber)) {
            String fieldIntro = caseLocationView.getText().toString().trim().replace(" ", "");
            if (TextUtils.isEmpty(fieldIntro)) {
                ToastHelper.showToast("案卷地点还未填写", ToastHelper.WARING);
                return;
            }
            String description = caseDetailEditView.getText().toString().trim().replace(" ", "");
            if (TextUtils.isEmpty(description)) {
                ToastHelper.showToast("案卷情况还未填写", ToastHelper.WARING);
                return;
            }
            if (imageAdapter.getItemCount() != 2) {
                ToastHelper.showToast("必须选择两张图片", ToastHelper.WARING);
                return;
            }
            shopCaseSubmitPresenter.onReadyRetrofitRequest("0", "0", longitude, latitude,
                    "2", "1",
                    gridId.substring(0, 6),
                    gridId.substring(0, 9),
                    gridId.substring(0, 12),
                    gridId, description, fieldIntro,
                    StringHelper.reformatURL(mediaList), 0, 0, shopID, shopKeeper, phoneNumber);
        } else {
            ToastHelper.showToast("电话号码格式不对", ToastHelper.WARING);
        }
    }

    @Override
    public void showProgress() {
        submitDialog.show();
    }

    @Override
    public void hideProgress() {
        submitDialog.dismiss();
    }

    @Override
    public void obtainSubmitResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            ToastHelper.showToast("提交成功", ToastHelper.SUCCESS);
            finish();
        } else {
            ToastHelper.showToast("提交失败，请重试", ToastHelper.ERROR);
        }
    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainUploadImageResult(ActionResultBean resultBean) {
        if (resultBean.isSuccess()) {
            PictureFileUtils.deleteAllCacheDirFile(this);
            /**
             * 系统路径static拼接图片返回路径
             * http://111.198.10.15:11409/static/2021-04/000bcf78345f4c1c86484efa3f9d68a2.jpeg
             */
            //2021-04\\000bcf78345f4c1c86484efa3f9d68a2.jpeg
            int sumItemCount = imageAdapter.getItemCount() + 1;//每上传一张图片，图片总数都是在原有的基础上+1
            if (sumItemCount <= 2) {
                String url = resultBean.getData();
                mediaList.add(url);
                realPaths.add(StringHelper.appendCompleteURL(url));
                if (realPaths.size() == 2) {
                    addImageView.setVisibility(View.GONE);
                }
                imageAdapter.setMediaList(realPaths);
                //九宫格点击事件
                imageAdapter.setOnItemClickListener(new ImageRecycleViewAdapter.OnItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        OtherUtils.showBigImage(context, position, realPaths);
                    }
                });
                //删除按钮点击事件
                imageAdapter.setOnDeleteClickListener(new ImageRecycleViewAdapter.OnDeleteItemClickListener() {
                    @Override
                    public void onClick(int position) {
                        realPaths.remove(position);
                        imageAdapter.setMediaList(realPaths);
                        if (realPaths.size() != 2) {
                            addImageView.setVisibility(View.VISIBLE);
                        }
                    }
                });
            } else {
                ToastHelper.showToast("最多只能上传2张图片", ToastHelper.WARING);
            }
        }
    }

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {

    }
}
