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

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.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.blankj.utilcode.util.UriUtils;
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.mesBean.FaultTypeBean;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.bean.mesBean.MesServiceCheckBillBean;
import com.wd.workoffice.bean.mesBean.ServiceBean;
import com.wd.workoffice.bean.mesBean.ServiceCheckBean;
import com.wd.workoffice.bean.mesBean.ServiceStandardBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.ImgAddAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.Glide4Engine;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
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 flexible.xd.android_base.utils.TimeUtils;
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 ServiceFaultActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_refuse)
    TextView tvRefuse;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_no)
    TextView tvNo;
    @BindView(R.id.tv_name)
    EditText tvName;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.ll_level)
    LinearLayout llLevel;
    @BindView(R.id.tv_report_name)
    TextView tvReportName;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_report_time)
    TextView tvReportTime;
    @BindView(R.id.tv_machine)
    TextView tvMachine;
    @BindView(R.id.tv_machine_location)
    TextView tvMachineLocation;
    @BindView(R.id.tv_fault_type)
    TextView tvFaultType;
    @BindView(R.id.ll_fault_type)
    LinearLayout llFaultType;
    @BindView(R.id.tv_fault_code)
    TextView tvFaultCode;
    @BindView(R.id.ll_fault_code)
    LinearLayout llFaultCode;
    @BindView(R.id.tv_stop_time)
    TextView tvStopTime;
    @BindView(R.id.tv_recover_time)
    TextView tvRecoverTime;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.tv_remark)
    EditText tvRemark;
    @BindView(R.id.tv_desc)
    EditText tvDesc;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    private ServiceStandardBean.ListBean info;
    private String[] levelList = new String[]{"一级", "二级", "三级", "四级"};
    private int chooseStatus;
    private ServiceCheckBean.ListBean data;
    private MesServiceCheckBillBean.ListBean machine;
    private QMUIDialog.MenuDialogBuilder levelDialog;
    private int chooseLevel;
    private FaultTypeBean.ListBean chooseFaultTypeBean;
    private FaultTypeBean.ListBean chooseFaultCode;
    private Map<String, Object> param;
    private Map<Integer, Object> annexMap = new HashMap<>();
    private List<ImageBean> imgList;
    private ImgAddAdapter imgAddAdapter;
    private ServiceBean.ListBean dataService;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        levelDialog = DialogUtils.listDialog(this);
        levelDialog.addItems(levelList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                tvLevel.setText(levelList[which]);
                chooseLevel = which + 1;
            }
        });
        rvData.setLayoutManager(new GridLayoutManager(this, 3, RecyclerView.VERTICAL, false));

    }

    @Override
    protected void initData() {
        getCode();
        info = JSON.parseObject(getIntent().getStringExtra("info"), ServiceStandardBean.ListBean.class);//第三，点检标准
        if (TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            data = JSON.parseObject(getIntent().getStringExtra("data"), ServiceCheckBean.ListBean.class);//最外层
        } else {
            //最外层
            dataService = JSON.parseObject(getIntent().getStringExtra("data"), ServiceBean.ListBean.class);

        }
        machine = JSON.parseObject(getIntent().getStringExtra("machine"), MesServiceCheckBillBean.ListBean.class);//第二级页面
        changeView();
        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(rvData);
    }

    private void getCode() {
        RtfUtils.getMesRtf().getNextCode("1").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;
                }
                tvNo.setText(data.getData().toString());
            }
        });
    }

    private void changeView() {

//        tvLocation.setText(data.getSiteName());

        if (TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
            tvMachine.setText(machine.getAssetName());
            tvMachineLocation.setText(machine.getLocationName());
            tvLocation.setText(data.getSiteName());
        } else {
            //最外层
//            dataService = JSON.parseObject(getIntent().getStringExtra("data"), ServiceBean.ListBean.class);
            tvMachine.setText(dataService.getAssetDesc());
            tvMachineLocation.setText(dataService.getLocationName());
            tvLocation.setText(dataService.getSiteDesc());
        }


//        if (TextUtils.isEmpty(getIntent().getStringExtra("type"))) {
//            tvDesc.setText(info.getDescription());
//            tvFailureCode.setText(info.getFailureCode());
//            tvMeasurementUnit.setText(info.getMeasurementUnit());
//            tvNumA.setText(MathUtils.converData(info.getNumA(), 3));
//            tvNumB.setText(MathUtils.converData(info.getNumB(), 3));
//            tvNumC.setText(MathUtils.converData(info.getNumC(), 3));
//            tvProcessStandard.setText(info.getProcessStandard());
//            tvStatus.setText(TextUtils.equals(info.getStatus(), "1") ? "异常" : "正常");//1 异常 0正常
//            tvRemark.setText(info.getRemarks());
//        } else {
//            tvDesc.setText(info.getInspoProDescription());
//            tvFailureCode.setText(info.getReportCode());
//            tvMeasurementUnit.setText(info.getUint());
//            tvNumA.setText(MathUtils.converData(info.getNumA(), 3));
//            tvNumB.setText(MathUtils.converData(info.getNumB(), 3));
//            tvNumC.setText(MathUtils.converData(info.getNumC(), 3));
//            tvProcessStandard.setText(info.getProcessStandard());
//            tvStatus.setText(TextUtils.equals(info.getStatus(), "1") ? "异常" : "正常");//1 异常 0正常
//            tvRemark.setText(info.getRemarks());
//        }
    }


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


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (TextUtils.equals(getIntent().getStringExtra("status"), "1")) {
            return super.onCreateOptionsMenu(menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_submit, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

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

    private void save() {
        if (TextUtils.isEmpty(tvName.getText().toString())) {
            toast("请输入故障名称");
            return;
        }
        if (chooseLevel == -1) {
            toast("请选择故障等级");
            return;
        }
        if (chooseFaultTypeBean == null) {
            toast("请选择故障类");
            return;
        }
        if (chooseFaultCode == null) {
            toast("请选择问题代码");
            return;
        }
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("phenomenonDescription", tvDesc.getText().toString());
        param.put("description", tvName.getText().toString());
        param.put("problemCode", chooseFaultCode.getFailureCode());
        param.put("problemDesc", chooseFaultCode.getDescription());
        param.put("problemId", chooseFaultCode.getId());
//        param.put("projectId", info.getProjectId());
        param.put("assetStopDateTime", tvStopTime.getText().toString());
        param.put("removeDateTime", tvRecoverTime.getText().toString());
        param.put("culevel", chooseLevel);
        param.put("remark", tvRemark.getText().toString());
        param.put("status", 1);
        param.put("reportCode", tvNo.getText().toString());
        param.put("failureId", chooseFaultTypeBean.getId());
        param.put("failureDesc", chooseFaultTypeBean.getDescription());
        param.put("failureCode", chooseFaultTypeBean.getCode());
        Observable<BaseMesBean> baseMesBeanObservable;
        if (TextUtils.isEmpty(getIntent().getStringExtra("type"))) {//点检
            param.put("siteId", data.getSiteId());
            param.put("siteDesc", data.getSiteName());
            param.put("assetId", machine.getAssetId());
            param.put("assetDesc", machine.getAssetName());
            param.put("assetCode", machine.getAssetCode());
            param.put("locaCode", machine.getLocationCode());
            param.put("locaDesc", machine.getLocationName());
            param.put("locationId", machine.getLocationId());
            param.put("appType", 2);
            baseMesBeanObservable = RtfUtils.getMesRtf().opmreporterror("00d12c310f4411ea8334fa163e1166bd", 3,
                    WorkUtils.convertMapToBody(param));

        } else {
            //最外层
            param.put("siteId", dataService.getSiteId());
            param.put("siteDesc", dataService.getSiteDesc());
//            param.put("assetCode", dataService.geta());
            param.put("assetDesc", dataService.getAssetDesc());
            param.put("assetCode", dataService.getAssetCode());
            param.put("assetId", dataService.getAssetId());
            param.put("locaCode", dataService.getLocationCode());
            param.put("locaDesc", dataService.getLocationName());
            param.put("locationId", dataService.getLocationId());
            param.put("appType", 1);
            baseMesBeanObservable = RtfUtils.getMesRtf().opmreporterror("00d12c310f4411ea8334fa163e1166bd", 3,
                    WorkUtils.convertMapToBody(param));
//            param.put("reportCode", chooseFaultTypeBean.getCode());
        }
        baseMesBeanObservable.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("保存成功");
                Intent intent = new Intent();
                intent.putExtra("data", tvNo.getText().toString());
                setResult(10001, intent);
                finish();
            }
        });
    }


    @OnClick({R.id.ll_recover_time, R.id.ll_time, R.id.ll_level, R.id.ll_fault_type, R.id.ll_fault_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_recover_time:
                PickTimeUtils.showPickThree(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                        tvRecoverTime.setText(time);
                    }
                }).show();
                break;
            case R.id.ll_time:
                PickTimeUtils.showPick(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date);
                        tvStopTime.setText(time);
                    }
                }).show();
                break;
            case R.id.ll_level:
                levelDialog.show();
                break;
            case R.id.ll_fault_type:
                startActivityForResult(MesFaultSearchActivity.class, 10001);
                break;
            case R.id.ll_fault_code:
                if (null == chooseFaultTypeBean) {
                    toast("请先选择故障类");
                    return;
                }
                startActivityForResult(MesFaultCodeSearchActivity.class, 10002,
                        "id", chooseFaultTypeBean.getId());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10001:
                if (requestCode == 10001 && resultCode == 10001) {
                    chooseFaultTypeBean = JSON.parseObject(data.getStringExtra("data"), FaultTypeBean.ListBean.class);
                    tvFaultType.setText(chooseFaultTypeBean.getDescription());
                }

                break;
            case 10002:
                if (resultCode == 10001) {
                    chooseFaultCode = JSON.parseObject(data.getStringExtra("data"), FaultTypeBean.ListBean.class);
                    tvFaultCode.setText(chooseFaultCode.getDescription());
                }
                break;
            case 10003:
                if (resultCode == RESULT_OK) {
                    List<Uri> dataUri = Matisse.obtainResult(data);
                    for (Uri uri : dataUri) {
                        upload(uri);
                    }
                }
                break;
        }
    }


    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(ServiceFaultActivity.this)
                                .choose(MimeType.ofAll())
                                .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(10003);
                    } else {
                        // At least one permission is denied
                        toast("您需要开启拍照、存储权限！");
                    }
                });
    }


    private void upload(Uri uri) {
        showLoading();
//        File file = WorkUtils.uriToFile(uri, this);
        File file;
        if (uri instanceof Uri) {
//            file = WorkUtils.uriToFile((Uri) uri, this);
            file = UriUtils.uri2File((Uri) uri);
        } else {
            file = new File(uri.toString());
        }
        File uploadFile = WorkUtils.getSmallImg(file, this);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
        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(uploadFile.getName());
                    imageBean.setSize(FileUtils.getFileLength(uploadFile));
                    imageBean.setType(data.getData().toString().split("\\.")[1]);

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

            }
        });
    }
}
