package com.gingersoft.supply_chain.mvp.ui.fragment.food;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.utils.FileUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.adapter.bean.InfoMultiBean;
import com.gingersoft.gsa.cloud.ui.adapter.bean.MultiSelectBean;
import com.gingersoft.gsa.cloud.ui.adapter.multi.InfoMultiAdapter;
import com.gingersoft.gsa.cloud.ui.bean.SectionCheckItem;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerNewFoodIngredientsComponent;
import com.gingersoft.supply_chain.mvp.bean.FoodPackingSpecificationBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean;
import com.gingersoft.supply_chain.mvp.contract.NewFoodIngredientsContract;
import com.gingersoft.supply_chain.mvp.presenter.NewFoodIngredientsPresenter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.jess.arms.di.component.AppComponent;
import com.permissionx.guolindev.PermissionX;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration.VERTICAL_LIST;
import static com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment.SELECT_CATEGORY_DATA_KEY;
import static com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment.SELECT_FOOD_CATEGORY_REQUEST_CODE;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.PackageSpecificationFragment.FOOD_PACKING_SPECIFICATION_DATA_KEY;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.PackageSpecificationFragment.SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE;
import static com.gingersoft.supply_chain.mvp.ui.fragment.food.PackageSpecificationFragment.SELECT_PACKAGE_SPECIFICATION_RESULT_CODE;
import static com.gingersoft.supply_chain.mvp.ui.fragment.supplier.SupplierListFragment.SELECT_SUPPLIER_DATA;
import static com.gingersoft.supply_chain.mvp.ui.fragment.supplier.SupplierListFragment.SELECT_SUPPLIER_RESULTCODE;
import static com.yalantis.ucrop.UCrop.REQUEST_CROP;


/**
 * ================================================
 * Description: 新增食材、編輯食材
 */
public class NewFoodIngredientsFragment extends BaseSupplyChainFragment<NewFoodIngredientsPresenter> implements NewFoodIngredientsContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_new_food_ingredients)
    QMUITopBar topbarNewFoodIngredients;
    @BindView(R2.id.btn_save_new_food_ingredients)
    QMUIAlphaButton btnSaveNewFoodIngredients;
    @BindView(R2.id.rv_new_food_ingredients)
    RecyclerView rvNewFoodIngredients;

    private InfoMultiAdapter infoMultiAdapter;

    public final static String FOOD_INFO_KEY = "foodInfoKey";
    public final static String SUPPLIER_NAME_KEY = "supplierName";
    public final static String CATEGORY_NAME_KEY = "categoryName";

    public final static int EDIT_FOOD_RESULT_CODE = 1060;
    /**
     * 是修改還是新增
     * ture:修改
     * false:新增
     */
    public boolean isUpdate = false;

    public static NewFoodIngredientsFragment newInstance(PurchaseFoodBean purchaseFoodBean) {
        NewFoodIngredientsFragment fragment = new NewFoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(FOOD_INFO_KEY, purchaseFoodBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static NewFoodIngredientsFragment newInstance(String supplierName, String categoryName) {
        NewFoodIngredientsFragment fragment = new NewFoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(SUPPLIER_NAME_KEY, supplierName);
        bundle.putSerializable(CATEGORY_NAME_KEY, categoryName);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerNewFoodIngredientsComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_new_food_ingredients, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        PermissionX.init(this)
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "上傳食材圖片需要文件讀取權限", "確定", "取消"))
                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去設置當中開啟文件讀取權限", "確定", "取消"))
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        //權限通過
                        killMyself();
                    }
                });
        Bundle arguments = getArguments();
        PurchaseFoodBean purchaseFoodBean;
        if (arguments != null) {
            purchaseFoodBean = (PurchaseFoodBean) arguments.getSerializable(FOOD_INFO_KEY);
            if (purchaseFoodBean == null) {
                isUpdate = false;
                initTopBar(topbarNewFoodIngredients, "新增食材");
                purchaseFoodBean = new PurchaseFoodBean();
            } else {
                isUpdate = true;
                mPresenter.setPurchaseFoodBean(purchaseFoodBean);
                initTopBar(topbarNewFoodIngredients, "編輯食材");
            }
            purchaseFoodBean.setFoodCategoryName(arguments.getString(CATEGORY_NAME_KEY));
            purchaseFoodBean.setSupplierName(arguments.getString(SUPPLIER_NAME_KEY));
        }
        infoMultiAdapter = new InfoMultiAdapter(mContext, mPresenter.getFragmentInfo());
        rvNewFoodIngredients.addItemDecoration(new DividerItemDecoration(mContext, VERTICAL_LIST));
        infoMultiAdapter.setOnItemClickListener((adapter, view, position) -> {
            List<InfoMultiBean> data = infoMultiAdapter.getData();
            InfoMultiBean infoMultiBean = data.get(position);
            if (infoMultiBean.getItemType() == InfoMultiBean.EDIT_FOOD_ITEM_SELECT) {
                if (infoMultiBean instanceof MultiSelectBean) {
                    MultiSelectBean multiBean = (MultiSelectBean) infoMultiBean;
                    startForResult(infoMultiBean.getFragment(), multiBean.getRequestCode());
                }
            }
        });
        //圖片點擊事件
        infoMultiAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_multi_upload_pic) {
                //拍照或者選擇圖片
                PermissionX.init(this).permissions(Manifest.permission.CAMERA)
                        .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "上傳圖片需要獲取拍照權限", "確定", "取消"))
                        .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去設置當中開啟拍照權限", "確定", "取消"))
                        .request((allGranted, grantedList, deniedList) -> showPictureChoice());
            }
        });
        rvNewFoodIngredients.setAdapter(infoMultiAdapter);
    }

    final String[] items = new String[]{"拍照", "從相冊選擇", "取消"};
    public static final int CHOOSE_PHOTO = 101;
    public static final int TAKE_PHOTO = 102;
    public static final int PHOTO_CROP = 103;

    public void showPictureChoice() {
        AppDialog.getInstance().showListDialog(mContext, items, (view, dialog, position) -> {
            if (position == 0) {
                takePhoto();
            } else if (position == 1) {
                Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intentToPickPic, CHOOSE_PHOTO);
            }
        });
    }

    private void takePhoto() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (photoFile != null) {
                Uri photoUri = FileProvider.getUriForFile(mContext,
                        mContext.getPackageName() + ".fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            }
            startActivityForResult(takePictureIntent, TAKE_PHOTO);
        } else {
            ToastUtils.show(mContext, "請安裝相機");
        }
    }

    String currentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
//        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File cacheDir = mContext.getCacheDir();
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                cacheDir      /* directory */
        );
        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        mCameraUri = Uri.fromFile(image);
        return image;
    }

    @OnClick({R2.id.btn_save_new_food_ingredients})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_save_new_food_ingredients) {
            //保存
            String msg = mPresenter.verificationData(infoMultiAdapter.getData());
            if (TextUtil.isNotEmptyOrNullOrUndefined(msg)) {
                ToastUtils.show(mContext, msg);
            } else {
                mPresenter.addFoodInfo(mPresenter.getFoodInfoByInfoMulti(infoMultiAdapter.getData()));
            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == SELECT_SUPPLIER_RESULTCODE) {
                //選擇供應商
                SupplierInfoBean supplierInfoBean = (SupplierInfoBean) data.get(SELECT_SUPPLIER_DATA);
                if (supplierInfoBean != null) {
                    mPresenter.setSupplierInfo(supplierInfoBean, infoMultiAdapter.getData());
                }
            } else if (requestCode == SELECT_PACKAGE_SPECIFICATION_REQUEST_CODE && resultCode == SELECT_PACKAGE_SPECIFICATION_RESULT_CODE) {
                //選擇包裝規格
                List<FoodPackingSpecificationBean> foodPackingSpecifications = (List<FoodPackingSpecificationBean>) data.get(FOOD_PACKING_SPECIFICATION_DATA_KEY);
                mPresenter.setPackingInfo(foodPackingSpecifications, infoMultiAdapter.getData());
            } else if (requestCode == SELECT_FOOD_CATEGORY_REQUEST_CODE) {
                //選擇食材類別
                List<SectionCheckItem> sectionCheckItems = (List<SectionCheckItem>) data.get(SELECT_CATEGORY_DATA_KEY);
                if (sectionCheckItems != null) {
                    mPresenter.setCategoryInfo(sectionCheckItems, infoMultiAdapter.getData());
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHOOSE_PHOTO && resultCode == RESULT_OK) {
            //從相冊選取完圖片之後，
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    File file = uriToFileApiQ(uri);
                    crop(Uri.fromFile(file));
                }
            }
        } else if (requestCode == TAKE_PHOTO && resultCode == RESULT_OK) {
            //拍照
            //拍照完成後需要裁剪
            crop(mCameraUri);
        } else if (requestCode == REQUEST_CROP && resultCode == RESULT_OK && data != null) {
            final Uri resultUri = UCrop.getOutput(data);
            Log.e("eee", "路徑：" + resultUri);
            if (resultUri != null) {
                String filePath = FileUtils.getFilePathByUri(mContext, resultUri);
                if (!TextUtils.isEmpty(filePath)) {
                    mPresenter.uploadPic(filePath);
                }
            }
        }
    }

    /**
     * 裁剪
     *
     * @param mCameraUri
     */
    private void crop(Uri mCameraUri) {
        UCrop.of(mCameraUri, mCameraUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(500, 500)
                .start(mContext, this);
    }

    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) {
            return null;
        }
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public File uriToFileApiQ(Uri uri) {
        File file = null;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = mContext.getContentResolver();
            Cursor cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                try {
                    InputStream is = contentResolver.openInputStream(uri);
                    File cache = new File(mContext.getExternalCacheDir().getAbsolutePath(), Math.round((Math.random() + 1) * 1000) + displayName);
                    FileOutputStream fos = new FileOutputStream(cache);
                    android.os.FileUtils.copy(is, fos);
                    file = cache;
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    //用于保存拍照图片的uri
    private Uri mCameraUri;

    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private String mCameraImagePath;

    // 是否是Android 10以上手机
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;

    /**
     * 调起相机拍照
     */
    private void openCamera() {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (captureIntent.resolveActivity(mContext.getPackageManager()) != null) {
            File photoFile = null;
            Uri photoUri = null;

            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri();
            } else {
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                        photoUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", photoFile);
                    } else {
                        photoUri = Uri.fromFile(photoFile);
                    }
                }
            }

            mCameraUri = photoUri;
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(captureIntent, TAKE_PHOTO);
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return mContext.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

//    /**
//     * 创建保存图片的文件
//     */
//    private File createImageFile() throws IOException {
//        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
//        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        if (!storageDir.exists()) {
//            storageDir.mkdir();
//        }
//        File tempFile = new File(storageDir, imageName);
//        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
//            return null;
//        }
//        return tempFile;
//    }

    @Override
    public void refreshAdapterByPosition(int position) {
        if (infoMultiAdapter != null) {
            infoMultiAdapter.notifyItemChanged(position);
        }
    }

    @Override
    public void uploadPicSuccess(List<String> picUrl) {
//        List<InfoMultiBean> data = infoMultiAdapter.getData();
//        InfoMultiBean infoMultiBean = data.get(mPresenter.picIndex);
//        if (infoMultiBean instanceof UploadPicMultiBean) {
//            UploadPicMultiBean uploadPicMultiBean = (UploadPicMultiBean) infoMultiBean;
//            uploadPicMultiBean.setPicUrl(picUrl);
//            refreshAdapterByPosition(mPresenter.picIndex);
//        }
        mPresenter.setPicUrl(infoMultiAdapter.getData(), picUrl);
    }

    @Override
    public void saveFoodInfoSuccess() {
        setFragmentResult(EDIT_FOOD_RESULT_CODE, null);
        killMyself();
    }

}
