package com.wd.workoffice.ui.activity.mes.ticket;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.event.AddSummarytEvent;
import com.wd.workoffice.bean.event.AddTicketEvent;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.bean.mesBean.MesProBean;
import com.wd.workoffice.bean.mesBean.TicketBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.AnnexAdapter;
import com.wd.workoffice.ui.adapter.ImgAddAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.Glide4Engine;
import com.wd.workoffice.util.WorkUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

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

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.FileUtils;
import io.reactivex.disposables.Disposable;
import me.rosuh.filepicker.config.FilePickerManager;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 工单新增
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesTicketAddSummaryActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_design_confirm)
    TextView tvDesignConfirm;
    @BindView(R.id.et_design1)
    EditText etDesign1;
    @BindView(R.id.et_design2)
    EditText etDesign2;
    @BindView(R.id.ll_design)
    LinearLayout llDesign;
    @BindView(R.id.tv_try_pro)
    TextView tvTryPro;
    @BindView(R.id.rl_try_pro)
    RelativeLayout rlTryPro;
    @BindView(R.id.et_try1)
    EditText etTry1;
    @BindView(R.id.et_try2)
    EditText etTry2;
    @BindView(R.id.et_try3)
    EditText etTry3;
    @BindView(R.id.ll_try)
    LinearLayout llTry;
    @BindView(R.id.tv_quality_pro)
    TextView tvQualityPro;
    @BindView(R.id.rl_quality_pro)
    RelativeLayout rlQualityPro;
    @BindView(R.id.et_quality1)
    EditText etQuality1;
    @BindView(R.id.et_quality2)
    EditText etQuality2;
    @BindView(R.id.et_quality3)
    EditText etQuality3;
    @BindView(R.id.et_quality4)
    EditText etQuality4;
    @BindView(R.id.ll_quality)
    LinearLayout llQuality;
    @BindView(R.id.tv_tech_pro)
    TextView tvTechPro;
    @BindView(R.id.rl_tech_pro)
    RelativeLayout rlTechPro;
    @BindView(R.id.et_tech1)
    EditText etTech1;
    @BindView(R.id.et_tech2)
    EditText etTech2;
    @BindView(R.id.et_tech3)
    EditText etTech3;
    @BindView(R.id.ll_tech)
    LinearLayout llTech;
    @BindView(R.id.et_tender1)
    EditText etTender1;
    @BindView(R.id.et_tender2)
    EditText etTender2;
    @BindView(R.id.ll_tender)
    LinearLayout llTender;
    @BindView(R.id.et_client)
    EditText etClient;
    @BindView(R.id.rv_photo)
    RecyclerView rvPhoto;
    @BindView(R.id.rv_annex)
    RecyclerView rvAnnex;
    private Map<String, Object> param;
    private TicketBean.ListBean data;
    private QMUIDialog.MenuDialogBuilder proDialog;
    private MesProBean.ListBean choosePro;
    private List<ImageBean> imgList;
    private List<ImageBean> annexList;
    private ImgAddAdapter imgAddAdapter;
    private AnnexAdapter annexAdapter;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvAnnex.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvPhoto.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        data = JSON.parseObject(getIntent().getStringExtra("data"), TicketBean.ListBean.class);
        changVisibility(data.getJobTypeId());
        proDialog = DialogUtils.listDialog(this);
        proDialog.addItems(new String[]{"是", "否"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0)
                    param.put("productDrawingConfirmation", 1);
                else
                    param.put("productDrawingConfirmation", 0);
                dialog.dismiss();
                tvDesignConfirm.setText(which == 0 ? "是" : "否");
            }
        });
    }

    @Override
    protected void initData() {
        param = WorkUtils.simpleParam();
        param.put("jobNo", data.getJobNo());
        param.put("jobTypeId", data.getJobTypeId());
        param.put("dataCollectionStatus", 1);
        annexList = new ArrayList<>();
        imgList = new ArrayList<>();
        ImageBean imageBean = new ImageBean();
        imageBean.setUri(null);
        imgList.add(imageBean);
        imgAddAdapter = new ImgAddAdapter(R.layout.item_mes_ticket_img, imgList);
        imgAddAdapter.bindToRecyclerView(rvPhoto);
        annexAdapter = new AnnexAdapter(R.layout.item_mes_ticket_annex, annexList);
        annexAdapter.bindToRecyclerView(rvAnnex);
    }

    @Override
    protected void initEvent() {
        imgAddAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                imgList.remove(position);
                imgAddAdapter.notifyDataSetChanged();
            }
        });
        imgAddAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position==imgList.size()-1){
                    addImg();
                }
            }
        });
        annexAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                annexList.remove(position);
                annexAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_mes_ticket_summary_add;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_finish, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.finish:
                submit();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void changVisibility(String jobTypeId) {
        if (TextUtils.equals(jobTypeId, "01")) {
            llDesign.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(jobTypeId, "02")) {
            llTry.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(jobTypeId, "03")) {
            llQuality.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(jobTypeId, "04")) {
            llTech.setVisibility(View.VISIBLE);
        } else if (TextUtils.equals(jobTypeId, "05")) {
            llTender.setVisibility(View.VISIBLE);
        }
    }


    @OnClick({R.id.tv_upload, R.id.rl_quality_pro, R.id.ll_design, R.id.rl_try_pro, R.id.rl_tech_pro})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_upload:
//                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                intent.addCategory(Intent.CATEGORY_OPENABLE);
//                intent.setType("*/*");
//                startActivityForResult(intent, 10003);
                addFile();
                break;
            case R.id.ll_design:
                proDialog.show();
                break;
            case R.id.rl_try_pro:
                startActivityForResult(MesTicketProActivity.class, 10001);
                break;
            case R.id.rl_tech_pro:
                startActivityForResult(MesTicketProActivity.class, 10001);
                break;
            case R.id.rl_quality_pro:
                startActivityForResult(MesTicketProActivity.class, 10001);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == 10001) {
            choosePro = JSON.parseObject(data.getStringExtra("data"), MesProBean.ListBean.class);
            tvQualityPro.setText(choosePro.getProductName());
            tvTechPro.setText(choosePro.getProductName());
            tvTryPro.setText(choosePro.getProductName());
        } else if (requestCode == 10002 && resultCode == RESULT_OK) {
            List<Uri> dataUri = Matisse.obtainResult(data);
            for (Uri uri : dataUri) {
                upload(1, uri);
            }
        } else if (requestCode == FilePickerManager.REQUEST_CODE && resultCode == RESULT_OK) {
            List<String> annex = FilePickerManager.INSTANCE.obtainData();
            for (String annexUri : annex) {
                upload(2, annexUri);
            }
        }
    }

    private void submit() {
        if (TextUtils.equals(data.getJobTypeId(), "01")) {
            param.put("siteInvestigation", etDesign1.getText().toString());
            param.put("feasibilityReport", etDesign2.getText().toString());
        } else if (TextUtils.equals(data.getJobTypeId(), "02")) {
            param.put("experimentProcess", etTry1.getText().toString());
            param.put("experimentResult", etTry2.getText().toString());
            param.put("improveProposal", etTry3.getText().toString());
        } else if (TextUtils.equals(data.getJobTypeId(), "03")) {
            param.put("feedbackQualityIssues", etQuality1.getText().toString());
            param.put("siteUseSituation", etQuality2.getText().toString());
            param.put("causeAnalysis", etQuality3.getText().toString());
            param.put("solution", etQuality4.getText().toString());
        } else if (TextUtils.equals(data.getJobTypeId(), "04")) {
            param.put("communicativePurposes", etTech1.getText().toString());
            param.put("communicativeSituation", etTech2.getText().toString());
            param.put("reachOpinion", etTech3.getText().toString());
        } else if (TextUtils.equals(data.getJobTypeId(), "05")) {
            param.put("productDevise", etTender1.getText().toString());
            param.put("productQuotedPrice", etTender2.getText().toString());
        }
        if (!TextUtils.equals(data.getJobTypeId(), "01") && !TextUtils.equals(data.getJobTypeId(), "05")) {
            if (choosePro != null) {
                param.put("productsCode", choosePro.getProductCode());
                param.put("productsName", choosePro.getProductName());
            }
        }
        param.put("completionSituation", etClient.getText().toString());
        List<ImageBean> uploadImg =new ArrayList<>();
        for (int i = 0; i < imgList.size()-1; i++) {
            uploadImg.add(imgList.get(i));
        }
        param.put("attachments",uploadImg);
        RtfUtils.getMesRtf().summaryAdd("1", "1", WorkUtils.convertMapToBody(param)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {


            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                finish();
                EventBus.getDefault().post(new AddTicketEvent());
                EventBus.getDefault().post(new AddSummarytEvent());
                toast("提交成功");
            }
        });
    }

    private void addImg() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        // All requested permissions are granted
                        Matisse.from(MesTicketAddSummaryActivity.this)
                                .choose(MimeType.ofImage())
                                .countable(true)
                                .maxSelectable(3).capture(true).
                                captureStrategy(new CaptureStrategy(true, "com.wd.workoffice.fileprovider"))
//                                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .thumbnailScale(0.85f)
                                .imageEngine(new Glide4Engine())
                                .forResult(10002);
                    } else {
                        // At least one permission is denied
                        toast("您需要开启拍照、存储权限！");
                    }
                });
    }
    private void addFile() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        // All requested permissions are granted
                        FilePickerManager.INSTANCE
                                .from(this)
                                .forResult(FilePickerManager.REQUEST_CODE);
                    } else {
                        // At least one permission is denied
                        toast("您需要开启拍照、存储权限！");
                    }
                });
    }
    /**
     * type 1 图片 2 附件
     *
     * @param type
     * @param uri
     */
    private void upload(int type, Object uri) {
        showLoading();
        File file;
        if (uri instanceof  Uri){
            file = WorkUtils.uriToFile((Uri) uri, this);
        }
        else {
            file =new File(uri.toString());
        }
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        RtfUtils.getMesRtf().
                upload(MultipartBody.Part.createFormData("file", file.getName(), requestFile)).
                compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {

            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                toast("上传成功");
                ImageBean imageBean = new ImageBean();
                imageBean.setPath(data.getData().toString());
                imageBean.setName(file.getName());
                imageBean.setSize(FileUtils.getFileLength(file));
                imageBean.setType(data.getData().toString().split("\\.")[1]);

                if (type == 1) {
                    imgList.add(imgList.size()-1, imageBean);
                    imgAddAdapter.notifyDataSetChanged();
                    imageBean.setUri((Uri) uri);
                } else {
                    annexList.add(imageBean);
                    annexAdapter.notifyDataSetChanged();
                }
            }
        });
    }

}
