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

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
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.CheckFeedbackEvent;
import com.wd.workoffice.bean.mesBean.BoxBean;
import com.wd.workoffice.bean.mesBean.ChooseMachineBean;
import com.wd.workoffice.bean.mesBean.DefectBean;
import com.wd.workoffice.bean.mesBean.FeedbackBean;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.bean.mesBean.MesClientBean;
import com.wd.workoffice.bean.mesBean.MesProBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.mes.MesProActivity;
import com.wd.workoffice.ui.activity.mes.ticket.MesTicketClientActivity;
import com.wd.workoffice.ui.activity.mes.ticket.TicketProActivity;
import com.wd.workoffice.ui.adapter.ImgAddAdapter;
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.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
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 id.zelory.compressor.Compressor;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesQualityAddActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_client)
    TextView tvClient;
    @BindView(R.id.rl_client)
    RelativeLayout rlClient;
    @BindView(R.id.tv_manager)
    TextView tvManager;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_box)
    TextView tvBox;
    @BindView(R.id.rl_box)
    RelativeLayout rlBox;
    @BindView(R.id.tv_pro_code)
    TextView tvProCode;
    @BindView(R.id.rl_pro)
    RelativeLayout rlPro;
    @BindView(R.id.tv_pro_name)
    TextView tvProName;
    @BindView(R.id.tv_spec)
    TextView tvSpec;
    @BindView(R.id.tv_img_code)
    TextView tvImgCode;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.tv_mark_code)
    TextView tvMarkCode;
    @BindView(R.id.tv_machine)
    TextView tvMachine;
    @BindView(R.id.tv_steel)
    TextView tvSteel;
    @BindView(R.id.tv_defect)
    TextView tvDefect;
    @BindView(R.id.rl_defect)
    RelativeLayout rlDefect;
    @BindView(R.id.et_desc)
    TextView etDesc;
    @BindView(R.id.btn_add)
    Button btnAdd;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.rl_machine)
    RelativeLayout rlMachine;
    @BindView(R.id.tv_feedback_desc)
    EditText tvFeedbackDesc;
    @BindView(R.id.tv_other_supplier)
    EditText tvOtherSupplier;
    @BindView(R.id.tv_feedback_suggest)
    EditText tvFeedbackSuggest;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    private MesClientBean.ListBean chooseClient;
    private ChooseMachineBean chooseMachine;
    private Map<String, Object> param;
    private BoxBean chooseBox;
    private DefectBean.ListBean chooseDefect;
    private List<ImageBean> imgList;
    private ImgAddAdapter imgAddAdapter;
    private MesProBean.ListBean choosePro;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvImg.setLayoutManager(new GridLayoutManager(this, 3, RecyclerView.VERTICAL, false));
    }


    @Override
    protected void initData() {
        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(rvImg);
        param = WorkUtils.simpleParam();
        String data = getIntent().getStringExtra("data");
        if (!TextUtils.isEmpty(data)) {
            FeedbackBean.ListBean ticketBean = JSON.parseObject(data, FeedbackBean.ListBean.class);
            tvFeedbackDesc.setText(ticketBean.getFeedbackDescription());
            tvOtherSupplier.setText(ticketBean.getOtherProviderBehavior());
            tvFeedbackSuggest.setText(ticketBean.getSalerOpinion());
            tvMarkCode.setText(ticketBean.getSerialNumber());
            param.put("serialNumber", ticketBean.getSerialNumber());


            param.put("id", ticketBean.getId());
            chooseClient = new MesClientBean.ListBean();
            chooseClient.setCustomerCode(ticketBean.getCustomerId());
            chooseClient.setCustomerName(ticketBean.getCustomerName());
            chooseClient.setSalesManagerCode(ticketBean.getSaleUserCode());
            chooseClient.setSalesManagerName(ticketBean.getSaleUserName());
            tvClient.setText(chooseClient.getCustomerName());
//              tvPhone.setText(chooseClient.get());
            tvManager.setText(chooseClient.getSalesManagerName());
            param.put("customerId", chooseClient.getCustomerCode());
            param.put("customerName", chooseClient.getCustomerName());
            param.put("saleUserCode", chooseClient.getSalesManagerCode());
            param.put("saleUserName", chooseClient.getSalesManagerName());


            chooseMachine = new ChooseMachineBean();
            chooseMachine.setSteelTypeId(ticketBean.getSteelTypeId());
            chooseMachine.setCasterName(ticketBean.getCasterName());
            chooseMachine.setCaster(ticketBean.getCaster());
            chooseMachine.setDefectCount(ticketBean.getDefectCount() + "");
            tvMachine.setText(chooseMachine.getCaster());
            tvSteel.setText(chooseMachine.getSteelTypeId());
            etNum.setText(chooseMachine.getDefectCount());
            param.put("steelTypeId", chooseMachine.getSteelTypeId());
            param.put("casterName", chooseMachine.getCasterName());
            param.put("defectCount", chooseMachine.getDefectCount());
            param.put("caster", chooseMachine.getCaster());
            chooseBox = new BoxBean();
//            chooseBox.setSerialNumber(ticketBean.getSerialNumber());
//            chooseBox.setDrawingNumber(ticketBean.getDrawingNumber());
//            chooseBox.setSpecification(ticketBean.getSpecification() + "");
//            chooseBox.setProductCode(ticketBean.getProductCode());
//            chooseBox.setProductName(ticketBean.getProductName());
            chooseBox.setBoxNumber(ticketBean.getBoxCode());
            chooseBox.setBoxId(ticketBean.getBoxId());

//            tvProCode.setText(chooseBox.getProductCode());
//            tvProName.setText(chooseBox.getProductName());
//            tvSpec.setText(chooseBox.getSpecification());
//            tvImgCode.setText(chooseBox.getDrawingNumber());
//            tvMarkCode.setText(chooseBox.getSerialNumber());
            tvBox.setText(chooseBox.getBoxId());
//            param.put("serialNumber", chooseBox.getSerialNumber());
//            param.put("drawingNumber", chooseBox.getDrawingNumber());
//            param.put("specification", chooseBox.getSpecification());
//            param.put("productCode", chooseBox.getProductCode());
//            param.put("productName", chooseBox.getProductName());
            param.put("boxCode", chooseBox.getBoxNumber());
            param.put("boxId", chooseBox.getBoxId());


            choosePro = new MesProBean.ListBean();
            choosePro.setDrawingNumber(ticketBean.getDrawingNumber());
            choosePro.setSpecification(ticketBean.getSpecification() + "");
            choosePro.setProductCode(ticketBean.getProductCode());
            choosePro.setProductName(ticketBean.getProductName());

            tvProCode.setText(choosePro.getProductCode());
            tvProName.setText(choosePro.getProductName());
            tvSpec.setText(choosePro.getSpecification());
            tvImgCode.setText(choosePro.getDrawingNumber());
            param.put("drawingNumber", choosePro.getDrawingNumber());
            param.put("specification", choosePro.getSpecification());
            param.put("productCode", choosePro.getProductCode());
            param.put("productName", choosePro.getProductName());

            chooseDefect = new DefectBean.ListBean();
            chooseDefect.setRemark(ticketBean.getMainCause());
            chooseDefect.setDefectCode(ticketBean.getDefectCode());
            chooseDefect.setDefectName(ticketBean.getDefectName());

            tvDefect.setText(chooseDefect.getDefectName());
            etDesc.setText(chooseDefect.getRemark());
            param.put("mainCause", chooseDefect.getRemark());
            param.put("defectCode", chooseDefect.getDefectCode());
            param.put("defectName", chooseDefect.getDefectName());
        }
        if (TextUtils.isEmpty(getIntent().getStringExtra("data"))) {
            if (WorkUtils.hasMesMenuPermission(JSON.parseArray(getIntent().getStringExtra("permission")), "新建")) {
                btnAdd.setVisibility(View.VISIBLE);
            }
        } else {
            btnSubmit.setVisibility(View.VISIBLE);
        }
    }


    @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 (imgList.size() > 9) {
                    toast("最大上传9张");
                    return;
                }
                if (position == imgList.size() - 1) {
                    addImg();
                }
            }
        });
    }

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


    @OnClick({R.id.rl_mark_code, R.id.btn_add, R.id.btn_submit, R.id.rl_machine, R.id.rl_client, R.id.rl_box, R.id.rl_defect,
            R.id.rl_pro})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                submit();
                break;
            case R.id.btn_submit:
                if (chooseClient == null) {
                    toast("请先选择客户");
                    break;
                }
                if (chooseMachine == null) {
                    toast("请先选择连铸机");
                    break;
                }
//                if (chooseBox == null) {
//                    toast("请先选择箱号");
//                    break;
//                }
//                if (chooseDefect == null) {
//                    toast("请先选择缺陷");
//                    break;
//                }
//                param.put("", "");
                submit();
                break;
            case R.id.rl_mark_code:
                startActivityForResult(MesQualityChooseMarkActivity.class,
                        10006);
                break;
            case R.id.rl_client:
                startActivityForResult(MesTicketClientActivity.class,
                        10001);
                break;
            case R.id.rl_machine:
                if (chooseClient == null) {
                    toast("请先选择客户");
                    return;
                }
                startActivityForResult(MesChooseMachineActivity.class,
                        10002, "code", chooseClient.getCustomerCode());
                break;
            case R.id.rl_pro:
                if (chooseClient == null) {
                    toast("请先选择客户");
                    return;
                }
                startActivityForResult(TicketProActivity.class,
                        10005, "code", chooseClient.getCustomerCode());
                break;
            case R.id.rl_box:
                if (chooseClient == null) {
                    toast("请先选择客户");
                    return;
                }
                startActivityForResult(MesChooseBoxActivity.class,
                        10003, "code", chooseClient.getCustomerCode());
                break;
            case R.id.rl_defect:
                if (chooseBox == null) {
                    toast("请先选择箱号");
                    return;
                }
                startActivityForResult(MesChooseDefectActivity.class,
                        10004, "code", chooseBox.getBasketId());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == 10001) {
            chooseClient = JSON.parseObject(data.getStringExtra("data"), MesClientBean.ListBean.class);
            tvClient.setText(chooseClient.getCustomerName());
//            tvPhone.setText(chooseClient.get());
            tvManager.setText(chooseClient.getSalesManagerName());
            param.put("customerId", chooseClient.getCustomerCode());
            param.put("customerName", chooseClient.getCustomerName());
            param.put("saleUserCode", chooseClient.getSalesManagerCode());
            param.put("saleUserName", chooseClient.getSalesManagerName());
            getPhone(chooseClient.getCustomerCode());
        } else if (requestCode == 10002 && resultCode == 10001) {
            chooseMachine = JSON.parseObject(data.getStringExtra("data"), ChooseMachineBean.class);
            tvMachine.setText(chooseMachine.getCaster());
            tvSteel.setText(chooseMachine.getSteelTypeId());
//            etNum.setText(chooseMachine.getDefectCount());
            param.put("steelTypeId", chooseMachine.getSteelTypeId());
            param.put("casterName", chooseMachine.getCasterName());
            param.put("defectCount", chooseMachine.getDefectCount());
            param.put("caster", chooseMachine.getCaster());
        } else if (requestCode == 10003 && resultCode == 10001) {
            chooseBox = JSON.parseObject(data.getStringExtra("data"), BoxBean.class);
//            tvProCode.setText(chooseBox.getProductCode());
//            tvProName.setText(chooseBox.getProductName());
//            tvSpec.setText(chooseBox.getSpecification());
//            tvImgCode.setText(chooseBox.getDrawingNumber());
//            tvMarkCode.setText(chooseBox.getSerialNumber());
            tvBox.setText(chooseBox.getBoxId());
//            param.put("serialNumber", chooseBox.getSerialNumber());
//            param.put("drawingNumber", chooseBox.getDrawingNumber());
//            param.put("specification", chooseBox.getSpecification());
//            param.put("productCode", chooseBox.getProductCode());
//            param.put("productName", chooseBox.getProductName());
            param.put("boxCode", chooseBox.getBoxNumber());
            param.put("boxId", chooseBox.getBoxId());
        } else if (requestCode == 10004 && resultCode == 10001) {
            chooseDefect = JSON.parseObject(data.getStringExtra("data"), DefectBean.ListBean.class);
            tvDefect.setText(chooseDefect.getDefectName());
            etDesc.setText(chooseDefect.getRemark());
            param.put("mainCause", chooseDefect.getRemark());
            param.put("defectCode", chooseDefect.getDefectCode());
            param.put("defectName", chooseDefect.getDefectName());
        } else if (requestCode == 10005 && resultCode == 10001) {
            choosePro = JSON.parseObject(data.getStringExtra("data"), MesProBean.ListBean.class);
            tvProCode.setText(choosePro.getProductCode());
            tvProName.setText(choosePro.getProductName());
            tvSpec.setText(choosePro.getSpecification());
            tvImgCode.setText(choosePro.getDrawingNumber());
//            tvMarkCode.setText(choosePro.get());
            param.put("serialNumber", chooseBox.getSerialNumber());
            param.put("drawingNumber", chooseBox.getDrawingNumber());
            param.put("specification", chooseBox.getSpecification());
            param.put("productCode", chooseBox.getProductCode());
            param.put("productName", chooseBox.getProductName());
        } else if (requestCode == 10006 && resultCode == 10001) {
            String chooseMarkCode = data.getStringExtra("data");
            tvMarkCode.setText(chooseMarkCode);
            param.put("serialNumber", chooseMarkCode);
        } else if (requestCode == 10002 && resultCode == RESULT_OK) {
            List<Uri> dataUri = Matisse.obtainResult(data);
            for (Uri uri : dataUri) {
                upload(uri);
            }
        }
    }

    private void getPhone(String customerCode) {
        Map<String, Object> phontParam = WorkUtils.pageMesKey();
        phontParam.put("pageNum", 1);
        Map<String, Object> paramMap = WorkUtils.simpleParam();
        paramMap.put("customerCode", customerCode);
        phontParam.put("paramMap", paramMap);
        RtfUtils.getMesRtf().clientPhoneList("1", WorkUtils.convertMapToBody(phontParam)).
                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()) {
                    return;
                }
                JSONArray dataList = JSON.parseObject(data.getData().toString()).getJSONArray("list");
                if (dataList.size() != 0) {
                    JSONObject userData = dataList.getJSONObject(0);
                    tvPhone.setText(userData.getString("telephone"));
                    param.put("phoneNumber", userData.getString("telephone"));
                }
            }
        });
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_finish_save, menu);
//        return super.onCreateOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.finish:
//                if (chooseClient == null) {
//                    toast("请先选择客户");
//                    break;
//                }
//                if (chooseMachine == null) {
//                    toast("请先选择连铸机");
//                    break;
//                }
//                if (chooseBox == null) {
//                    toast("请先选择箱号");
//                    break;
//                }
//                if (chooseDefect == null) {
//                    toast("请先选择缺陷");
//                    break;
//                }
//                submit();
//                break;
//            case R.id.save:
//                submit();
//                break;
//        }
//        return super.onOptionsItemSelected(item);
//    }

    private void submit() {
        String feedback = tvFeedbackDesc.getText().toString();
        String otherSupplier = tvOtherSupplier.getText().toString();
        String feedbackSuggest = tvFeedbackSuggest.getText().toString();
        if (TextUtils.isEmpty(feedback)) {
            toast("请输入反馈信息详细描述");
            return;
        }
        if (TextUtils.isEmpty(otherSupplier)) {
            toast("其他供货厂家及使用情况");
            return;
        }
        if (TextUtils.isEmpty(feedbackSuggest)) {
            toast("分析及建议");
            return;
        }
        param.put("feedbackDescription", feedback);
        param.put("otherProviderBehavior", otherSupplier);
        param.put("salerOpinion", feedbackSuggest);
        param.put("defectCount", etNum.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);
        Observable<BaseMesBean> observable;
        if (TextUtils.isEmpty(getIntent().getStringExtra("data"))) {
            param.put("status", "1");
            observable = RtfUtils.getMesRtf().feedbackAdd("1", WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getMesRtf().startFeedback("6628708f85d111ea8334fa163e1166bd", WorkUtils.convertMapToBody(param));
        }
        observable.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;
                }
                EventBus.getDefault().post(new CheckFeedbackEvent());
                toast("新增成功");
                finish();
            }
        });
    }

    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(MesQualityAddActivity.this)
                                .choose(MimeType.ofImage())
                                .countable(true)
                                .maxSelectable(9).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("您需要开启拍照、存储权限！");
                    }
                });
    }

    /**
     * @param uri
     */
    private void upload(Object uri) {
        showLoading();
        File file;
        if (uri instanceof Uri) {
//            file = WorkUtils.uriToFile((Uri) uri, this);
            file = UriUtils.uri2File((Uri) uri);
        } else {
            file = new File(uri.toString());
        }
        File smallImg = WorkUtils.getSmallImg(file, this);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),smallImg );
        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;
                }
                if (imgList.size() < 10) {
                    toast("上传成功");
                    ImageBean imageBean = new ImageBean();
                    imageBean.setPath(data.getData().toString());
                    imageBean.setName(smallImg.getName());
                    imageBean.setSize(FileUtils.getFileLength(smallImg));
                    imageBean.setType(data.getData().toString().split("\\.")[1]);

                    imgList.add(imgList.size() - 1, imageBean);
                    imgAddAdapter.notifyDataSetChanged();
                    imageBean.setUri((Uri) uri);
                }

            }
        });
    }

}
