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

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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.multi.InfoMultiAdapter;
import com.gingersoft.gsa.cloud.ui.bean.InfoMultiBean;
import com.gingersoft.gsa.cloud.ui.bean.MultiSelectBean;
import com.gingersoft.gsa.cloud.ui.bean.SectionCheckItem;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
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.PurchaseFoodListVosBean;
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 java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.ui.adapter.multi.MultiUploadPicProvider.CHOOSE_PHOTO;
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;


/**
 * ================================================
 * 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 int EDIT_FOOD_RESULT_CODE = 1060;

    public static NewFoodIngredientsFragment newInstance(PurchaseFoodListVosBean purchaseFoodListVosBean) {
        NewFoodIngredientsFragment fragment = new NewFoodIngredientsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(FOOD_INFO_KEY, purchaseFoodListVosBean);
        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) {
                        //權限通過

                    } else {
                        killMyself();
                    }
                });

        initTopBar();
        //加載佈局
        Bundle arguments = getArguments();
        PurchaseFoodListVosBean purchaseFoodListVosBean = null;
        if (arguments != null) {
            purchaseFoodListVosBean = (PurchaseFoodListVosBean) arguments.getSerializable(FOOD_INFO_KEY);
        }
        infoMultiAdapter = new InfoMultiAdapter(mContext, mPresenter.getFragmentInfo(purchaseFoodListVosBean));
        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) {
                //選擇圖片
                Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intentToPickPic, CHOOSE_PHOTO);
            }
        });
        rvNewFoodIngredients.setAdapter(infoMultiAdapter);
    }

    private void initTopBar() {
        topbarNewFoodIngredients.setTitle("新增食材");
        topbarNewFoodIngredients.addLeftBackImageButton().setOnClickListener(v -> killMyself());
    }

    @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 && data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                String filePath = FileUtils.getFilePathByUri(mContext, uri);
                if (!TextUtils.isEmpty(filePath)) {
                    mPresenter.uploadPic(filePath);
                }
            } else {
                ToastUtils.show(mContext, "圖片路徑獲取失敗");
            }
        }
//        else if (requestCode == TAKE_PHOTO) {
        //拍照
//        }
    }

//    private String mTempPhotoPath;
//    private Uri imageUri;
//
//    private void takePhoto() {
//        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        File fileDir = new File(Environment.getExternalStorageDirectory() + File.separator + "photoTest" + File.separator);
//        if (!fileDir.exists()) {
//            fileDir.mkdirs();
//        }
//
//        File photoFile = new File(fileDir, "photo.jpeg");
//        mTempPhotoPath = photoFile.getAbsolutePath();
//        imageUri = FileProvider7.getUriForFile(this, photoFile);
//        intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//        startActivityForResult(intentToTakePhoto, RC_TAKE_PHOTO);
//    }

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

}
