package com.itant.shiwushu.ui.menu.post.publish;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.itant.shiwushu.MainActivity;
import com.itant.shiwushu.R;
import com.itant.shiwushu.base.BaseSkinActivity;
import com.itant.shiwushu.base.IPermission;
import com.itant.shiwushu.bean.City;
import com.itant.shiwushu.bean.LostFound;
import com.itant.shiwushu.bean.Province;
import com.itant.shiwushu.manager.CityManager;
import com.itant.shiwushu.manager.RealmManager;
import com.itant.shiwushu.manager.ToastManager;
import com.itant.shiwushu.tool.ActivityTool;
import com.itant.shiwushu.tool.PermissionTool;
import com.itant.shiwushu.tool.PhotoTool;
import com.itant.shiwushu.tool.file.FileTool;
import com.itant.shiwushu.ui.city.ProvinceActivity;

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

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

/**
 * Created by Jason on 2018/10/9.
 */

public class PublishPostActivity extends BaseSkinActivity implements View.OnClickListener,
        RadioGroup.OnCheckedChangeListener, IPermission, PublishPostContract.View {
    private static final int PHOTO_MAX_SIZE = 2 * 1024 * 1024;
    private static final int REQUEST_PHOTO = 1;
    private static final String[] PERMISSIONS_NECESSARY = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    public static final String KEY_POST_TYPE = "post_type";
    public static final int POST_TYPE_LOST = 0;
    public static final int POST_TYPE_FOUND = 1;

    private TextView tv_city_name;
    private EditText et_phone;
    private EditText et_money;
    private EditText et_desc;
    private AppCompatImageView aciv_related_photo;

    private int cityId;
    private String cityName;
    private int postType;
    private static final int TYPE_NONE = 404;
    private int lostType = TYPE_NONE;
    private File photoFile;
    private File targetFile;


    private PublishPostPresenter presenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_post);

        // 刚开始是没有选城市的
        CityManager.getInstance().restorePublishCity();

        tv_city_name = findViewById(R.id.tv_city_name);
        et_phone = findViewById(R.id.et_phone);
        et_money = findViewById(R.id.et_money);
        et_desc = findViewById(R.id.et_desc);
        LinearLayout ll_money = findViewById(R.id.ll_money);
        TextView tv_post_title = findViewById(R.id.tv_post_title);
        LinearLayout ll_lost_type = findViewById(R.id.ll_lost_type);
        RadioGroup rg_lost_type = findViewById(R.id.rg_lost_type);
        rg_lost_type.setOnCheckedChangeListener(this);
        findViewById(R.id.aciv_back).setOnClickListener(this);
        findViewById(R.id.ll_post).setOnClickListener(this);
        findViewById(R.id.tv_publish).setOnClickListener(this);
        aciv_related_photo = findViewById(R.id.aciv_related_photo);
        aciv_related_photo.setOnClickListener(this);

        // 如果是失物启事，才显示失物类型
        postType = getIntent().getIntExtra(KEY_POST_TYPE, POST_TYPE_LOST);
        if (postType == POST_TYPE_FOUND) {
            ll_lost_type.setVisibility(View.GONE);
            tv_post_title.setText("招领启事");
            et_desc.setHint("简要描述实际情况");
            ll_money.setVisibility(View.GONE);
        } else {
            ll_lost_type.setVisibility(View.VISIBLE);
            tv_post_title.setText("失物启事");
            ll_money.setVisibility(View.VISIBLE);
        }

        presenter = new PublishPostPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.aciv_back:
                onBackPressed();
                break;

            case R.id.ll_post:
                // 选择城市
                List<Province> provinceList = RealmManager.getInstance().getProvinceList();
                if (provinceList == null) {
                    ToastManager.getInstance().toastShort("城市加载失败");
                }
                Intent intent = new Intent(this, ProvinceActivity.class);
                intent.putExtra(MainActivity.KEY_CITY_TYPE, MainActivity.CODE_CITY_PUBLISH);
                ActivityTool.startActivityForResult(this, intent, MainActivity.CODE_CITY_PUBLISH);
                break;

            case R.id.aciv_related_photo:
                // 选择图片之前，要先判断权限
                PermissionTool.initPermission(this,this, PERMISSIONS_NECESSARY, REQUEST_PHOTO);
                break;

            case R.id.tv_publish:
                // 发布帖子
                publishPost();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        showExitDataDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.setView(null);
    }

    /**
     * 询问是否退出
     */
    private void showExitDataDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage("确定不保存任何内容，退出发布界面？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).create();
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == MainActivity.CODE_CITY_PUBLISH) {
            City city = CityManager.getInstance().getPublishCity();
            cityId = city.getCityId();
            if (city.getProvinceName().endsWith("市")) {
                cityName = city.getName();
            } else {
                cityName = city.getProvinceName() + city.getName();
            }

            tv_city_name.setText(cityName);
        }

        if (requestCode == PhotoPicker.REQUEST_CODE) {
            if (data == null) {
                return;
            }
            ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            if (photos.size() == 1) {
                String sourceFilePath = photos.get(0);
                RequestOptions options = new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .skipMemoryCache(true)
                        .signature(new ObjectKey(System.currentTimeMillis()));
                photoFile = new File(sourceFilePath);
                Glide.with(this).load(photoFile)
                        .apply(options)
                        .into(aciv_related_photo);
            }
        }
    }

    private void publishPost() {
        if (cityId == 0) {
            ToastManager.getInstance().toastShort("请选择城市");
            return;
        }

        final String phoneNumber = et_phone.getText().toString();
        if (TextUtils.isEmpty(phoneNumber)) {
            ToastManager.getInstance().toastShort("请填写联系方式");
            return;
        }

        int money = 0;
        String moneyString = et_money.getText().toString();
        if (!TextUtils.isEmpty(moneyString)) {
            money = Integer.parseInt(moneyString);
        }

        final String content = et_desc.getText().toString();
        if (TextUtils.isEmpty(content)) {
            ToastManager.getInstance().toastShort("请输入描述内容");
            return;
        }

        if (postType == LostFound.POST_TYPE_LOST && lostType == TYPE_NONE) {
            ToastManager.getInstance().toastShort("请选择失物类型");
            return;
        }

        // 如果图片大于2MB
        if (photoFile != null && photoFile.length() > PHOTO_MAX_SIZE) {
            // 先压缩图片到我们的内部存储，然后看压缩后的大小，如果还是大于2MB，则提示用户图片太大
            Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
                @Override
                //将事件发射出去,持有观察者的对象
                public void subscribe(ObservableEmitter<String> e) throws Exception {
                    String fileName = photoFile.getName();
                    File publishDir = FileTool.getPublishDir(PublishPostActivity.this);
                    boolean dirExist = true;
                    if (!publishDir.exists()) {
                        dirExist = publishDir.mkdirs();
                    }

                    if (dirExist) {
                        targetFile = new File(publishDir, fileName);
                        PhotoTool.compressAndSavePhoto(photoFile, targetFile, PHOTO_MAX_SIZE);
                        e.onNext("compress completed");
                        e.onComplete();
                    }
                }
            });

            final int finalMoney = money;
            observable.observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(String beans) {
                            setLoading(true);
                            // 开始发布帖子
                            presenter.publishPost(cityId, cityName, phoneNumber, finalMoney, postType, lostType, content, targetFile);
                        }

                        @Override
                        public void onError(Throwable e) {
                            ToastManager.getInstance().toastShort("请选择小于2MB的图片");
                        }

                        @Override
                        public void onComplete() {

                        }
                    });

        } else {
            setLoading(true);
            // 开始发布帖子
            presenter.publishPost(cityId, cityName, phoneNumber, money, postType, lostType, content, photoFile);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_man:
                lostType = LostFound.LOST_TYPE_MAN;
                break;
            case R.id.rb_goods:
                lostType = LostFound.LOST_TYPE_GOODS;
                break;
            case R.id.rb_pets:
                lostType = LostFound.LOST_TYPE_PETS;
                break;
            default:
                lostType = TYPE_NONE;
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionTool.onActivityPermissionResult(this, requestCode, grantResults);
    }

    @Override
    public void onPermissionSuccess(int requestCode) {
        pickPhoto();
    }

    @Override
    public void onPermissionFail(int requestCode) {
        ToastManager.getInstance().toastShort("权限被拒绝");
    }

    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(false)
                .setShowGif(false)
                .setPreviewEnabled(false)
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    public void onRequestComplete() {
        setLoading(false);
    }

    @Override
    public void onPublishSuccess(LostFound lostFound) {
        ToastManager.getInstance().toastShort("发布成功，下拉刷新即可查看");
        finish();
    }

    @Override
    public void onPublishFailed(String message) {
        ToastManager.getInstance().toastShort(message);
    }
}
